I want to create an entity reference field in Drupal 8 using my custom module. Like when someone clicks a link on a Drupal page, an entity reference field would be created in the page node type automatically.
Can anyone help me with this?
Step1: Create settings related to Entity Reference module from backend. Step2: Create Content type. Step3: Add/Edit fields of content type through Home -> Administration -> Structure -> Content Types -> Content type (ie:user) -> Manage fields, Add a new Entity Reference field. Step4: Choose the number of values.
You do not need to convert $entity into an array, this would simply work. $entity->get('field_name')->getValue();
This will create an entity reference field for node
content types with the article
bundle.
$form['node_id'] = array(
'#type' => 'entity_autocomplete',
'#title' => $this->t('Node'),
'#target_type' => 'node',
'#selection_settings' => ['target_bundles' => ['article']],
'#tags' => TRUE,
'#size' => 30,
'#maxlength' => 1024,
);
Note you can change target_type
for other entities like taxonomy_term
.
So I can hopefully find this faster if I need to again...
Create field storage:
if (!$field_storage = FieldStorageConfig::loadByName($entity_type, $field_name)) {
FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => $entity_type,
'type' => $type,
'cardinality' => -1,
// Optional to target entity types.
'settings' => [
'target_type' => $entity_target_type, // Ex: node, taxonomy_term.
],
])->save();
}
Create field:
FieldConfig::create([
'field_name' => $field_name,
'entity_type' => $entity_type,
'bundle' => $bundle,
'label' => $label,
'cardinality' => -1,
// Optional to target bundles.
'settings' => [
'handler' => 'default',
'handler_settings' => [
'target_bundles' => [
$vid1,
$vid2,
],
],
],
])->save();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With