0

I am trying add new field to image widget using hook_field_widget_form_alter

Bellow is the code:

function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
     $element[0]['custom'] = array(
     '#type' => 'textfield',
     '#title' => 'Custom Field',
     '#default_value' => FALSE,
    );
}

But it add a new field to first image always. I'm expecting the custom field with each image as Alt & Title fields are showing for each image. enter image description here

If I remove the [0] index like:

      $element['custom']

or

    $element[]['custom']

it show an error, and show the field bellow image field not with Alt & Title field.

Notice: Undefined index: #file in theme_file_widget_multiple() (line 861 of C:\xampp\htdocs\drupal39\modules\file\file.field.inc).

I also try with [#process][] way:

function MYMODULE_field_widget_form_alter(&$element, &$form_state, &$context) {
if (isset($element['#field_name']) && $element['#field_name'] == 'field_gallery_image') {
      foreach (element_children($element) as $key => $child) {
          $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
      }
    }
}


function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
$element['custom'] = array(
    '#title' => t('Custom Field'),
    '#type' => 'textfield',
    '#default_value' => isset($item['custom']) ? $item['custom'] : '',
    '#weight' => 1,
);
return $element;
}

This way the Custom field is adding to all images but create one EXTRA custom field bellow the Image field.

enter image description here

0

I put element in IF condition in MYMODULE_image_field_widget_process and it works fine. What it does is, it checks for ALT attribute if it is ENABLED so it will then add the CUSTOM field, you can instead add the CUSTOM field visibility option in image setting page and check for that.

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
   if ($element['alt']['#access']) { // IF condition added here
      $element['custom'] = array(
        '#title' => t('Custom Field'),
        '#type' => 'textfield',
        '#default_value' => isset($item['custom']) ? $item['custom'] : '',
        '#weight' => 1,
      );
   }
   return $element;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.