Last active
August 29, 2015 14:15
-
-
Save Jaesin/713bcb077e1b928471c2 to your computer and use it in GitHub Desktop.
Getting an autocomplete field widget for use in block configuration.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\Core\Form\FormStateInterface; | |
use Drupal\Core\Field\BaseFieldDefinition; | |
use Drupal\Core\Field\EntityReferenceFieldItemList; | |
use Drupal\Core\TypedData\DataDefinition; | |
use Drupal\Core\TypedData\Plugin\DataType\ItemList; | |
/** | |
* Provides a 'FooBlock' block. | |
* | |
* @Block( | |
* id = "foo_block", | |
* admin_label = @Translation("FooBlock"), | |
* ) | |
*/ | |
class FooBlock extends BlockBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function blockForm($form, FormStateInterface $form_state) { | |
$widget_plugin_manager = \Drupal::service('plugin.manager.field.widget'); | |
$base_field_definition = BaseFieldDefinition::create('entity_reference') | |
->setLabel(t('Node Reference')) | |
->setDescription(t('The Node.')) | |
->setSetting('target_type', 'node') | |
->setSetting('handler', 'default') | |
->setName('field_reference') | |
->setCardinality(1); | |
$widget_options = array( | |
'field_definition' => $base_field_definition, | |
'form_mode' => 'default', | |
'configuration' => array( | |
'type' => 'entityreference_auto_complete', | |
), | |
); | |
$instance = $widget_plugin_manager->getInstance($widget_options); | |
$element = array(); | |
$item_list = new ItemList(new DataDefinition()); | |
$list = new EntityReferenceFieldItemList($base_field_definition, 'reference_list', $item_list); | |
// Fail, `formElement` needs `$list->parent` to be an entity with en entity-reference field. | |
$form_field = $instance->formElement($list, 12, $element, $form, $form_state); | |
return $form; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment