Added Entity and Entity Reference Revisions which got dropped somewhere along the...
[yaffs-website] / web / core / modules / contact / src / ContactFormEditForm.php
1 <?php
2
3 namespace Drupal\contact;
4
5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
6 use Symfony\Component\DependencyInjection\ContainerInterface;
7 use Drupal\Core\Entity\EntityForm;
8 use Drupal\Core\Entity\EntityTypeInterface;
9 use Drupal\Core\Form\ConfigFormBaseTrait;
10 use Drupal\Core\Form\FormStateInterface;
11 use Egulias\EmailValidator\EmailValidator;
12 use Drupal\Core\Path\PathValidatorInterface;
13 use Drupal\Core\Render\Element\PathElement;
14
15 /**
16  * Base form for contact form edit forms.
17  *
18  * @internal
19  */
20 class ContactFormEditForm extends EntityForm implements ContainerInjectionInterface {
21   use ConfigFormBaseTrait;
22
23   /**
24    * The email validator.
25    *
26    * @var \Egulias\EmailValidator\EmailValidator
27    */
28   protected $emailValidator;
29
30   /**
31    * The path validator.
32    *
33    * @var \Drupal\Core\Path\PathValidatorInterface
34    */
35   protected $pathValidator;
36
37   /**
38    * Constructs a new ContactFormEditForm.
39    *
40    * @param \Egulias\EmailValidator\EmailValidator $email_validator
41    *   The email validator.
42    * @param \Drupal\Core\Path\PathValidatorInterface $path_validator
43    *   The path validator service.
44    */
45   public function __construct(EmailValidator $email_validator, PathValidatorInterface $path_validator) {
46     $this->emailValidator = $email_validator;
47     $this->pathValidator = $path_validator;
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   public static function create(ContainerInterface $container) {
54     return new static(
55       $container->get('email.validator'),
56       $container->get('path.validator')
57     );
58   }
59
60   /**
61    * {@inheritdoc}
62    */
63   protected function getEditableConfigNames() {
64     return ['contact.settings'];
65   }
66
67   /**
68    * {@inheritdoc}
69    */
70   public function form(array $form, FormStateInterface $form_state) {
71     $form = parent::form($form, $form_state);
72
73     $contact_form = $this->entity;
74     $default_form = $this->config('contact.settings')->get('default_form');
75
76     $form['label'] = [
77       '#type' => 'textfield',
78       '#title' => $this->t('Label'),
79       '#maxlength' => 255,
80       '#default_value' => $contact_form->label(),
81       '#description' => $this->t("Example: 'website feedback' or 'product information'."),
82       '#required' => TRUE,
83     ];
84     $form['id'] = [
85       '#type' => 'machine_name',
86       '#default_value' => $contact_form->id(),
87       '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
88       '#machine_name' => [
89         'exists' => '\Drupal\contact\Entity\ContactForm::load',
90       ],
91       '#disabled' => !$contact_form->isNew(),
92     ];
93     $form['recipients'] = [
94       '#type' => 'textarea',
95       '#title' => $this->t('Recipients'),
96       '#default_value' => implode(', ', $contact_form->getRecipients()),
97       '#description' => $this->t("Example: 'webmaster@example.com' or 'sales@example.com,support@example.com' . To specify multiple recipients, separate each email address with a comma."),
98       '#required' => TRUE,
99     ];
100     $form['message'] = [
101       '#type' => 'textarea',
102       '#title' => $this->t('Message'),
103       '#default_value' => $contact_form->getMessage(),
104       '#description' => $this->t('The message to display to the user after submission of this form. Leave blank for no message.'),
105     ];
106     $form['redirect'] = [
107       '#type' => 'path',
108       '#title' => $this->t('Redirect path'),
109       '#convert_path' => PathElement::CONVERT_NONE,
110       '#default_value' => $contact_form->getRedirectPath(),
111       '#description' => $this->t('Path to redirect the user to after submission of this form. For example, type "/about" to redirect to that page. Use a relative path with a slash in front.'),
112     ];
113     $form['reply'] = [
114       '#type' => 'textarea',
115       '#title' => $this->t('Auto-reply'),
116       '#default_value' => $contact_form->getReply(),
117       '#description' => $this->t('Optional auto-reply. Leave empty if you do not want to send the user an auto-reply message.'),
118     ];
119     $form['weight'] = [
120       '#type' => 'weight',
121       '#title' => $this->t('Weight'),
122       '#default_value' => $contact_form->getWeight(),
123       '#description' => $this->t('When listing forms, those with lighter (smaller) weights get listed before forms with heavier (larger) weights. Forms with equal weights are sorted alphabetically.'),
124     ];
125     $form['selected'] = [
126       '#type' => 'checkbox',
127       '#title' => $this->t('Make this the default form'),
128       '#default_value' => $default_form === $contact_form->id(),
129     ];
130
131     return $form;
132   }
133
134   /**
135    * {@inheritdoc}
136    */
137   public function validateForm(array &$form, FormStateInterface $form_state) {
138     parent::validateForm($form, $form_state);
139
140     // Validate and each email recipient.
141     $recipients = explode(',', $form_state->getValue('recipients'));
142
143     foreach ($recipients as &$recipient) {
144       $recipient = trim($recipient);
145       if (!$this->emailValidator->isValid($recipient)) {
146         $form_state->setErrorByName('recipients', $this->t('%recipient is an invalid email address.', ['%recipient' => $recipient]));
147       }
148     }
149     $form_state->setValue('recipients', $recipients);
150     $redirect_url = $form_state->getValue('redirect');
151     if ($redirect_url && $this->pathValidator->isValid($redirect_url)) {
152       if (mb_substr($redirect_url, 0, 1) !== '/') {
153         $form_state->setErrorByName('redirect', $this->t('The path should start with /.'));
154       }
155     }
156   }
157
158   /**
159    * {@inheritdoc}
160    */
161   public function save(array $form, FormStateInterface $form_state) {
162     $contact_form = $this->entity;
163     $status = $contact_form->save();
164     $contact_settings = $this->config('contact.settings');
165
166     $edit_link = $this->entity->link($this->t('Edit'));
167     $view_link = $contact_form->link($contact_form->label(), 'canonical');
168     if ($status == SAVED_UPDATED) {
169       $this->messenger()->addStatus($this->t('Contact form %label has been updated.', ['%label' => $view_link]));
170       $this->logger('contact')->notice('Contact form %label has been updated.', ['%label' => $contact_form->label(), 'link' => $edit_link]);
171     }
172     else {
173       $this->messenger()->addStatus($this->t('Contact form %label has been added.', ['%label' => $view_link]));
174       $this->logger('contact')->notice('Contact form %label has been added.', ['%label' => $contact_form->label(), 'link' => $edit_link]);
175     }
176
177     // Update the default form.
178     if ($form_state->getValue('selected')) {
179       $contact_settings
180         ->set('default_form', $contact_form->id())
181         ->save();
182     }
183     // If it was the default form, empty out the setting.
184     elseif ($contact_settings->get('default_form') == $contact_form->id()) {
185       $contact_settings
186         ->set('default_form', NULL)
187         ->save();
188     }
189
190     $form_state->setRedirectUrl($contact_form->urlInfo('collection'));
191   }
192
193 }