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