You are here

class FieldValidationRuleSetEditForm in Field Validation 8

Controller for blocktabs edit form.

Hierarchy

Expanded class hierarchy of FieldValidationRuleSetEditForm

File

src/Form/FieldValidationRuleSetEditForm.php, line 15

Namespace

Drupal\field_validation\Form
View source
class FieldValidationRuleSetEditForm extends FieldValidationRuleSetFormBase {

  /**
   * The fieldValidationRule manager service.
   *
   * @var \Drupal\field_validation\FieldValidationRuleManager
   */
  protected $fieldValidationRuleManager;

  /**
   * Constructs an FieldValidationRuleSetEditForm object.
   *
   * @param \Drupal\Core\Entity\EntityStorageInterface $entity_storage
   *   The storage.
   * @param \Drupal\field_validation\FieldValidationRuleManager $field_validation_rule_manager
   *   The field_validation_rule manager service.
   */
  public function __construct(EntityStorageInterface $entity_storage, FieldValidationRuleManager $field_validation_rule_manager) {
    parent::__construct($entity_storage);
    $this->fieldValidationRuleManager = $field_validation_rule_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager')
      ->getStorage('field_validation_rule_set'), $container
      ->get('plugin.manager.field_validation.field_validation_rule'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $user_input = $form_state
      ->getUserInput();
    $form['#title'] = $this
      ->t('Edit field validation rule set %name', array(
      '%name' => $this->entity
        ->label(),
    ));
    $form['#tree'] = TRUE;

    //$form['#attached']['library'][] = 'field_validation/admin';

    // Build the list of existing field validation rule for this rule set.
    $form['rules'] = [
      '#type' => 'table',
      '#header' => [
        $this
          ->t('Title'),
        $this
          ->t('Weight'),
        $this
          ->t('Plugin'),
        $this
          ->t('Field'),
        $this
          ->t('Operations'),
      ],
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'rule-order-weight',
        ],
      ],
      '#attributes' => [
        'id' => 'field-validation-rule-set-rules',
      ],
      '#empty' => $this
        ->t('There are currently no rules in this rule set. Add one by selecting an option below.'),
      // Render tabs below parent elements.
      '#weight' => 5,
    ];
    $field_validation_rules = $this->entity
      ->getFieldValidationRules();

    //drupal_set_message(var_export($field_validation_rules, true));
    foreach ($field_validation_rules as $field_validation_rule) {

      //drupal_set_message('abcd');
      $key = $field_validation_rule
        ->getUuid();
      $form['rules'][$key]['#attributes']['class'][] = 'draggable';
      $form['rules'][$key]['#weight'] = isset($user_input['rules']) ? $user_input['rules'][$key]['weight'] : NULL;
      $form['rules'][$key]['rule'] = [
        '#tree' => FALSE,
        'data' => [
          'label' => [
            '#plain_text' => $field_validation_rule
              ->label(),
          ],
        ],
      ];

      //$form['rules'][$key]['field_name'] = [

      //  '#markup' => $field_validation_rule->getFieldName(),

      //];

      //$summary = $field_validation_rule->getSummary();

      //if (!empty($summary)) {

      //  $summary['#prefix'] = ' ';
      //  $form['rules'][$key]['rule']['data']['summary'] = $summary;

      //}
      $form['rules'][$key]['weight'] = [
        '#type' => 'weight',
        '#title' => $this
          ->t('Weight for @title', [
          '@title' => $field_validation_rule
            ->label(),
        ]),
        '#title_display' => 'invisible',
        '#default_value' => $field_validation_rule
          ->getWeight(),
        '#attributes' => [
          'class' => [
            'rule-order-weight',
          ],
        ],
      ];
      $form['rules'][$key]['id'] = [
        '#markup' => $field_validation_rule
          ->getPluginId(),
      ];
      $form['rules'][$key]['field'] = [
        '#type' => 'markup',
        '#markup' => $field_validation_rule
          ->getFieldName(),
      ];
      $links = [];
      $is_configurable = $field_validation_rule instanceof ConfigurableFieldValidationRuleInterface;
      if ($is_configurable) {
        $links['edit'] = [
          'title' => $this
            ->t('Edit'),
          'url' => Url::fromRoute('field_validation.field_validation_rule_edit_form', [
            'field_validation_rule_set' => $this->entity
              ->id(),
            'field_validation_rule' => $key,
          ]),
        ];
      }
      $links['delete'] = [
        'title' => $this
          ->t('Delete'),
        'url' => Url::fromRoute('field_validation.field_validation_rule_delete', [
          'field_validation_rule_set' => $this->entity
            ->id(),
          'field_validation_rule' => $key,
        ]),
      ];
      $form['rules'][$key]['operations'] = [
        '#type' => 'operations',
        '#links' => $links,
      ];
    }

    // Build the new field_validation_rule addition form and add it to the field_validation_rule list.
    $new_field_validation_rule_options = [];
    $field_validation_rules = $this->fieldValidationRuleManager
      ->getDefinitions();

    //drupal_set_message(var_export($field_validation_rules, true));
    uasort($field_validation_rules, function ($a, $b) {
      return strcasecmp($a['id'], $b['id']);
    });
    foreach ($field_validation_rules as $field_validation_rule => $definition) {
      $new_field_validation_rule_options[$field_validation_rule] = $definition['label'];
    }
    $form['rules']['new'] = [
      '#tree' => FALSE,
      '#weight' => isset($user_input['weight']) ? $user_input['weight'] : NULL,
      '#attributes' => [
        'class' => [
          'draggable',
        ],
      ],
    ];
    $form['rules']['new']['rule'] = [
      'data' => [
        'new' => [
          '#type' => 'select',
          '#title' => $this
            ->t('Rule'),
          '#title_display' => 'invisible',
          '#options' => $new_field_validation_rule_options,
          '#empty_option' => $this
            ->t('Select a new rule'),
        ],
        [
          'add' => [
            '#type' => 'submit',
            '#value' => $this
              ->t('Add'),
            '#validate' => [
              '::fieldValidationRuleValidate',
            ],
            '#submit' => [
              '::submitForm',
              '::fieldValidationRuleSave',
            ],
          ],
        ],
      ],
      '#prefix' => '<div class="field-validation-rule-new">',
      '#suffix' => '</div>',
    ];
    $form['rules']['new']['weight'] = [
      '#type' => 'weight',
      '#title' => $this
        ->t('Weight for new rule'),
      '#title_display' => 'invisible',
      '#default_value' => count($this->entity
        ->getFieldValidationRules()) + 1,
      '#attributes' => [
        'class' => [
          'rule-order-weight',
        ],
      ],
    ];
    $form['rules']['new']['operations'] = [
      'data' => [],
    ];
    return parent::form($form, $form_state);
  }

  /**
   * Validate handler for fieldValidationRule.
   */
  public function fieldValidationRuleValidate($form, FormStateInterface $form_state) {
    if (!$form_state
      ->getValue('new')) {
      $form_state
        ->setErrorByName('new', $this
        ->t('Select an rule to add.'));
    }
  }

  /**
   * Submit handler for fieldValidationRule.
   */
  public function fieldValidationRuleSave($form, FormStateInterface $form_state) {
    $this
      ->save($form, $form_state);

    // Check if this field has any configuration options.
    $field_validation_rule = $this->fieldValidationRuleManager
      ->getDefinition($form_state
      ->getValue('new'));

    // Load the configuration form for this option.
    if (is_subclass_of($field_validation_rule['class'], '\\Drupal\\field_validation\\ConfigurableFieldValidationRuleInterface')) {

      // Remove the destination parameter as it redirects us back to the
      // overview.
      $this
        ->getRequest()->query
        ->remove('destination');
      $form_state
        ->setRedirect('field_validation.field_validation_rule_add_form', [
        'field_validation_rule_set' => $this->entity
          ->id(),
        'field_validation_rule' => $form_state
          ->getValue('new'),
      ], [
        'query' => [
          'weight' => $form_state
            ->getValue('weight'),
        ],
      ]);
    }
    else {
      $field_validation_rule = [
        'id' => $field_validation_rule['id'],
        'data' => [],
        'weight' => $form_state
          ->getValue('weight'),
      ];
      $field_validation_rule_id = $this->entity
        ->addFieldValidationRule($field_validation_rule);
      $this->entity
        ->save();
      if (!empty($tab_id)) {
        $this
          ->messenger()
          ->addMessage($this
          ->t('The rule was successfully added.'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Update tab weights.
    if (!$form_state
      ->isValueEmpty('rules')) {
      $this
        ->updateFieldValidationRuleWeights($form_state
        ->getValue('rules'));
    }
    parent::submitForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    parent::save($form, $form_state);
    $this
      ->messenger()
      ->addMessage($this
      ->t('Changes to the field validation rule set have been saved.'));
  }

  /**
   * {@inheritdoc}
   */
  public function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this
      ->t('Update field validation rule set');
    return $actions;
  }

  /**
   * Updates fieldValidationRule weights.
   *
   * @param array $field_validation_rules
   *   Associative array with tabs having fieldValidationRule uuid as keys and array
   *   with fieldValidationRule data as values.
   */
  protected function updateFieldValidationRuleWeights(array $field_validation_rules) {
    foreach ($field_validation_rules as $uuid => $field_validation_rule_data) {
      if ($this->entity
        ->getFieldValidationRules()
        ->has($uuid)) {
        $this->entity
          ->getFieldValidationRule($uuid)
          ->setWeight($field_validation_rule_data['weight']);
      }
    }
  }

}

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
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
FieldValidationRuleSetEditForm::$fieldValidationRuleManager protected property The fieldValidationRule manager service.
FieldValidationRuleSetEditForm::actions public function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
FieldValidationRuleSetEditForm::create public static function Instantiates a new instance of this class. Overrides FieldValidationRuleSetFormBase::create
FieldValidationRuleSetEditForm::fieldValidationRuleSave public function Submit handler for fieldValidationRule.
FieldValidationRuleSetEditForm::fieldValidationRuleValidate public function Validate handler for fieldValidationRule.
FieldValidationRuleSetEditForm::form public function Gets the actual form array to be built. Overrides FieldValidationRuleSetFormBase::form
FieldValidationRuleSetEditForm::save public function Form submission handler for the 'save' action. Overrides FieldValidationRuleSetFormBase::save
FieldValidationRuleSetEditForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm
FieldValidationRuleSetEditForm::updateFieldValidationRuleWeights protected function Updates fieldValidationRule weights.
FieldValidationRuleSetEditForm::__construct public function Constructs an FieldValidationRuleSetEditForm object. Overrides FieldValidationRuleSetFormBase::__construct
FieldValidationRuleSetFormBase::$entity protected property The entity being used by this form. Overrides EntityForm::$entity
FieldValidationRuleSetFormBase::$entityStorage protected property The block tabs entity storage.
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::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.
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.