public function MetatagCustomCreateForm::validateForm in Metatag Routes 8
Form validation handler.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Overrides FormBase::validateForm
File
- src/
Form/ MetatagCustomCreateForm.php, line 106
Class
- MetatagCustomCreateForm
- Class MetatagCustomCreateForm.
Namespace
Drupal\metatag_routes\FormCode
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
// Get the path given by the user.
$url = trim($form_state
->getValue('metatag_url'));
// Validate the url format.
if (strpos($url, '/') === FALSE) {
$form_state
->setErrorByName('metatag_url', $this
->t('The path must begin with /'));
return FALSE;
}
// Get route name from path.
$url_object = $this->pathValidator
->getUrlIfValid($url);
if ($url_object) {
$route_name = $url_object
->getRouteName();
$route_object = $this->routeProvider
->getrouteByName($route_name);
// Avoid administrative routes to have metatags.
if ($this->adminContext
->isAdminRoute($route_object)) {
$form_state
->setErrorByName('metatag_url', $this
->t('The admin routes should not have metatags.'));
return FALSE;
}
// Avoid including entity routes.
$params = $url_object
->getRouteParameters();
$entity_type = !empty($params) ? key($params) : NULL;
if (isset($entity_type) && in_array($entity_type, [
'node',
'taxonomy_term',
])) {
$form_state
->setErrorByName('metatag_url', $this
->t('The entities routes metatags must be added by fields. @entity_type - @id', [
'@entity_type' => $entity_type,
'@id' => $params[$entity_type],
]));
return FALSE;
}
// Validate that the route doesn't have metatags created already.
$ids = $this->entityTypeManager
->getStorage('metatag_defaults')
->getQuery()
->condition('id', $route_name)
->execute();
if ($ids) {
$form_state
->setErrorByName('metatag_url', $this
->t('There are already metatags created for this route.'));
return FALSE;
}
$form_state
->setValue('route_name', $route_name);
}
else {
$form_state
->setErrorByName('metatag_url', $this
->t('The path does not exist as an internal Drupal route.'));
}
}