contacts_events-8.x-1.x-dev/modules/accommodation/src/Form/AccommodationForm.php
modules/accommodation/src/Form/AccommodationForm.php
<?php
namespace Drupal\contacts_events_accommodation\Form;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
/**
* Form controller for the accommodation entity edit forms.
*/
class AccommodationForm extends ContentEntityForm {
/**
* {@inheritdoc}
*/
protected function prepareEntity() {
parent::prepareEntity();
if ($this->entity->isNew()) {
$this->entity->set('event', $this->getRouteMatch()->getParameter('contacts_event'));
}
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
// Min is required if max is set.
$form['delegates_min']['widget'][0]['value']['#states']['required'] = [
':input[name="delegates_max[0][value]"]' => ['filled' => TRUE],
];
// Max is required if min is set.
$form['delegates_max']['widget'][0]['value']['#states']['required'] = [
':input[name="delegates_min[0][value]"]' => ['filled' => TRUE],
];
// Show max if min or max are set.
$form['delegates_max']['widget'][0]['value']['#states']['visible'] = [
[':input[name="delegates_min[0][value]"]' => ['filled' => TRUE]],
[':input[name="delegates_max[0][value]"]' => ['filled' => TRUE]],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\contacts_events_accommodation\AccommodationInterface $entity */
$entity = parent::validateForm($form, $form_state);
// Check that neither or both delegate numbers are set.
$min = $entity->getMinDelegates();
$max = $entity->getMaxDelegates();
if ($min !== NULL && $max === NULL) {
$form_state->setError($form['delegates_max']['widget'][0]['value'], $this->t('Maximum delegates is required if a minimum is given.'));
}
if ($max !== NULL && $min === NULL) {
$form_state->setError($form['delegates_min']['widget'][0]['value'], $this->t('Minimum delegates is required if a maximum is given.'));
}
return $entity;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
/** @var \Drupal\contacts_events_accommodation\AccommodationInterface $entity */
$entity = $this->getEntity();
$result = $entity->save();
$message_arguments = ['%label' => $entity->label()];
if ($result == SAVED_NEW) {
$this->messenger()->addStatus($this->t('New accommodation %label has been created.', $message_arguments));
}
else {
$this->messenger()->addStatus($this->t('The accommodation %label has been updated.', $message_arguments));
}
$form_state->setRedirect('entity.c_events_accommodation.collection', [
'contacts_event' => $entity->get('event')->target_id,
]);
}
}
