Skip to content
Snippets Groups Projects

Issue #3260103: Automatic entity label does not take into account the field constraints

Open Issue #3260103: Automatic entity label does not take into account the field constraints
All threads resolved!
All threads resolved!
+ 65
0
@@ -64,6 +64,51 @@ function auto_entitylabel_form_alter(&$form, FormStateInterface $form_state) {
}
}
/**
* Entity builder to update the label by the pattern.
*
* It will be called two times on ContentEntityForm::validateForm()
* and EntityForm::submitForm()
*
* @param string $entity_type
* Entity type.
* @param EntityInterface $entity
* Entity to update the label.
* @param array $form
* Form array.
* @param FormStateInterface $form_state
* Form state.
*/
function auto_entitylabel_entity_builder_set_label($entity_type, EntityInterface $entity, array &$form, FormStateInterface $form_state) {
if ($entity instanceof ContentEntityInterface) {
$decorator = \Drupal::service('auto_entitylabel.entity_decorator');
/** @var \Drupal\auto_entitylabel\AutoEntityLabelManager $decorated_entity */
$decorated_entity = $decorator->decorate($entity);
if ($decorated_entity->hasLabel() && $decorated_entity->autoLabelNeeded()
&& !$decorated_entity->isTitlePreserved()) {
$pattern = $decorated_entity->getPattern();
// Try to get from the form state the new value for the entity label.
if ($pattern) {
$token = str_replace(['[',']'], '', $pattern);
$parts = explode(':', $token);
$entity_type_token = \Drupal::service('token.entity_mapper')->getEntityTypeForTokenType($parts[0]);
if ($entity_type_token == $entity_type && isset($parts[1])) {
$field_name = $parts[1];
$value = $form_state->getValue($field_name);
// The method setLabel() will take this value to set
// the entity label.
$entity->set($field_name, $value);
}
}
$decorated_entity->setLabel();
}
}
}
/**
* Implements hook_inline_entity_form_entity_form_alter().
*/
@@ -141,6 +186,9 @@ function auto_entitylabel_prepare_entityform(array &$form, ContentEntityInterfac
break;
}
// Set the entity builder for generate the entity label.
$form['#entity_builders']['auto_entitylabel'] = 'auto_entitylabel_entity_builder_set_label';
$form['#auto_entitylabel_processed'] = TRUE;
}
}
@@ -162,6 +210,23 @@ function auto_entitylabel_entity_prepare_view($entity_type_id, array $entities,
}
}
/**
* Implements hook_entity_create().
*/
function auto_entitylabel_entity_create(EntityInterface $entity) {
// Set the label when the entity is created programmaticaly with the
// method create.
if ($entity instanceof ContentEntityInterface) {
$decorator = \Drupal::service('auto_entitylabel.entity_decorator');
/** @var \Drupal\auto_entitylabel\AutoEntityLabelManager $decorated_entity */
$decorated_entity = $decorator->decorate($entity);
if ($decorated_entity->hasLabel() && $decorated_entity->autoLabelNeeded()
&& !$decorated_entity->isTitlePreserved()) {
$decorated_entity->setLabel();
}
}
}
/**
* Implements hook_entity_presave().
*/
Loading