You are here

class EditForm in bootstrap simple carousel 8

Class EditForm.

Add/edit form.

@package Drupal\bootstrap_simple_carousel\Form

Hierarchy

Expanded class hierarchy of EditForm

1 string reference to 'EditForm'
bootstrap_simple_carousel.routing.yml in ./bootstrap_simple_carousel.routing.yml
bootstrap_simple_carousel.routing.yml

File

src/Form/EditForm.php, line 20

Namespace

Drupal\bootstrap_simple_carousel\Form
View source
class EditForm extends FormBase {

  /**
   * The database connection object.
   *
   * @var \Drupal\bootstrap_simple_carousel\CarouselItemStorage
   */
  protected $carouselItemStorage;

  /**
   * The catousel service.
   *
   * @var \Drupal\bootstrap_simple_carousel\Service\CarouselService
   */
  protected $carouselService;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity.
   *
   * @var \Drupal\bootstrap_simple_carousel\Entity\CarouselItem
   */
  protected $entity;

  /**
   * The logger.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'bootstrap_simple_carousel_edit_form';
  }

  /**
   * Constructs a \Drupal\system\ConfigFormBase object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\bootstrap_simple_carousel\Service\CarouselService $carouselService
   *   The CarouselService.
   * @param \Drupal\Core\Logger\LoggerChannelInterface $logger
   *   Logger.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, CarouselService $carouselService, LoggerChannelInterface $logger) {
    $this->carouselItemStorage = $entity_type_manager
      ->getStorage('bootstrap_simple_carousel');
    $this->entityTypeManager = $entity_type_manager;
    $this->carouselService = $carouselService;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('bootstrap_simple_carousel.carousel_service'), $container
      ->get('logger.channel.bootstrap_simple_carousel'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $id = NULL) {
    $this->entity = $this->carouselItemStorage
      ->create();
    if (is_numeric($id)) {
      $this->entity = $this->carouselItemStorage
        ->load($id);
    }
    if (!$this->entity
      ->isNew()) {
      $form['cid'] = [
        '#type' => 'hidden',
        '#required' => FALSE,
        '#default_value' => $this->entity
          ->id(),
      ];
      $form['image_preview'] = [
        '#markup' => $this->carouselService
          ->renderImageById($this->entity
          ->getImageId()),
        '#suffix' => '<br><b>NOTE: You can\'t change image, just remove\\set inactive the item and create new one</b>',
      ];
    }
    else {
      $form['image_id'] = [
        '#type' => 'managed_file',
        '#title' => $this
          ->t('Image'),
        '#upload_validators' => [
          'file_validate_extensions' => [
            'gif png jpg jpeg',
          ],
          'file_validate_size' => [
            25600000,
          ],
        ],
        '#upload_location' => 'public://bootstrap_simple_carousel/',
        '#required' => !$this->entity
          ->isNew(),
        '#default_value' => !$this->entity
          ->isNew() ? $this->entity
          ->getImageId() : '',
      ];
    }
    $form['image_title'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Image title'),
      '#required' => FALSE,
      '#default_value' => !$this->entity
        ->isNew() ? $this->entity
        ->getImageTitle() : '',
    ];
    $form['image_alt'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Image alt'),
      '#required' => FALSE,
      '#default_value' => !$this->entity
        ->isNew() ? $this->entity
        ->getImageAlt() : '',
    ];
    $form['image_link'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Image link'),
      '#description' => $this
        ->t('For instance: `https://example.com`, `node/1`, `about`'),
      '#required' => FALSE,
      '#default_value' => !$this->entity
        ->isNew() ? $this->entity
        ->getImageLink() : '',
    ];
    $form['caption_title'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Caption title'),
      '#required' => FALSE,
      '#default_value' => !$this->entity
        ->isNew() ? $this->entity
        ->getCaptionTitle() : '',
    ];
    $form['caption_text'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Caption text'),
      '#required' => FALSE,
      '#default_value' => !$this->entity
        ->isNew() ? $this->entity
        ->getCaptionText() : '',
    ];
    $form['status'] = [
      '#type' => 'select',
      '#title' => 'Status',
      '#options' => $this->carouselService
        ->getStatuses(),
      '#default_value' => !$this->entity
        ->isNew() ? $this->entity
        ->getStatus() : '',
    ];
    $form['weight'] = [
      '#type' => 'number',
      '#title' => 'Weight',
      '#required' => FALSE,
      '#default_value' => !$this->entity
        ->isNew() ? $this->entity
        ->getWeight() : 0,
    ];
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!in_array($form_state
      ->getValue('status'), [
      0,
      1,
    ])) {
      $form_state
        ->setErrorByName('status', $this
        ->t('Status is incorrect.'));
    }
    if ($form_state
      ->getValue('weight') < 0) {
      $form_state
        ->setErrorByName('status', $this
        ->t('Weight must be zero or greater than zero.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if (!empty($form_state
      ->getValue('image_id'))) {
      $file = $this->entityTypeManager
        ->getStorage('file')
        ->load(current($form_state
        ->getValue('image_id')));
      $file
        ->setPermanent();
      $file
        ->save();
    }
    $form_state
      ->cleanValues();
    foreach ($form_state
      ->getValues() as $field => $value) {
      $this->entity
        ->set($field, $value);
    }
    try {
      $messageStatus = MessengerInterface::TYPE_STATUS;
      $this->entity
        ->save();
      $message = $this
        ->t('Item successfully saved!');
    } catch (\Exception $e) {
      $message = $this
        ->t('Record was not saved!') . $e
        ->getMessage();
      $messageStatus = MessengerInterface::TYPE_ERROR;
      $this->logger
        ->error('Can not save carousel item: ' . $e
        ->getMessage(), [
        'exception' => $e,
        'data' => $form_state
          ->getValues(),
      ]);
    }
    $this
      ->messenger()
      ->addMessage($message, $messageStatus);
    $form_state
      ->setRedirect('bootstrap_simple_carousel.table');
  }

}

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
EditForm::$carouselItemStorage protected property The database connection object.
EditForm::$carouselService protected property The catousel service.
EditForm::$entity protected property The entity.
EditForm::$entityTypeManager protected property The entity type manager.
EditForm::$logger protected property The logger.
EditForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
EditForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
EditForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
EditForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
EditForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
EditForm::__construct public function Constructs a \Drupal\system\ConfigFormBase object.
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.
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.