You are here

class BUEditorButtonForm in BUEditor 8

Same name and namespace in other branches
  1. 8.2 src/Form/BUEditorButtonForm.php \Drupal\bueditor\Form\BUEditorButtonForm

Base form for BUEditor Button entities.

Hierarchy

Expanded class hierarchy of BUEditorButtonForm

File

src/Form/BUEditorButtonForm.php, line 11

Namespace

Drupal\bueditor\Form
View source
class BUEditorButtonForm extends EntityForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $bueditor_button = $this
      ->getEntity();

    // Check duplication
    if ($this
      ->getOperation() === 'duplicate') {
      $bueditor_button = $bueditor_button
        ->createDuplicate();
      $bueditor_button
        ->set('label', $this
        ->t('Duplicate of @label', [
        '@label' => $bueditor_button
          ->label(),
      ]));
      $this
        ->setEntity($bueditor_button);
    }

    // Label
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Name'),
      '#default_value' => $bueditor_button
        ->label(),
      '#maxlength' => 64,
      '#required' => TRUE,
    ];

    // Id
    $id = $bueditor_button
      ->id();
    $form['id'] = [
      '#type' => 'machine_name',
      '#machine_name' => [
        'exists' => [
          get_class($bueditor_button),
          'load',
        ],
        'source' => [
          'label',
        ],
      ],
      '#default_value' => $id && strpos($id, 'custom_') === 0 ? substr($id, 7) : $id,
      '#maxlength' => 32,
      '#required' => TRUE,
      '#field_prefix' => 'custom_',
    ];

    // Template button
    $code = $bueditor_button
      ->get('code');
    $template = $bueditor_button
      ->get('template');
    $js_info = $this
      ->t('If the code starts with <code>js:</code> it is executed as javascript inside <code>function(E, $){...}</code> where <code>E</code> is the editor instance, and <code>$</code> is JQuery. Ex: <code>js: console.log(this, E, $);</code>');
    $template_checked = [
      ':input[name="is_template"]' => [
        'checked' => TRUE,
      ],
    ];
    $template_unchecked = [
      ':input[name="is_template"]' => [
        'checked' => FALSE,
      ],
    ];
    $form['is_template'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('This is a template button'),
      '#default_value' => $template && !$code,
    ];
    $form['template_button'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Template button'),
      '#description' => $this
        ->t('A template button is used for inserting a custom element into toolbar.'),
      '#open' => TRUE,
      '#states' => [
        'visible' => $template_checked,
      ],
    ];

    // Template
    $form['template_button']['template'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Template'),
      '#default_value' => $template,
      '#description' => $this
        ->t('Html template that will be inserted into toolbar.') . '<br />' . $js_info,
      '#states' => [
        'required' => $template_checked,
      ],
    ];

    // Normal button
    $form['button'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Button properties'),
      '#open' => TRUE,
      '#states' => [
        'visible' => $template_unchecked,
      ],
    ];

    // Code
    $form['button']['code'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Code'),
      '#default_value' => $code,
      '#description' => $this
        ->t('Text to insert into editor textarea. Ex: <code>&lt;strong&gt;|&lt;/strong&gt;</code>. The vertical bar <strong>|</strong> represents the cursor position or the selected text in the textarea.') . '<br />' . $js_info,
      '#states' => [
        'required' => $template_unchecked,
      ],
    ];

    // Button text
    $form['button']['text'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Button text'),
      '#default_value' => $bueditor_button
        ->get('text'),
      '#description' => $this
        ->t('A text label or html icon for the button element.'),
    ];

    // Tooltip
    $form['button']['tooltip'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Tooltip'),
      '#default_value' => $bueditor_button
        ->get('tooltip'),
      '#description' => $this
        ->t('Descriptive text displayed on button hover.'),
    ];

    // Class name
    $form['button']['cname'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Class name'),
      '#default_value' => $bueditor_button
        ->get('cname'),
      '#description' => $this
        ->t('Additional class name for the button element.') . '<br />' . $this
        ->t('Font icon class can be used as <code>ficon-NAME</code> where <code>NAME</code> is one of %names.', [
        '%names' => 'bold, italic, underline, strike, image, link, quote, code, ul, ol, table, template, undo, redo, preview, help',
      ]),
    ];

    // Class name
    $form['button']['shortcut'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Shortcut'),
      '#default_value' => $bueditor_button
        ->get('shortcut'),
      '#description' => $this
        ->t('Button shortcut as a combination of Modifier keys (<kbd>Ctrl</kbd>, <kbd>Alt</kbd>, <kbd>Shift</kbd>) and Alphanumeric keys(<kbd>0-9</kbd>, <kbd>A-Z</kbd>) or special keys like Back space(<kbd>BACKSPACE</kbd>), Tabulator(<kbd>TAB</kbd>), Return(<kbd>ENTER</kbd>), Escape(<kbd>ESC</kbd>), Space(<kbd>SPACE</kbd>), Arrow keys(<kbd>LEFT|RIGHT|UP|DOWN</kbd>), Function keys(<kbd>F1-F12</kbd>).') . '<br />' . $this
        ->t('Example shortcuts: <kbd>Ctrl+M</kbd>, <kbd>Alt+Shift+5</kbd>, <kbd>Ctrl+Shift+ENTER</kbd>.') . '<br />' . $this
        ->t('Make sure not to override default shortcuts like <kbd>Ctrl+A|C|V|X</kbd> which are critical for text editing.'),
    ];

    // Libraries
    $form['libraries'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Required libraries'),
      '#default_value' => implode(', ', $bueditor_button
        ->get('libraries')),
      '#description' => $this
        ->t('Comma separated list of required drupal libraries for the button. Ex: core/drupal.progress, node/drupal.node.preview'),
    ];

    // Add demo
    if (!$bueditor_button
      ->isNew()) {
      $bueditor_editor = \Drupal::entityTypeManager()
        ->getStorage('bueditor_editor')
        ->create([
        'id' => '_button_demo',
        'settings' => [
          'toolbar' => [
            $bueditor_button
              ->id(),
          ],
        ],
      ]);
      $attached['library'] = $bueditor_editor
        ->getLibraries();
      $attached['drupalSettings']['bueditor']['demoSettings'] = $bueditor_editor
        ->getJSSettings();
      $form['demo'] = [
        '#type' => 'text_format',
        '#base_type' => 'textarea',
        '#title' => $this
          ->t('Demo'),
        '#weight' => 1000,
        '#attributes' => [
          'class' => [
            'bueditor-demo',
          ],
        ],
        '#attached' => $attached,
        '#editor' => FALSE,
        '#input' => FALSE,
        '#value' => NULL,
      ];
    }

    // Add library
    $form['#attached']['library'][] = 'bueditor/drupal.bueditor.admin';
    return parent::form($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $bueditor_button = $this
      ->getEntity();
    $values = $form_state
      ->getValues();

    // Add ID prefix
    if (!$form_state
      ->getError($form['id'])) {
      $id = 'custom_' . $values['id'];
      $form_state
        ->setValue('id', $id);

      // Check duplicate.  Entity contains the submitted values
      if ($id != $bueditor_button
        ->getOriginalId()) {
        if ($bueditor_button
          ->load($id)) {
          $form_state
            ->setError($form['id'], $this
            ->t('The machine-readable name is already in use. It must be unique.'));
        }
      }
    }

    // Template button
    if (!empty($values['is_template'])) {
      $form_state
        ->setValue('code', '');
    }
    else {
      $form_state
        ->setValue('template', '');

      // Check class name
      if (!empty($values['cname']) && preg_match('/[^a-zA-Z0-9\\-_ ]/', $values['cname'])) {
        $form_state
          ->setErrorByName('cname', $this
          ->t('@field contains invalid characters.', [
          '@field' => $this
            ->t('Class name'),
        ]));
      }

      // Check shortcut
      if (!empty($values['shortcut']) && preg_match('/[^a-zA-Z0-9\\+]/', $values['shortcut'])) {
        $form_state
          ->setErrorByName('shortcut', $this
          ->t('@field contains invalid characters.', [
          '@field' => $this
            ->t('Shortcut'),
        ]));
      }
    }

    // Convert libraries to array.
    if (isset($values['libraries']) && is_string($values['libraries'])) {
      $form_state
        ->setValue('libraries', array_values(array_filter(array_map('trim', explode(',', $values['libraries'])))));
    }
    return parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $bueditor_button = $this
      ->getEntity();
    $status = $bueditor_button
      ->save();
    if ($status == SAVED_NEW) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('Button %name has been added.', [
        '%name' => $bueditor_button
          ->label(),
      ]));
    }
    elseif ($status == SAVED_UPDATED) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('The changes have been saved.'));
    }
    $form_state
      ->setRedirect('entity.bueditor_button.edit_form', [
      'bueditor_button' => $bueditor_button
        ->id(),
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BUEditorButtonForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
BUEditorButtonForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
BUEditorButtonForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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::$entity protected property The entity being used by this form. 7
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::actions protected function Returns an array of supported actions for the current entity form. 29
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::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 FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
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.
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.