You are here

public function MessageTemplateMultipleTextField::textField in Message 8

Return the message text element.

File

src/FormElement/MessageTemplateMultipleTextField.php, line 51

Class

MessageTemplateMultipleTextField
Helper class to construct a multiple text field form.

Namespace

Drupal\message\FormElement

Code

public function textField(&$form, FormStateInterface $form_state, $text = []) {

  // Creating the container.
  $form['text'] = [
    '#type' => 'container',
    '#tree' => TRUE,
    '#theme' => 'field_multiple_value_form',
    '#cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
    '#cardinality_multiple' => TRUE,
    '#field_name' => 'message_text',
    '#title' => t('Message text'),
    '#description' => t('Please enter the message text.'),
    '#prefix' => '<div id="message-text">',
    '#suffix' => '</div>',
  ];
  if (\Drupal::moduleHandler()
    ->moduleExists('token')) {
    $form['token_tree'] = [
      '#theme' => 'token_tree_link',
      '#token_types' => 'all',
      '#show_restricted' => TRUE,
      '#theme_wrappers' => [
        'form_element',
      ],
    ];
  }
  $form['add_more'] = [
    '#type' => 'button',
    '#value' => t('Add another item'),
    '#href' => '',
    '#add_more' => TRUE,
    '#ajax' => [
      'callback' => $this->callback,
      'wrapper' => 'message-text',
    ],
  ];

  // Building the multiple form element; Adding first the the form existing
  // text.
  $start_key = 0;
  foreach ($this->entity
    ->get('text') as $item) {
    $form['text'][$start_key] = $this
      ->singleElement($start_key, $item);
    $start_key++;
  }

  // Increase number of elements if requested, or none exist.
  $trigger_element = $form_state
    ->getTriggeringElement();
  if (!empty($trigger_element['#add_more']) || !$start_key) {
    $form['text'][] = $this
      ->singleElement($start_key + 1, [
      'value' => '',
    ]);
  }
}