contacts_events-8.x-1.x-dev/modules/villages/src/Form/VillageGroupForm.php
modules/villages/src/Form/VillageGroupForm.php
<?php namespace Drupal\contacts_events_villages\Form; use Drupal\Core\Entity\ContentEntityForm; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Routing\RouteMatchInterface; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Form controller for Camping village group edit forms. * * @ingroup contacts_events_villages */ class VillageGroupForm extends ContentEntityForm { /** * {@inheritdoc} */ public function getEntityFromRouteMatch(RouteMatchInterface $route_match, $entity_type_id) { /** @var \Drupal\contacts_events_villages\Entity\VillageGroup $entity */ $entity = parent::getEntityFromRouteMatch($route_match, $entity_type_id); // Pre-populate event ID from URL. if ($entity->isNew()) { $event = $route_match->getParameter('contacts_event'); $entity->setEvent($event); } elseif ($entity->get('event')->isEmpty()) { throw new NotFoundHttpException('Invalid event.'); } return $entity; } /** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { /** @var \Drupal\contacts_events_villages\Entity\VillageGroup $entity */ $entity = parent::validateForm($form, $form_state); /** @var \Drupal\contacts_events_villages\Plugin\VillageGroupTypeManager $plugin_manager */ $plugin_manager = \Drupal::service('plugin.manager.c_events_village_group_type'); /** @var \Drupal\contacts_events_villages\Plugin\VillageGroupTypeInterface $type_plugin */ $type_plugin = $plugin_manager->createInstance($entity->bundle()); // Check that an exiting entity does not already exist. $existing = $type_plugin->getExisting($entity); $error_message = $this->t('A group already exists for the following configuration.'); if ($entity->isNew() && !$existing->isNew()) { $form_state->setErrorByName(NULL, $error_message); } elseif (!$entity->isNew() && $existing->isNew()) { $form_state->setErrorByName(NULL, $error_message); } elseif (!$entity->isNew() && !$existing->isNew() && $existing->id() !== $entity->id()) { $form_state->setErrorByName(NULL, $error_message); } return $entity; } /** * {@inheritdoc} */ public function save(array $form, FormStateInterface $form_state) { /** @var \Drupal\contacts_events_villages\Entity\VillageGroup $entity */ $entity = $this->entity; $status = parent::save($form, $form_state); switch ($status) { case SAVED_NEW: $this->messenger()->addMessage($this->t('Created the %label Camping village group.', [ '%label' => $entity->label(), ])); break; default: $this->messenger()->addMessage($this->t('Saved the %label Camping village group.', [ '%label' => $entity->label(), ])); } $form_state->setRedirect('entity.c_events_village_group.collection', [ 'contacts_event' => $entity->getEventId(), ]); } }