class EventsExampleForm

Same name in other branches
  1. 4.0.x modules/events_example/src/Form/EventsExampleForm.php \Drupal\events_example\Form\EventsExampleForm

Implements the SimpleForm form controller.

The submitForm() method of this class demonstrates using the event dispatcher service to dispatch an event.

Hierarchy

Expanded class hierarchy of EventsExampleForm

See also

\Drupal\events_example\Event\IncidentEvents

\Drupal\events_example\Event\IncidentReportEvent

\Symfony\Component\EventDispatcher\EventDispatcherInterface

\Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher

Related topics

1 string reference to 'EventsExampleForm'
events_example.routing.yml in modules/events_example/events_example.routing.yml
modules/events_example/events_example.routing.yml

File

modules/events_example/src/Form/EventsExampleForm.php, line 25

Namespace

Drupal\events_example\Form
View source
class EventsExampleForm extends FormBase {
    
    /**
     * The event dispatcher service.
     *
     * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
     */
    protected $eventDispatcher;
    
    /**
     * Constructs a new UserLoginForm.
     *
     * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
     *   The event dispatcher service.
     */
    public function __construct(EventDispatcherInterface $event_dispatcher) {
        // The event dispatcher service is an implementation of
        // \Symfony\Component\EventDispatcher\EventDispatcherInterface. In Drupal
        // this is generally and instance of the
        // \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher service.
        // This dispatcher improves performance when dispatching events by compiling
        // a list of subscribers into the service container so that they do not need
        // to be looked up every time.
        $this->eventDispatcher = $event_dispatcher;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('event_dispatcher'));
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $form['intro'] = [
            '#markup' => '<p>' . $this->t('This form demonstrates subscribing to, and dispatching, events. When the form is submitted an event is dispatched indicating a new report has been submitted. Event subscribers respond to this event with various messages depending on the incident type. Review the code for the events_example module to see how it works.') . '</p>',
        ];
        $form['incident_type'] = [
            '#type' => 'radios',
            '#required' => TRUE,
            '#title' => $this->t('What type of incident do you want to report?'),
            '#options' => [
                'stolen_princess' => $this->t('Missing princess'),
                'cat' => $this->t('Cat stuck in tree'),
                'joker' => $this->t('Something involving the Joker'),
            ],
        ];
        $form['incident'] = [
            '#type' => 'textarea',
            '#required' => FALSE,
            '#title' => $this->t('Incident report'),
            '#description' => $this->t('Describe the incident in detail. This information will be passed along to all crime fighters.'),
            '#cols' => 60,
            '#rows' => 5,
        ];
        $form['actions'] = [
            '#type' => 'actions',
        ];
        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
        ];
        return $form;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'events_example_form';
    }
    
    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        $type = $form_state->getValue('incident_type');
        $report = $form_state->getValue('incident');
        // When dispatching, or triggering, an event start by constructing a new
        // event object. Then use the event dispatcher service to notify any event
        // subscribers. Event objects are used to transport relevant data to any
        // subscribers, as well as keep track of the current state of an event. It
        // is best practice to create a unique class wrapping
        // \Symfony\Component\EventDispatcher\Event.
        $event = new IncidentReportEvent($type, $report);
        // Dispatch an event by specifying which event, and providing an event
        // object. Rather than hard code the event name you should use a constant
        // to represent the event being dispatched. The constant serves as a
        // location for documentation of the event, and ensures your code is future
        // proofed against event name changes.
        $this->eventDispatcher
            ->dispatch($event, IncidentEvents::NEW_REPORT);
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EventsExampleForm::$eventDispatcher protected property The event dispatcher service.
EventsExampleForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
EventsExampleForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
EventsExampleForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
EventsExampleForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
EventsExampleForm::__construct public function Constructs a new UserLoginForm.
FormBase::$configFactory protected property The config factory. 3
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. 3
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.
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 73
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. 17
MessengerTrait::messenger public function Gets the messenger. 17
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; 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. 3
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.