You are here

function auto_entitylabel_form_alter in Automatic Entity Label 8

Same name and namespace in other branches
  1. 8.3 auto_entitylabel.module \auto_entitylabel_form_alter()
  2. 8.2 auto_entitylabel.module \auto_entitylabel_form_alter()
  3. 7 auto_entitylabel.module \auto_entitylabel_form_alter()

Implements hook_form_alter().

File

./auto_entitylabel.module, line 48
Allows hiding of entity label fields and automatic label creation.

Code

function auto_entitylabel_form_alter(&$form, FormStateInterface $form_state) {
  if (isset($form['#entity_builders']) && empty($form['#auto_entitylabel_processed'])) {
    $decorator = \Drupal::service('auto_entitylabel.entity_decorator');

    /** @var \Drupal\auto_entitylabel\AutoEntityLabelManager $entity */
    $entity = $decorator
      ->decorate($form_state
      ->getFormObject()
      ->getEntity());
    if ($entity instanceof AutoEntityLabelManagerInterface) {
      if ($entity
        ->hasAutoLabel()) {
        $label = $entity
          ->getLabelName();
        $widget =& $form[$label]['widget'][0];

        // Hide the label field. It will be automatically generated in
        // hook_entity_presave().
        $widget['value']['#type'] = 'hidden';
        $widget['value']['#required'] = FALSE;
        if (empty($widget['value']['#default_value'])) {
          $widget['value']['#default_value'] = '%AutoEntityLabel%';
        }
      }
      else {
        if ($entity
          ->hasOptionalAutoLabel()) {
          $label = $entity
            ->getLabelName();
          $widget =& $form[$label]['widget'][0];

          // Allow label field to be empty. It will be automatically generated
          // in hook_entity_presave().
          $widget['value']['#required'] = FALSE;
        }
      }
      $form['#auto_entitylabel_processed'] = TRUE;
    }
  }
}