You are here

class AnimateAnyForm in Animate Any 8

Provides the Animate Any form.

Hierarchy

Expanded class hierarchy of AnimateAnyForm

1 string reference to 'AnimateAnyForm'
animate_any.routing.yml in ./animate_any.routing.yml
animate_any.routing.yml

File

src/Form/AnimateAnyForm.php, line 11

Namespace

Drupal\animate_any\Form
View source
class AnimateAnyForm extends FormBase {

  /**
   * Function to get Form ID.
   */
  public function getFormId() {
    return 'animate_any_form';
  }

  /**
   * Build Animate Any Setting Form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Fetch animate.css from library.
    $animate_css = DRUPAL_ROOT . '/libraries/animate.css/animate.css';

    // Check animate.css file exists.
    if (!file_exists($animate_css)) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('animate.css library is missing.'), 'warning');
    }

    // Building add more form element to add animation.
    $form['#attached']['library'][] = 'animate_any/animate';
    $form['parent_class'] = [
      '#title' => $this
        ->t('Add Parent Class / ID'),
      '#description' => $this
        ->t('You can add body class like <em>body.front (for front page)</em> OR class with dot(.) prefix and Id with hash(#) prefix.'),
      '#type' => 'textfield',
    ];
    $form['#tree'] = TRUE;
    $form['animate_fieldset'] = [
      '#prefix' => '<div id="item-fieldset-wrapper">',
      '#suffix' => '</div>',
      '#tree' => TRUE,
      '#theme' => 'table',
      '#header' => [],
      '#rows' => [],
      '#attributes' => [
        'class' => 'animation',
      ],
    ];
    $field_deltas = $form_state
      ->get('field_deltas');
    if (is_null($field_deltas)) {
      $field_deltas = \NULL;
      $form_state
        ->set('field_deltas', $field_deltas);
    }
    if (!\is_null($field_deltas)) {
      for ($delta = 0; $delta < $field_deltas; $delta++) {
        $section_identity = [
          '#title' => $this
            ->t('Add section class/Id'),
          '#description' => $this
            ->t('Add class with dot(.) prefix and Id with hash(#) prefix.'),
          '#type' => 'textfield',
          '#size' => 20,
        ];
        $section_event = [
          '#title' => $this
            ->t('Select event'),
          '#type' => 'select',
          '#options' => animate_on_event(),
          '#attributes' => [
            'class' => [
              'select_event',
            ],
          ],
        ];
        $section_animation = [
          '#title' => $this
            ->t('Select animation'),
          '#type' => 'select',
          '#options' => animate_any_options(),
          '#attributes' => [
            'class' => [
              'select_animate',
            ],
          ],
        ];
        $animation = [
          '#markup' => 'ANIMATE ANY',
          '#prefix' => '<h1 id="animate" class="" style="font-size: 30px;">',
          '#suffix' => '</h1>',
        ];
        $remove = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Remove'),
          '#submit' => [
            '::animate_any_custom_add_more_remove_one',
          ],
          '#ajax' => [
            'callback' => '::animate_any_custom_remove_callback',
            'wrapper' => 'item-fieldset-wrapper',
          ],
          '#name' => 'remove_name_' . $delta,
        ];
        $form['animate_fieldset'][$delta] = [
          'section_identity' => &$section_identity,
          'section_event' => &$section_event,
          'section_animation' => &$section_animation,
          'animation' => &$animation,
          'remove' => &$remove,
        ];
        $form['animate_fieldset']['#rows'][$delta] = [
          [
            'data' => &$section_identity,
          ],
          [
            'data' => &$section_event,
          ],
          [
            'data' => &$section_animation,
          ],
          [
            'data' => &$animation,
          ],
          [
            'data' => &$remove,
          ],
        ];
        unset($section_identity);
        unset($section_event);
        unset($section_animation);
        unset($animation);
        unset($remove);
      }
    }
    $form['instruction'] = [
      '#markup' => '<strong>Click on <i>Add item</i> button to add animation section.</strong>',
      '#prefix' => '<div class="form-item">',
      '#suffix' => '</div>',
    ];

    // Add more button with ajax callback.
    $form['add'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Add Item'),
      '#submit' => [
        '::animate_any_custom_add_more_add_one',
      ],
      '#ajax' => [
        'callback' => '::animate_any_custom_add_more_callback',
        'wrapper' => 'item-fieldset-wrapper',
      ],
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save Settings'),
    ];
    return $form;
  }

  /**
   * Validate for Animate Any Settings Form.
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $op = (string) $form_state
      ->getValue('op');
    if ($op == $this
      ->t('Save Settings')) {
      $parent = $form_state
        ->getValue('parent_class');
      if (empty($parent)) {
        $form_state
          ->setRebuild();
        $form_state
          ->setErrorByName("parent_class", $this
          ->t("Please select parent class"));
      }
      foreach ($form_state
        ->getValue('animate_fieldset') as $key => $value) {
        if (empty($value['section_identity'])) {
          $form_state
            ->setRebuild();
          $form_state
            ->setErrorByName("animate_fieldset][{$key}][section_identity", $this
            ->t("Please select section identity for row @key", [
            '@key' => $key,
          ]));
        }
        if ($value['section_event'] == 'none') {
          $form_state
            ->setRebuild();
          $form_state
            ->setErrorByName("animate_fieldset][{$key}][section_event", $this
            ->t("Please select section event for row @key", [
            '@key' => $key,
          ]));
        }
        if ($value['section_animation'] == 'none') {
          $form_state
            ->setRebuild();
          $form_state
            ->setErrorByName("animate_fieldset][{$key}][section_animation", $this
            ->t("Please select section animation for row @key", [
            '@key' => $key,
          ]));
        }
      }
    }
  }

  /**
   * Submit for Animate Any Settings Form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $op = (string) $form_state
      ->getValue('op');
    if ($op == $this
      ->t('Save Settings')) {
      $parent = $form_state
        ->getValue('parent_class');
      $identifiers = json_encode($form_state
        ->getValue('animate_fieldset'));
      $db = \Drupal::database();
      $db
        ->insert('animate_any_settings')
        ->fields([
        'parent' => $parent,
        'identifier' => $identifiers,
      ])
        ->execute();
      $this
        ->messenger()
        ->addMessage($this
        ->t('Animation added for @parent.', [
        '@parent' => $parent,
      ]));
    }
  }

  /**
   * Implements Add more Callback.
   */
  public function animate_any_custom_add_more_callback(array $form, FormStateInterface $form_state) {
    return $form['animate_fieldset'];
  }

  /**
   * Implements Remove Animate Callback.
   */
  public function animate_any_custom_remove_callback(array $form, FormStateInterface $form_state) {
    return $form['animate_fieldset'];
  }

  /**
   * Submit handler for the "add-one-more" button.
   */
  public function animate_any_custom_add_more_add_one(array $form, FormStateInterface $form_state) {
    $max = $form_state
      ->get('field_deltas') + 1;
    $form_state
      ->set('field_deltas', $max);
    $form_state
      ->setRebuild();
  }

  /**
   * Submit handler for the "remove" button.
   */
  public function animate_any_custom_add_more_remove_one(array $form, FormStateInterface $form_state) {
    $field_deltas = $form_state
      ->get('field_deltas');
    if ($field_deltas > 0) {
      $remove_one = $field_deltas - 1;
      $form_state
        ->set('field_deltas', $remove_one);
    }
    $form_state
      ->setRebuild();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AnimateAnyForm::animate_any_custom_add_more_add_one public function Submit handler for the "add-one-more" button.
AnimateAnyForm::animate_any_custom_add_more_callback public function Implements Add more Callback.
AnimateAnyForm::animate_any_custom_add_more_remove_one public function Submit handler for the "remove" button.
AnimateAnyForm::animate_any_custom_remove_callback public function Implements Remove Animate Callback.
AnimateAnyForm::buildForm public function Build Animate Any Setting Form. Overrides FormInterface::buildForm
AnimateAnyForm::getFormId public function Function to get Form ID. Overrides FormInterface::getFormId
AnimateAnyForm::submitForm public function Submit for Animate Any Settings Form. Overrides FormInterface::submitForm
AnimateAnyForm::validateForm public function Validate for Animate Any Settings Form. 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
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.