I have a custom field that extends the ImageField to add a checkbox to the image, similarly to how the image field contains a text field for title and alt information. I can get the checkbox to appear and save values as they show on the formatter page ok, but I cannot figure out how to get the default value for the checkbox. My code initializes the checkbox in formElement function:
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$field_settings=$this->getFieldSettings();
// Setup how the show_image field is shown on the node edit form.
$element['#show_image'] = $field_settings["show_image"];
return $element;
}
And then creates the checkbox field when the file is uploaded and the process callback function is called:
/**
* {@inheritdoc}
*
* This is a callback from formElement. For example, this could be triggered from an ajax call.
*/
public static function process($element, FormStateInterface $form_state, $form) {
$item = $element['#value'];
$item['fids'] = $element['fids']['#value'];
$element["show_image"] = array(
'#default_value' => $element['#show_image'],
'#type' => 'checkbox',
'#title' => t('Show image on website'),
'#description' => t('This may be from an external source. Show on the website?'),
'#weight' => 10,
'#access' => (bool) $item['fids']
);
return parent::process($element, $form_state, $form);
}
After changing the #default_value key, I can't seem to have the form both display the default setting of "checked" on new uploads, and show the correct value that is saved in previously saved nodes. For example, if I set the
#default_value=>$element['#show_image']
I always get the default value, no matter what the user saves. If I set it like this:
isset($item['show_image']) ? $item['show_image'] : $element['#show_image']
It always shows the saved value, and never the default, even on new uploads. So my question is, how do I show both the default value for new uploads and the saved value for updates?