You are here

function image_replace_form_field_config_edit_form_alter in Image Replace 8

Implements hook_form_FORM_ID_alter() for 'field_config_edit_form'.

Add per image-field instance settings for image style replacement.

File

./image_replace.module, line 21
Provides an image style effect replacing the whole image with another one.

Code

function image_replace_form_field_config_edit_form_alter(&$form, &$form_state, $form_id) {
  $field = $form_state
    ->getFormObject()
    ->getEntity();
  if ($field
    ->getType() == 'image') {
    $form['third_party_settings']['image_replace'] = [
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#title' => t('Image replace'),
      '#description' => t('Use another image when rendered with certain image styles.'),
      '#weight' => 99,
      '#tree' => TRUE,
      '#element_validate' => [
        'image_replace_form_field_config_edit_form_element_validate',
      ],
    ];
    $image_field_options = array_map(function ($replacement_field) {
      return $replacement_field
        ->label();
    }, _image_replace_image_fields($field
      ->getTargetEntityTypeId(), $field
      ->getTargetBundle()));
    unset($image_field_options[$field
      ->getName()]);
    $image_style_map = $field
      ->getThirdPartySetting('image_replace', 'image_style_map', []);
    foreach (_image_replace_style_options() as $image_style => $label) {
      $default_value = isset($image_style_map[$image_style]['source_field']) ? $image_style_map[$image_style]['source_field'] : NULL;
      $form['third_party_settings']['image_replace']['image_style_map'][$image_style]['source_field'] = [
        '#type' => 'select',
        '#title' => $label,
        '#description' => t('The image field to use as a source when rendered with the %style image style.', [
          '%style' => $label,
        ]),
        '#options' => $image_field_options,
        '#default_value' => $default_value,
        '#empty_value' => FALSE,
      ];
      if ($default_value) {
        $form['third_party_settings']['image_replace']['#collapsed'] = FALSE;
      }
    }
  }
}