You are here

class MultiNodeAddForm in Multi Node Add 8

Form to launch Multi Node Add process.

Hierarchy

Expanded class hierarchy of MultiNodeAddForm

1 string reference to 'MultiNodeAddForm'
multi_node_add.routing.yml in ./multi_node_add.routing.yml
multi_node_add.routing.yml

File

src/Form/MultiNodeAddForm.php, line 13

Namespace

Drupal\multi_node_add\Form
View source
class MultiNodeAddForm extends FormBase {

  /**
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'multi-node-add';
  }

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param Drupal\Core\Form\FormStateInterface $form_state
   *   Current state of the form.
   * @param Drupal\node\NodeTypeInterface $node_type
   *   Selected node type.
   *
   * @return array
   *   The form structure.
   */
  public function buildForm(array $form, FormStateInterface $form_state, NodeTypeInterface $node_type = NULL) {
    global $base_path;
    $form['#attached']['drupalSettings']['multiNodeAdd'] = [
      'callback' => $base_path . Url::fromRoute('multi_node_add.frame', [
        'node_type' => $node_type
          ->getOriginalId(),
        'fields' => '#fields',
      ], [
        'absolute' => TRUE,
      ])
        ->getInternalPath(),
    ];
    $prefilled = FALSE;
    if (isset($_GET['fields']) && isset($_GET['num'])) {
      $form['#attached']['drupalSettings']['multiNodeAdd'] = [
        'multiNodeAddPreload' => [
          'fields' => explode(',', $_GET['fields']),
          'num' => $_GET['num'],
        ],
      ];
      $prefilled = TRUE;
    }
    if (!$prefilled) {
      $fields = \Drupal::entityManager()
        ->getFieldDefinitions('node', $node_type
        ->get('type'));
      $req_val = [];
      $field_req = [];
      $field_names = [];
      foreach ($fields as $field_name => $entry) {
        if (!$entry
          ->isReadOnly() && !$entry
          ->isComputed()) {
          if ($entry
            ->isRequired()) {
            $field_req[$field_name] = $entry
              ->getLabel();
            $req_val[$field_name] = $field_name;
          }
          else {
            $field_names[$field_name] = $entry
              ->getLabel();
          }
        }
      }
      $form['#attached']['library'][] = 'multi_node_add/multi_node_add';
      $form['hint']['#markup'] = '<div class="warning messages js">' . t('Multi Node Add requires Javascript to provide the needed functionality') . '</div>';
      $form['info']['#value'] = t('Current content-type: %type', [
        '%type' => $node_type
          ->label(),
      ]);
      if (!empty($field_req)) {
        $form['fields_req'] = [
          '#type' => 'checkboxes',
          '#options' => $field_req,
          '#default_value' => $req_val,
          '#title' => t('Mandatory fields'),
          '#attributes' => [
            'class' => [
              'multi-node-add',
            ],
          ],
          '#disabled' => TRUE,
        ];
      }
      if (!empty($field_names)) {
        $form['fields_to_utilize'] = [
          '#type' => 'checkboxes',
          '#options' => $field_names,
          '#title' => t('Fields to manage'),
          '#attributes' => [
            'class' => [
              'multi-node-add',
            ],
          ],
          '#description' => t('Choose those fields that you would like to edit on the new nodes'),
        ];
      }

      // If there are no available fields, we should not offer a form.
      if (empty($field_names) && empty($field_req)) {
        drupal_set_message(t('Unable to generate multiple nodes for this content type (failed to detect usable fields).'), 'warning');
        return $form;
      }
      $form['number'] = [
        '#type' => 'textfield',
        '#default_value' => 2,
        '#size' => 2,
        '#required' => TRUE,
        '#title' => t('Number of rows'),
      ];
      $form['show'] = [
        '#type' => 'button',
        '#value' => t('Show'),
      ];
      $form['shortcut'] = [
        '#type' => 'button',
        '#value' => t('Get shortcut URL'),
      ];
    }
    $common_attr = [
      '#attributes' => [
        'class' => [
          'second-step',
        ],
      ],
    ];
    $form['addmore'] = [
      '#type' => 'button',
      '#value' => t('Add 2 more nodes'),
    ] + $common_attr;
    $form['create'] = [
      '#type' => 'button',
      '#value' => t('Create all nodes'),
    ] + $common_attr;
    $form['prepopulate'] = [
      '#type' => 'button',
      '#value' => t('Prepopulate based on first form'),
    ] + $common_attr;
    $form['placeholder']['#markup'] = '<div id="multi_node_add_frames"></div>';
    return $form;
  }

  /**
   * Form submission handler.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // This form never gets submitted, really.
    // Everything is handled by Javascript.
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
MultiNodeAddForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
MultiNodeAddForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MultiNodeAddForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.