bm-1.0.x-dev/src/Form/BookingButtonForm.php

src/Form/BookingButtonForm.php
<?php

declare(strict_types=1);

namespace Drupal\bm\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a Booking Manager form.
 */
final class BookingButtonForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'bm_booking_button';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $query = \Drupal::request()->query->all();
    $bid = $query['bid'];
    $entity = \Drupal::entityTypeManager()->getStorage('bm')->load($bid);
    $view = \Drupal::entityTypeManager()->getViewBuilder('bm')->view($entity, 'book_form');
    $markup = \Drupal::service('renderer')->renderRoot($view);

    $form['booking_entity_markup'] = [
      '#type' => 'markup',
      '#title' => $this->t('Book'),
      '#markup' => $markup
    ];

    $form['booking_bid'] = [
      '#type' => 'hidden',
      '#hidden' => TRUE,
      '#value' => $bid,
    ];

    $form['booking_name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
      '#required' => TRUE,
    ];

    $form['booking_email'] = [
      '#type' => 'email',
      '#title' => $this->t('Email'),
      '#required' => TRUE,
    ];

    $form['booking_date'] = [
      '#type' => 'date',
      '#title' => $this->t('Date of Book'),
      '#required' => TRUE,
    ];

    $form['actions'] = [
      '#type' => 'actions',
      'submit' => [
        '#type' => 'submit',
        '#value' => $this->t('Book'),
      ],
    ];

    $form_state->set('bm_entity', $entity);

    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state): void {
    $booking_date = $form_state->getValue('booking_date');
    if (strtotime($booking_date) < time()) {
      $form_state->setErrorByName('booking_date', t('Booking Date must be in the future'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->messenger()->addStatus($this->t('Book Confirm'));
    $booking_bid = $form_state->getValue('booking_bid');
    $booking_name = $form_state->getValue('booking_name');
    $booking_email = $form_state->getValue('booking_email');
    $booking_date = $form_state->getValue('booking_date');
    $bm_entity = $form_state->getStorage()['bm_entity'];

    \Drupal::entityTypeManager()->getStorage('bm')->create([
      'label' => trim($booking_bid) . '-' . trim($booking_name),
      'bundle' => 'booking_list',
      'field_bm_booking_item' => $bm_entity,
      'field_bm_booking_date' => $booking_date,
    ])->save();
    $form_state->setRedirect('entity.bm.canonical', ['bm' => $booking_bid]);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc