public function QuickNodeBlock::blockForm in Quick Node Block 8
Overrides BlockPluginTrait::blockForm
File
- src/
Plugin/ Block/ QuickNodeBlock.php, line 89
Class
- QuickNodeBlock
- Provides a Node Block with his display.
Namespace
Drupal\quick_node_block\Plugin\BlockCode
public function blockForm($form, FormStateInterface $form_state) {
$form = parent::blockForm($form, $form_state);
$config = $this
->getConfiguration();
$form['quick_node'] = [
'#type' => 'textfield',
'#title' => $this
->t('Node'),
'#description' => $this
->t('What node do you want to show? You can write a node number or node title.'),
'#required' => TRUE,
'#autocomplete_route_name' => 'quick_node_block.autocomplete',
'#default_value' => $config['quick_node'] ?? '',
'#ajax' => [
'wrapper' => 'quick-ajax-wrapper',
'callback' => [
$this,
'ajaxCallback',
],
'disable-refocus' => TRUE,
],
];
// Get node from the url.
$nid_add = $this->routeMatch
->getParameter('node');
// Check if there is a node selected.
$element = $form_state
->getTriggeringElement();
if (!empty($element['#value'])) {
$node_title = $element['#value'];
}
elseif (!empty($nid_add)) {
// Default value when creating the block from the node.
$node = $this->entityTypeManager
->getStorage('node')
->load($nid_add);
$node_title = $node
->getTitle() . ' (' . $nid_add . ')';
$form['quick_node']['#default_value'] = $node_title;
$form['quick_node']['#attributes']['disabled'] = TRUE;
}
else {
$node_title = $config['quick_node'] ?? '';
}
// Get nid.
preg_match("/.+\\s\\(([^\\)]+)\\)/", $node_title, $matches);
$nid = $matches[1] ?? '';
if (empty($nid)) {
$quick_display = $this
->getQuickDisplays();
}
else {
// Get bundle.
$storage = $this->entityTypeManager
->getStorage('node');
$node = $storage
->load($nid);
$content_type = $node
->getType();
// Get view mode.
$quick_display = $this->entityDisplay
->getViewModeOptionsByBundle('node', $content_type);
}
$form['quick_display'] = [
'#type' => 'select',
'#title' => $this
->t('Display'),
'#description' => $this
->t('How do you want the node to be displayed?. You must first choose a node.'),
'#required' => TRUE,
'#options' => $quick_display,
'#default_value' => $config['quick_display'] ?? '',
'#prefix' => '<div id="quick-ajax-wrapper">',
'#suffix' => '</div>',
// Hide field if quick_node is empty.
'#states' => [
'visible' => [
':input[name$="[quick_node]"]' => [
[
'empty' => FALSE,
],
],
],
],
];
return $form;
}