You are here

class FullcalendarEventManagerForm in Booking and Availability Management Tools for Drupal 8

Hierarchy

Expanded class hierarchy of FullcalendarEventManagerForm

File

modules/bat_fullcalendar/src/Form/FullcalendarEventManagerForm.php, line 23
Contains \Drupal\bat_fullcalendar\Form\FullcalendarEventManagerForm.

Namespace

Drupal\bat_fullcalendar\Form
View source
class FullcalendarEventManagerForm extends FormBase {

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

  /**
   * The entity field manager service.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Constructs a new FullcalendarEventManagerForm.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
   *   The entity manager.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   */
  public function __construct(EntityTypeManagerInterface $entity_manager, EntityFieldManagerInterface $entity_field_manager, RendererInterface $renderer) {
    $this->entityTypeManager = $entity_manager;
    $this->entityFieldManager = $entity_field_manager;
    $this->renderer = $renderer;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $entity_id = 0, $event_type = 0, $event_id = 0, $start_date = 0, $end_date = 0) {
    if (!isset($form_state
      ->getUserInput()['form_id'])) {
      $form_state
        ->getUserInput()['form_id'] = '';
    }
    $new_event_id = $event_id;
    if ($form_state
      ->getValue('change_event_status')) {
      $new_event_id = $form_state
        ->getValue('change_event_status');
    }
    $form['#attributes']['class'][] = 'bat-management-form bat-event-form';

    // This entire form element will be replaced whenever 'changethis' is updated.
    $form['#prefix'] = '<div id="replace_textfield_div">';
    $form['#suffix'] = '</div>';
    $form['entity_id'] = [
      '#type' => 'hidden',
      '#value' => $entity_id,
    ];
    $form['event_type'] = [
      '#type' => 'hidden',
      '#value' => $event_type
        ->id(),
    ];
    $form['event_id'] = [
      '#type' => 'hidden',
      '#value' => $event_id,
    ];
    $form['bat_start_date'] = [
      '#type' => 'hidden',
      '#value' => $start_date
        ->format('Y-m-d H:i:s'),
    ];
    $form['bat_end_date'] = [
      '#type' => 'hidden',
      '#value' => $end_date
        ->format('Y-m-d H:i:s'),
    ];
    $unit = $this->entityTypeManager
      ->getStorage($event_type
      ->getTargetEntityType())
      ->load($entity_id);
    $form['event_title'] = [
      '#prefix' => '<h2>',
      '#markup' => t('@unit_name', [
        '@unit_name' => $unit
          ->label(),
      ]),
      '#suffix' => '</h2>',
    ];
    $date_format = $this
      ->configFactory()
      ->get('bat.settings')
      ->get('date_format') ?: 'Y-m-d H:i';
    $form['event_details'] = [
      '#prefix' => '<div class="event-details">',
      '#markup' => t('Date range selected: @startdate to @enddate', [
        '@startdate' => $start_date
          ->format($date_format),
        '@enddate' => $end_date
          ->format($date_format),
      ]),
      '#suffix' => '</div>',
    ];
    if ($event_type
      ->getFixedEventStates()) {
      $state_options = bat_unit_state_options($event_type
        ->id());
      $form['change_event_status'] = [
        '#title' => t('Change the state for this event to') . ': ',
        '#type' => 'select',
        '#options' => $state_options,
        '#ajax' => [
          'callback' => '::ajaxEventStatusChange',
          'wrapper' => 'replace_textfield_div',
        ],
        '#empty_option' => t('- Select -'),
      ];
    }
    else {
      if (isset($event_type->default_event_value_field_ids) && !empty($event_type->default_event_value_field_ids)) {
        $field_name = $event_type->default_event_value_field_ids;
        $form['field_name'] = [
          '#type' => 'hidden',
          '#value' => $field_name,
        ];
        $field_definition = $this->entityFieldManager
          ->getFieldDefinitions('bat_event', $event_type
          ->id())[$field_name];
        $items = new FieldItemList($field_definition, NULL, EntityAdapter::createFromEntity(bat_event_create([
          'type' => $event_type
            ->id(),
        ])));
        $form_display = EntityFormDisplay::load('bat_event.' . $event_type
          ->id() . '.default');
        $widget = $form_display
          ->getRenderer($field_name);
        $form['#parents'] = [];
        $form[$field_name] = $widget
          ->form($items, $form, $form_state);
        $form[$field_name]['#weight'] = 1;
        $form['submit'] = [
          '#type' => 'submit',
          '#value' => t('Update value'),
          '#weight' => 2,
          '#ajax' => [
            'callback' => '::eventManagerAjaxSubmit',
            'wrapper' => 'replace_textfield_div',
          ],
        ];
      }
    }
    return $form;
  }

  /**
   * The callback for the change_event_status widget of the event manager form.
   */
  public function ajaxEventStatusChange($form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $start_date = new \DateTime($values['bat_start_date']);
    $end_date = new \DateTime($values['bat_end_date']);
    $entity_id = $values['entity_id'];
    $event_id = $values['event_id'];
    $event_type = $values['event_type'];
    $state_id = $values['change_event_status'];
    $event = bat_event_create([
      'type' => $event_type,
    ]);
    $event->uid = $this
      ->currentUser()
      ->id();
    $event_dates = [
      'value' => $start_date
        ->format('Y-m-d\\TH:i:00'),
      'end_value' => $end_date
        ->format('Y-m-d\\TH:i:00'),
    ];
    $event
      ->set('event_dates', $event_dates);
    $event_type_entity = bat_event_type_load($event_type);

    // Construct target entity reference field name using this event type's target entity type.
    $target_field_name = 'event_' . $event_type_entity
      ->getTargetEntityType() . '_reference';
    $event
      ->set($target_field_name, $entity_id);
    $event
      ->set('event_state_reference', $state_id);
    $event
      ->save();
    $state_options = bat_unit_state_options($event_type);
    $form['form_wrapper_bottom'] = [
      '#prefix' => '<div>',
      '#markup' => t('New Event state is <strong>@state</strong>.', [
        '@state' => $state_options[$state_id],
      ]),
      '#suffix' => '</div>',
      '#weight' => 9,
    ];
    return $form;
  }

  /**
   * The callback for the change_event_status widget of the event manager form.
   */
  public function eventManagerAjaxSubmit($form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $start_date = new \DateTime($values['bat_start_date']);
    $end_date = new \DateTime($values['bat_end_date']);
    $entity_id = $values['entity_id'];
    $event_id = $values['event_id'];
    $event_type = $values['event_type'];
    $field_name = $values['field_name'];
    $event = bat_event_create([
      'type' => $event_type,
    ]);
    $event->uid = $this
      ->currentUser()
      ->id();
    $event_dates = [
      'value' => $start_date
        ->format('Y-m-d\\TH:i:00'),
      'end_value' => $end_date
        ->format('Y-m-d\\TH:i:00'),
    ];
    $event
      ->set('event_dates', $event_dates);
    $event_type_entity = bat_event_type_load($event_type);

    // Construct target entity reference field name using this event type's target entity type.
    $target_field_name = 'event_' . $event_type_entity
      ->getTargetEntityType() . '_reference';
    $event
      ->set($target_field_name, $entity_id);
    $event
      ->set($field_name, $values[$field_name]);
    $event
      ->save();
    $unit = $this->entityTypeManager
      ->getStorage($event_type_entity
      ->getTargetEntityType())
      ->load($entity_id);
    $elements = $event->{$field_name}
      ->view([
      'label' => 'hidden',
    ]);
    $value = $this->renderer
      ->render($elements);
    $form['form_wrapper_bottom'] = [
      '#prefix' => '<div>',
      '#markup' => t('Value for <b>@name</b> changed to <b>@value</b>', [
        '@name' => $unit
          ->label(),
        '@value' => trim(strip_tags($value
          ->__toString())),
      ]),
      '#suffix' => '</div>',
      '#weight' => 9,
    ];
    return $form;
  }

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

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

}

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
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.
FullcalendarEventManagerForm::$entityFieldManager protected property The entity field manager service.
FullcalendarEventManagerForm::$entityTypeManager protected property The entity manager.
FullcalendarEventManagerForm::$renderer protected property The renderer.
FullcalendarEventManagerForm::ajaxEventStatusChange public function The callback for the change_event_status widget of the event manager form.
FullcalendarEventManagerForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
FullcalendarEventManagerForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FullcalendarEventManagerForm::eventManagerAjaxSubmit public function The callback for the change_event_status widget of the event manager form.
FullcalendarEventManagerForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FullcalendarEventManagerForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
FullcalendarEventManagerForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
FullcalendarEventManagerForm::__construct public function Constructs a new FullcalendarEventManagerForm.
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.