Skip to content
Snippets Groups Projects

Issue #3470043: Change machine name while writting the label.

Open Gaurav Gupta requested to merge issue/action-3470043:3470043-change-machine-name into 1.x
1 file
+ 35
0
Compare changes
  • Side-by-side
  • Inline
@@ -67,11 +67,16 @@ abstract class ActionFormBase extends EntityForm {
'#machine_name' => [
'exists' => [$this, 'exists'],
],
'#element_validate' => [
[$this, 'validateMachineName'],
],
];
$form['plugin'] = [
'#type' => 'value',
'#value' => $this->entity->get('plugin'),
];
$form['type'] = [
'#type' => 'value',
'#value' => $this->entity->getType(),
@@ -150,4 +155,34 @@ abstract class ActionFormBase extends EntityForm {
return NULL;
}
/**
* Validates and ensures a unique machine name for the action entity.
*
* This method generates a machine name from the label, ensures its uniqueness
* by appending or incrementing a numeric suffix if necessary, and sets the
* unique machine name in the form state.
*
* @param array &$element
* The form element to validate.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param array &$complete_form
* The complete form structure.
*/
public function validateMachineName(array &$element, FormStateInterface $form_state, array &$complete_form) {
$label = $form_state->getValue('label');
$machine_name = preg_replace('/[^a-z0-9_]+/', '_', strtolower($label));
$original_machine_name = $machine_name;
$suffix = 1;
if (preg_match('/^(.*)_(\d+)$/', $machine_name, $matches)) {
$original_machine_name = $matches[1];
$suffix = (int) $matches[2] + 1;
}
while ($this->exists($machine_name)) {
$machine_name = $original_machine_name . '_' . $suffix;
$suffix++;
}
$form_state->setValueForElement($element, $machine_name);
}
}
Loading