You need to create a custom field type that can hold the value along with the entity reference.
A field widget can not store any data that the field type has not provided space for.
You must create a new field type would look similar to this:
<?php
namespace Drupal\MY_MODULE\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
/**
* @FieldType(
* id = "entity_reference_with_value",
* label = @Translation("Entity reference with value"),
* category = @Translation("Reference"),
* default_widget = "my_custom_field_widget",
* default_formatter = "some_formatter",
* list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",
* )
*/
class EntityReferenceWithValue extends EntityReferenceItem {
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
$schema = parent::schema($field_definition);
$schema['columns']['value'] = [
'type' => 'varchar',
'length' => 255,
];
return $schema;
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties = parent::propertyDefinitions($field_definition);
$properties['value'] = DataDefinition::create('string')
->setLabel(new TranslatableMarkup('Value'))
->setRequired(TRUE);
return $properties;
}
}
Now you can get the value with $entity->field_name->value
.
It would also be better to extend EntityReferenceAutocompleteWidget
in your field widget, instead of WidgetBase
. Then you can just do like this in the formElement
method:
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$widget = parent::formElement($items, $delta, $element, $form, $form_state);
$widget['value'] = [
'#type' => 'textfield',
'#title' => $this->t('Value'),
'#default_value' => $items[$delta]->value,
'#weight' => 999,
];
return $widget;
}