View source
<?php
namespace Drupal\bibcite_entity\Plugin\Field\FieldWidget;
use Drupal\bibcite_entity\Entity\Contributor;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
class ParseNameWidget extends WidgetBase {
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$field_name = $this->fieldDefinition
->getName();
$parents = $form['#parents'];
$entity = $form_state
->getFormObject()
->getEntity();
$element['value'] = [
'#title' => $this
->t('Full name'),
'#title_display' => 'invisible',
'#type' => 'textfield',
'#description' => $this
->t('Parse full name and overwrite name parts by parse result.<br><strong>Note:</strong> parts can be set to empty value if not presented in entered name.'),
'#default_value' => $entity
->getName(),
];
$element['parse'] = [
'#type' => 'submit',
'#name' => 'parse',
'#value' => $this
->t('Parse'),
'#limit_validation_errors' => [
array_merge($parents, [
$field_name,
]),
],
'#validate' => [
[
$this,
'validate',
],
],
'#submit' => [
[
$this,
'submit',
],
],
'#ajax' => [
'callback' => [
$this,
'ajaxParseName',
],
'wrapper' => 'bibcite-contributor-form-wrapper',
],
];
$element['#theme_wrappers'] = [
'fieldset' => [
'#title' => $this
->t('Full name'),
],
];
return $element;
}
public function validate(array &$form, FormStateInterface $form_state) {
}
public function submit(array &$form, FormStateInterface $form_state) {
$entity = $form_state
->getFormObject()
->getEntity();
$entity->name = $form_state
->getValue('name');
$user_input = $form_state
->getUserInput();
foreach (Contributor::getNameParts() as $part) {
unset($user_input[$part]);
}
$form_state
->setUserInput($user_input);
$form_state
->setRebuild();
}
public function ajaxParseName(array &$form, FormStateInterface $form_state) {
return $form;
}
public static function isApplicable(FieldDefinitionInterface $field_definition) {
return parent::isApplicable($field_definition) && $field_definition
->getName() === 'name' && $field_definition
->getTargetEntityTypeId() === 'bibcite_contributor';
}
}