Skip to content

Instantly share code, notes, and snippets.

@BR0kEN-
Last active November 25, 2016 15:57
Show Gist options
  • Save BR0kEN-/8aad5627a0682c91ae22f868fc313410 to your computer and use it in GitHub Desktop.
Save BR0kEN-/8aad5627a0682c91ae22f868fc313410 to your computer and use it in GitHub Desktop.
Drupal 8: validate entity field if value changed (PHP 7).
<?php
/**
* Implements hook_entity_type_alter().
*/
function MODULE_entity_type_alter(array &$entity_types) {
/* @var \Drupal\Core\Entity\ContentEntityType $entity_user */
$entity_user = $entity_types['user'];
$entity_user->setFormClass('default', \Drupal\MODULE\Entity\User\Form\ProfileForm::class);
}
<?php
namespace Drupal\stats\Entity\User\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\user\Entity\User;
use Drupal\user\ProfileForm as BaseProfileForm;
/**
* @method User getEntity()
*/
class ProfileForm extends BaseProfileForm {
/**
* Validate entity field.
*
* @param array $form
* Form specification.
* @param FormStateInterface $form_state
* A state of form.
* @param string $field
* Name of field.
* @param \Closure $validator
* Validation callback.
*/
protected function validateEntityField(array &$form, FormStateInterface $form_state, string $field, \Closure $validator) {
$entity = $this->getEntity();
if ($entity->hasField($field)) {
try {
$value = $form_state->getValue($field);
// Execute validation only if value have been changed.
if ($entity->get($field)->getValue() !== $value) {
// Update the value of entity field.
$entity->set($field, $value);
// Validate updated value.
$value = $validator->call($this, $entity->get($field));
// Update the entity and state of form if value has been processed.
if (NULL !== $value) {
$entity->set($field, $value);
// Update state of form with new, validated value.
$form_state->setValue($field, $entity->get($field)->getValue());
}
}
}
catch (\Exception $e) {
$form_state->setError($form[$field], $e->getMessage());
}
}
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$this->validateEntityField($form, $form_state, 'field_first_name', function (FieldItemListInterface $field) {
// Remember that object instance is accessible inside of this
// anonymous callback.
switch ($field->value) {
// Reject entity saving.
case 'Dummy':
throw new \InvalidArgumentException($this->t('Incorrect name!'));
// Convert the value.
case 'Sergey':
return 'Sergii';
// Allow value as it is.
default:
return NULL;
}
});
return parent::validateForm($form, $form_state);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment