You are here

class AjaxToggleForm in Toggle Editable fields 8

Build a form to switch state of targeted FieldItem.

Hierarchy

Expanded class hierarchy of AjaxToggleForm

1 file declares its use of AjaxToggleForm
ToggleEditableFormatter.php in src/Plugin/Field/FieldFormatter/ToggleEditableFormatter.php

File

src/Form/AjaxToggleForm.php, line 14

Namespace

Drupal\toggle_editable_fields\Form
View source
class AjaxToggleForm extends FormBase {

  /**
   * The FieldItem being targeted by this form.
   *
   * @var \Drupal\Core\Field\FieldItemInterface
   */
  protected $fieldItem;

  /**
   * The FieldDefinition being targeted by this form.
   *
   * @var \Drupal\Core\Field\FieldDefinitionInterface
   */
  protected $fieldDefinition;

  /**
   * The entity being used by this form.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $entity;

  /**
   * The current FieldItem name.
   *
   * @var string
   */
  protected $fieldName;

  /**
   * The current FieldItem delta.
   *
   * @var int
   */
  protected $delta;

  /**
   * Default value of current FieldItem.
   *
   * @var bool
   */
  protected $defaultValue;

  /**
   * The field item plugin settings.
   *
   * @var array
   */
  protected $fieldSettings;

  /**
   * Initialize this Form Builder with FieldItem definition.
   *
   * Drupal only supports one form with a given ID per page,
   * so we generate a fieldItem specific ID at getFormId().
   *
   * @param \Drupal\Core\Field\FieldItemInterface $item
   *   FieldItem to be displayed.
   * @param array $settings
   *   The formatter settings.
   */
  public function setFieldItem(FieldItemInterface $item, array $settings = []) {
    $this->fieldItem = $item;
    $this->fieldDefinition = $item
      ->getFieldDefinition();
    $this->entity = $this->fieldItem
      ->getEntity();
    $this->fieldName = $this->fieldDefinition
      ->getName();
    $this->delta = $this->fieldItem
      ->getName();
    $this->defaultValue = $this->fieldItem->value;
    $this->fieldSettings = $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    $parts = [
      'editable_ajax_toggle',
      $this->entity
        ->getEntityTypeId(),
      $this->entity
        ->id(),
      $this->fieldName,
      $this->delta,
      'form',
    ];
    return implode('_', $parts);
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#tree'] = TRUE;
    $form['checkbox'] = [
      '#type' => 'checkbox',
      '#default_value' => $this->defaultValue,
      '#attributes' => [
        'data-toggle' => 'toggle',
        'class' => [
          'checkbox-toggle',
        ],
      ],
      '#ajax' => [
        'callback' => [
          $this,
          'formListAjax',
        ],
        'event' => 'change',
        'progress' => [
          'type' => 'none',
        ],
      ],
      '#disabled' => !($this
        ->fieldIsEditable() || $this
        ->checkEditFieldAccess()),
    ];

    // Add library.
    $form['#attached']['library'][] = 'toggle_editable_fields/bootstrap.toogle';
    $this
      ->setBooststrapDataAttributes($form['checkbox']);
    return $form;
  }

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

  /**
   * Update the clicked field with given value.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The current AjaxResponse.
   *
   * @throws \Exception
   *   Thrown when the entity can't found the clicked field name.
   */
  public function formListAjax(array &$form, FormStateInterface $form_state) {
    $element = $form_state
      ->getTriggeringElement();
    if (!empty($element)) {
      $this
        ->updateFieldValue($form_state
        ->getValue($element['#parents']));
    }
    return new AjaxResponse();
  }

  /**
   * Update the clicked field with given value.
   *
   * @param bool $value
   *   Value given by user.
   *
   * @throws \Exception
   *   Thrown when the entity can't found the clicked field name.
   */
  public function updateFieldValue($value) {
    if (!$this->entity
      ->hasField($this->fieldName)) {
      throw new \Exception("No field {$this->fieldName} found in {$this->entity->id()} entity.");
    }
    if ($this
      ->fieldIsEditable() || $this
      ->checkEditFieldAccess()) {
      $this->entity
        ->get($this->fieldName)
        ->set($this->delta, $value);
      $this->entity
        ->save();
    }
  }

  /**
   * Set booststrap data attributes for given element.
   *
   * @param array $element
   *   An associative array containing the part of the form structure,
   *   representing checkbox element.
   */
  public function setBooststrapDataAttributes(array &$element) {
    foreach ($this->fieldSettings as $data_id => $data_value) {
      if ($data_value != NULL && !isset($element['#attributes']["data-{$data_id}"])) {
        $element['#attributes']["data-{$data_id}"] = $data_value;
      }
    }
  }

  /**
   * Check if the combo of entity + field access are satisfased.
   *
   * @return bool
   *   True if current user can edit the entity AND have access to current field.
   */
  public function fieldIsEditable() {
    return $this->entity
      ->access('update') && $this
      ->checkEditFieldAccess();
  }

  /**
   * Check only the access of the 'edit' operation for current field.
   *
   * @return bool
   *   True if current user can edit that field or FALSE.
   */
  public function checkEditFieldAccess() {
    $permission_type = $this->fieldDefinition instanceof FieldConfigInterface ? $this->fieldDefinition
      ->getFieldStorageDefinition()
      ->getThirdPartySetting('field_permissions', 'permission_type') : NULL;
    $field_access = \Drupal::entityTypeManager()
      ->getAccessControlHandler($this->entity
      ->getEntityTypeId())
      ->fieldAccess('edit', $this->fieldDefinition, \Drupal::currentUser(), $this->fieldItem
      ->getParent());
    if ($field_access && empty($permission_type)) {
      return $this->entity
        ->access('update');
    }
    return $field_access;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AjaxToggleForm::$defaultValue protected property Default value of current FieldItem.
AjaxToggleForm::$delta protected property The current FieldItem delta.
AjaxToggleForm::$entity protected property The entity being used by this form.
AjaxToggleForm::$fieldDefinition protected property The FieldDefinition being targeted by this form.
AjaxToggleForm::$fieldItem protected property The FieldItem being targeted by this form.
AjaxToggleForm::$fieldName protected property The current FieldItem name.
AjaxToggleForm::$fieldSettings protected property The field item plugin settings.
AjaxToggleForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
AjaxToggleForm::checkEditFieldAccess public function Check only the access of the 'edit' operation for current field.
AjaxToggleForm::fieldIsEditable public function Check if the combo of entity + field access are satisfased.
AjaxToggleForm::formListAjax public function Update the clicked field with given value.
AjaxToggleForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AjaxToggleForm::setBooststrapDataAttributes public function Set booststrap data attributes for given element.
AjaxToggleForm::setFieldItem public function Initialize this Form Builder with FieldItem definition.
AjaxToggleForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
AjaxToggleForm::updateFieldValue public function Update the clicked field with given value.
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.
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.