public static function HomeboxPageForm::addBlock in Homebox 8
Ajax callback to add block.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
\Symfony\Component\HttpFoundation\Request $request: Current request.
Return value
\Drupal\Core\Ajax\AjaxResponse Response to hide buttons.
Throws
\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
\Drupal\Component\Plugin\Exception\PluginNotFoundException
\Drupal\Core\Entity\EntityStorageException
File
- src/
Form/ HomeboxPageForm.php, line 187
Class
- HomeboxPageForm
- Class HomeboxPageForm.
Namespace
Drupal\homebox\FormCode
public static function addBlock(array $form, FormStateInterface $form_state, Request $request) {
$user = \Drupal::currentUser();
/* @var HomeboxInterface $homebox */
$homebox = $request->attributes
->get('homebox');
// Get user layout settings or default homebox settings if not exists.
/** @var \Drupal\homebox\Entity\HomeboxLayoutInterface $homebox_layout */
$homebox_layout = self::getLayoutStorageData($homebox
->id(), $user
->id());
$blocks = $homebox
->getBlocks();
if (isset($homebox_layout)) {
$serializer = \Drupal::service('serializer');
$layout_blocks = $homebox_layout
->get('settings')
->getValue();
$layout_blocks = $serializer
->decode(array_shift($layout_blocks)['value'], 'json');
}
else {
$layout_blocks = $blocks;
}
$element = $form_state
->getTriggeringElement();
foreach ($blocks as $block) {
if ($block['id'] == $element['#attributes']['block_id']) {
break;
}
$block = NULL;
}
if (!empty($block)) {
$block['status'] = TRUE;
$layout_blocks[] = $block;
/** @var \Drupal\Core\Block\BlockPluginInterface $block_instance */
$block_instance = \Drupal::service('plugin.manager.block')
->createInstance($block['id']);
$token = \Drupal::csrfToken()
->get((new Random())
->string(32));
$render[$block['id']] = [
'#type' => 'container',
'#attributes' => [
'class' => 'block_render',
'id' => $token,
],
];
$render[$block['id']]['render'] = $block_instance
->build();
$render[$block['id']]['render']['#theme'] = 'homebox_block';
$render[$block['id']]['render']['#block_id'] = $block_instance
->getPluginId();
$render[$block['id']]['render']['#block_title'] = $block['title'] != '' ? $block['title'] : $block_instance
->label();
$render[$block['id']]['render']['#block_content'] = $block_instance
->build();
$form['regions'][$block['region']][] = $render;
}
$form_state
->setValue('blocks', $layout_blocks);
self::saveUserLayoutData($form, $form_state, $request);
return $form['regions'];
}