View source
<?php
namespace Drupal\flexiform\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\flexiform\FlexiformManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EntityForm extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface {
protected $entityTypeManager;
protected $formBuilder;
protected $classResolver;
protected $stringTranslation;
protected $moduleHandler;
protected $flexiformManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_manager, FormBuilderInterface $form_builder, ClassResolverInterface $class_resolver, TranslationInterface $translation, ModuleHandlerInterface $module_handler, FlexiformManager $flexiform_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_manager;
$this->formBuilder = $form_builder;
$this->classResolver = $class_resolver;
$this->stringTranslation = $translation;
$this->moduleHandler = $module_handler;
$this->flexiformManager = $flexiform_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->get('form_builder'), $container
->get('class_resolver'), $container
->get('string_translation'), $container
->get('module_handler'), $container
->get('flexiform.manager'));
}
public function build() {
$entity = $this
->getContextValue('entity');
$definition = $this
->getPluginDefinition();
if ($entity
->bundle() !== $definition['bundle']) {
return;
}
$entity_form_display = EntityFormDisplay::collectRenderDisplay($entity, $definition['form_mode']);
$form_object = $this->flexiformManager
->getFormObject($entity_form_display, [
$entity_form_display
->getBaseEntityNamespace() => $entity,
]);
foreach ($entity_form_display
->getFormEntityConfig() as $namespace => $configuration) {
if ($configuration['plugin'] == 'provided' && ($provided_entity = $this
->getContextValue($namespace))) {
$provided[$namespace] = $provided_entity;
}
}
$form_state = new FormState();
$form_state
->set('form_entity_provided', $provided['form_entity_provided']);
return $this->formBuilder
->buildForm($form_object, $form_state);
}
}