You are here

public function BulkUpdateFieldsForm::buildForm in Bulk Update Fields 8.2

Same name and namespace in other branches
  1. 8 src/Form/BulkUpdateFieldsForm.php \Drupal\bulk_update_fields\Form\BulkUpdateFieldsForm::buildForm()

Form constructor.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The form structure.

Overrides FormInterface::buildForm

File

src/Form/BulkUpdateFieldsForm.php, line 170

Class

BulkUpdateFieldsForm
BulkUpdateFieldsForm.

Namespace

Drupal\bulk_update_fields\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {
  if (isset($this->form)) {
    $form = $this->form;
  }
  $form['#title'] = $this
    ->t('Bulk Update Fields');
  $submit_label = 'Next';
  switch ($this->step) {
    case 1:

      // Retrieve IDs from the temporary storage.
      $this->userInput['entities'] = $this->tempStoreFactory
        ->get('bulk_update_fields_ids')
        ->get($this->currentUser
        ->id());
      $options = [];

      // Exclude some base fields.
      // TODO add date fields and revision log.
      $excluded_base_fields = [
        'nid',
        'uuid',
        'vid',
        'type',
        'revision_uid',
        'title',
        'path',
        'menu_link',
        'status',
        'uid',
        'default_langcode',
        'revision_timestamp',
        'revision_log',
        'created',
        'changed',
        'pass',
        'name',
        'mail',
        'init',
      ];
      $excluded_fields = $this
        ->config('bulk_update_fields.settings')
        ->get('exclude');

      // Make it possible to bulk update 'Generate automatic URL alias'.
      // @todo: add code to remove 'URL alias'.
      if (\Drupal::moduleHandler()
        ->moduleExists('pathauto')) {
        if (($key = array_search('path', $excluded_base_fields)) !== FALSE) {
          unset($excluded_base_fields[$key]);
        }
      }
      foreach ($this->userInput['entities'] as $index => $entity) {
        $langcode = explode(':', $index)[1];
        $entity = $entity
          ->getTranslation($langcode);
        $this->entity = $entity;
        $fields = $entity
          ->getFieldDefinitions();
        foreach ($fields as $field) {
          if (!in_array($field
            ->getName(), $excluded_base_fields) && !isset($options[$field
            ->getName()])) {
            if (!in_array($field
              ->getName(), array_filter($excluded_fields))) {
              $options[$field
                ->getName()]['field_name'] = $field
                ->getLabel() ? $field
                ->getLabel() : $field
                ->getName();
            }
          }
        }
      }
      $header = [
        'field_name' => $this
          ->t('Field Name'),
      ];
      $form['#title'] .= ' - ' . $this
        ->t('Select Fields to Alter');
      $form['table'] = [
        '#type' => 'tableselect',
        '#header' => $header,
        '#options' => $options,
        '#empty' => $this
          ->t('No fields found'),
      ];
      break;
    case 2:
      foreach ($this->userInput['entities'] as $index => $entity) {
        $langcode = explode(':', $index)[1];
        $entity = $entity
          ->getTranslation($langcode);
        $this->entity = $entity;
        foreach ($this->userInput['fields'] as $field_name) {
          $temp_form_element = [];
          $temp_form_state = new FormState();
          $temp_form_state
            ->setFormObject($form_state
            ->getFormObject());
          if ($field = $entity
            ->getFieldDefinition($field_name)) {

            // TODO Dates fields are incorrect due to TODOs below.
            if ($field
              ->getType() == 'datetime') {
              $type = \Drupal::service('plugin.manager.field.widget');
              $plugin_definition = $type
                ->getDefinition('datetime_default');
              $widget = new DateTimeWidgetBase('datetime', $plugin_definition, $entity
                ->get($field_name)
                ->getFieldDefinition(), [], []);
              $form['#parents'] = [];
              $form['default_value_input'][$field_name] = $widget
                ->form($entity
                ->get($field_name), $form, $form_state);
            }
            elseif ($field
              ->getType() == 'entity_reference_revisions') {

              // TODO - allow other types of entity_reference_revisions
              // currently paragraphs only.
              $type = \Drupal::service('plugin.manager.field.widget');
              $plugin_definition = $type
                ->getDefinition('paragraphs');
              $widget = new ParagraphsWidget('paragraphs', $plugin_definition, $entity
                ->get($field_name)
                ->getFieldDefinition(), [], []);
              $form['#parents'] = [];
              $form['default_value_input'][$field_name] = $widget
                ->form($entity
                ->get($field_name), $form, $form_state);
              if ($form_state
                ->getTriggeringElement()['#name'] != 'op') {
                $paragraph_type = $form_state
                  ->getTriggeringElement()['#bundle_machine_name'];
                $form_state
                  ->set('paragraph_type', $paragraph_type);
              }
            }
            else {

              // TODO
              // I cannot figure out how to get a form element for only a
              // field. Maybe someone else can.
              // TODO Doing it this way does not allow for feild labels on
              // textarea widgets.
              $form[$field_name] = $entity
                ->get($field_name)
                ->defaultValuesForm($temp_form_element, $temp_form_state);
            }
          }
        }
      }
      $form['#title'] .= ' - ' . $this
        ->t('Enter New Values in Appropriate Fields');
      break;
    case 3:
      $form['#title'] .= ' - ' . $this
        ->t('Are you sure you want to alter @count_fields fields on @count_entities entities?', [
        '@count_fields' => count($this->userInput['fields']),
        '@count_entities' => count($this->userInput['entities']),
      ]);
      $submit_label = 'Update Fields';
      break;
  }
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => $submit_label,
    '#button_type' => 'primary',
  ];
  return $form;
}