class AjaxToggleForm in Toggle Editable fields 8
Build a form to switch state of targeted FieldItem.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\toggle_editable_fields\Form\AjaxToggleForm
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\FormView 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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
AjaxToggleForm:: |
protected | property | Default value of current FieldItem. | |
AjaxToggleForm:: |
protected | property | The current FieldItem delta. | |
AjaxToggleForm:: |
protected | property | The entity being used by this form. | |
AjaxToggleForm:: |
protected | property | The FieldDefinition being targeted by this form. | |
AjaxToggleForm:: |
protected | property | The FieldItem being targeted by this form. | |
AjaxToggleForm:: |
protected | property | The current FieldItem name. | |
AjaxToggleForm:: |
protected | property | The field item plugin settings. | |
AjaxToggleForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
|
AjaxToggleForm:: |
public | function | Check only the access of the 'edit' operation for current field. | |
AjaxToggleForm:: |
public | function | Check if the combo of entity + field access are satisfased. | |
AjaxToggleForm:: |
public | function | Update the clicked field with given value. | |
AjaxToggleForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
AjaxToggleForm:: |
public | function | Set booststrap data attributes for given element. | |
AjaxToggleForm:: |
public | function | Initialize this Form Builder with FieldItem definition. | |
AjaxToggleForm:: |
public | function |
Form submission handler. Overrides FormInterface:: |
|
AjaxToggleForm:: |
public | function | Update the clicked field with given value. | |
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
public static | function |
Instantiates a new instance of this class. Overrides ContainerInjectionInterface:: |
87 |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
FormBase:: |
public | function |
Form validation handler. Overrides FormInterface:: |
62 |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |