public function MetatagDefaultsForm::save in Metatag 8
Form submission handler for the 'save' action.
Normally this method should be overridden to provide specific messages to the user and redirect the form after the entity has been saved.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Return value
int Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
Overrides EntityForm::save
File
- src/
Form/ MetatagDefaultsForm.php, line 231
Class
- MetatagDefaultsForm
- Class MetatagDefaultsForm.
Namespace
Drupal\metatag\FormCode
public function save(array $form, FormStateInterface $form_state) {
$metatag_defaults = $this->entity;
$metatag_defaults
->setStatus($form_state
->getValue('status'));
// Set the label on new defaults.
if ($metatag_defaults
->isNew()) {
$metatag_defaults_id = $form_state
->getValue('id');
$type_parts = explode('__', $metatag_defaults_id);
$entity_type = $type_parts[0];
$entity_bundle = isset($type_parts[1]) ? $type_parts[1] : NULL;
// Get the entity label.
$entity_info = $this->entityTypeManager
->getDefinitions();
$entity_label = (string) $entity_info[$entity_type]
->get('label');
if (!is_null($entity_bundle)) {
// Get the bundle label.
$bundle_info = $this->entityTypeBundleInfo
->getBundleInfo($entity_type);
if ($entity_type === 'page_variant') {
// Check if page manager is enabled and try to load the page variant
// so the label of the variant can be used.
if ($this->moduleHandler
->moduleExists('metatag_page_manager')) {
$page_variant = PageVariant::load($entity_bundle);
$page = $page_variant
->getPage();
if ($page_variant) {
$entity_label .= ': ' . $page
->label() . ': ' . $page_variant
->label();
}
}
}
else {
$entity_label .= ': ' . $bundle_info[$entity_bundle]['label'];
}
}
// Set the label to the config entity.
$this->entity
->set('label', $entity_label);
}
// Set tags within the Metatag entity.
$tags = $this->metatagPluginManager
->getDefinitions();
$tag_values = [];
foreach ($tags as $tag_id => $tag_definition) {
if ($form_state
->hasValue($tag_id)) {
// Some plugins need to process form input before storing it. Hence, we
// set it and then get it.
$tag = $this->metatagPluginManager
->createInstance($tag_id);
$tag
->setValue($form_state
->getValue($tag_id));
if (!empty($tag
->value())) {
$tag_values[$tag_id] = $tag
->value();
}
}
}
$metatag_defaults
->set('tags', $tag_values);
$status = $metatag_defaults
->save();
switch ($status) {
case SAVED_NEW:
$this
->messenger()
->addMessage($this
->t('Created the %label Metatag defaults.', [
'%label' => $metatag_defaults
->label(),
]));
break;
default:
$this
->messenger()
->addMessage($this
->t('Saved the %label Metatag defaults.', [
'%label' => $metatag_defaults
->label(),
]));
}
$form_state
->setRedirectUrl($metatag_defaults
->toUrl('collection'));
}