You are here

class EntityForm in Entity Browser 8

Same name and namespace in other branches
  1. 8.2 modules/entity_form/src/Plugin/EntityBrowser/Widget/EntityForm.php \Drupal\entity_browser_entity_form\Plugin\EntityBrowser\Widget\EntityForm

Provides entity form widget.

Plugin annotation


@EntityBrowserWidget(
  id = "entity_form",
  label = @Translation("Entity form"),
  description = @Translation("Provides entity form widget."),
  auto_select = FALSE
)

Hierarchy

Expanded class hierarchy of EntityForm

File

modules/entity_form/src/Plugin/EntityBrowser/Widget/EntityForm.php, line 28

Namespace

Drupal\entity_browser_entity_form\Plugin\EntityBrowser\Widget
View source
class EntityForm extends WidgetBase {

  /**
   * The entity type bundle info service.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * The entity display repository.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
   */
  protected $entityDisplayRepository;

  /**
   * Constructs widget plugin.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   Event dispatcher service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\entity_browser\WidgetValidationManager $validation_manager
   *   The Widget Validation Manager service.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle info service.
   * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
   *   The entity display repository.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, EntityTypeManagerInterface $entity_type_manager, WidgetValidationManager $validation_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, EntityDisplayRepositoryInterface $entity_display_repository) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher, $entity_type_manager, $validation_manager);
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    $this->entityDisplayRepository = $entity_display_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('event_dispatcher'), $container
      ->get('entity_type.manager'), $container
      ->get('plugin.manager.entity_browser.widget_validation'), $container
      ->get('entity_type.bundle.info'), $container
      ->get('entity_display.repository'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'entity_type' => NULL,
      'bundle' => NULL,
      'form_mode' => 'default',
      'submit_text' => $this
        ->t('Save entity'),
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function getForm(array &$original_form, FormStateInterface $form_state, array $additional_widget_parameters) {
    if (empty($this->configuration['entity_type']) || empty($this->configuration['bundle']) || empty($this->configuration['form_mode'])) {
      return [
        '#markup' => $this
          ->t('The settings for this widget (Entity type, Bundle or Form mode) are not configured correctly.'),
      ];
    }
    $form = parent::getForm($original_form, $form_state, $additional_widget_parameters);

    // Pretend to be IEFs submit button.
    $form['#submit'] = [
      [
        'Drupal\\inline_entity_form\\ElementSubmit',
        'trigger',
      ],
    ];
    $form['actions']['submit']['#ief_submit_trigger'] = TRUE;
    $form['actions']['submit']['#ief_submit_trigger_all'] = TRUE;
    $form['inline_entity_form'] = [
      '#type' => 'inline_entity_form',
      '#op' => 'add',
      '#entity_type' => $this->configuration['entity_type'],
      '#bundle' => $this->configuration['bundle'],
      '#form_mode' => $this->configuration['form_mode'],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function prepareEntities(array $form, FormStateInterface $form_state) {
    return [
      $form[$form['#browser_parts']['widget']]['inline_entity_form']['#entity'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function submit(array &$element, array &$form, FormStateInterface $form_state) {
    if (!empty($form_state
      ->getTriggeringElement()['#eb_widget_main_submit'])) {
      $entities = $this
        ->prepareEntities($form, $form_state);
      array_walk($entities, function (EntityInterface $entity) {
        $entity
          ->save();
      });
      $this
        ->selectEntities($entities, $form_state);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $parents = [
      'table',
      $this
        ->uuid(),
      'form',
    ];
    $entity_type = $form_state
      ->hasValue(array_merge($parents, [
      'entity_type',
    ])) ? $form_state
      ->getValue(array_merge($parents, [
      'entity_type',
    ])) : $this->configuration['entity_type'];
    $bundle = $form_state
      ->hasValue(array_merge($parents, [
      'bundle',
      'select',
    ])) ? $form_state
      ->getValue(array_merge($parents, [
      'bundle',
      'select',
    ])) : $this->configuration['bundle'];
    $form_mode = $form_state
      ->hasValue(array_merge($parents, [
      'form_mode',
      'form_select',
    ])) ? $form_state
      ->hasValue(array_merge($parents, [
      'form_mode',
      'form_select',
    ])) : $this->configuration['form_mode'];
    $definitions = $this->entityTypeManager
      ->getDefinitions();
    $entity_types = array_combine(array_keys($definitions), array_map(function (EntityTypeInterface $item) {
      return $item
        ->getLabel();
    }, $definitions));
    $form['entity_type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Entity type'),
      '#options' => $entity_types,
      '#default_value' => $entity_type,
      '#ajax' => [
        'callback' => [
          $this,
          'updateFormElements',
        ],
      ],
    ];
    $bundles = [];
    if ($entity_type) {
      $definitions = $this->entityTypeBundleInfo
        ->getBundleInfo($entity_type);
      $bundles = array_map(function ($item) {
        return $item['label'];
      }, $definitions);
    }
    $form['bundle'] = [
      '#type' => 'container',
      'select' => [
        '#type' => 'select',
        '#title' => $this
          ->t('Bundle'),
        '#options' => $bundles,
        '#default_value' => $bundle,
      ],
      '#attributes' => [
        'id' => 'bundle-wrapper-' . $this
          ->uuid(),
      ],
    ];
    $form['form_mode'] = [
      '#type' => 'container',
      'form_select' => [
        '#type' => 'select',
        '#title' => $this
          ->t('Form mode'),
        '#default_value' => $form_mode,
        '#options' => $this->entityDisplayRepository
          ->getFormModeOptions($entity_type),
      ],
      '#attributes' => [
        'id' => 'form-mode-wrapper-' . $this
          ->uuid(),
      ],
    ];
    return $form;
  }

  /**
   * AJAX callback for bundle dropdown update.
   */
  public function updateBundle($form, FormStateInterface $form_state) {
    return $form['widgets']['table'][$this
      ->uuid()]['form']['bundle'];
  }

  /**
   * AJAX callback for the Form Mode dropdown update.
   */
  public function updateFormMode($form, FormStateInterface $form_state) {
    return $form['widgets']['table'][$this
      ->uuid()]['form']['form_mode'];
  }

  /**
   * AJAX callback to update the two form elements: bundle and form_mode.
   */
  public function updateFormElements($form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response
      ->addCommand(new ReplaceCommand('#bundle-wrapper-' . $this
      ->uuid(), $this
      ->updateBundle($form, $form_state)));
    $response
      ->addCommand(new ReplaceCommand('#form-mode-wrapper-' . $this
      ->uuid(), $this
      ->updateFormMode($form, $form_state)));
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    $this->configuration['bundle'] = $this->configuration['bundle']['select'];
    $this->configuration['form_mode'] = $this->configuration['form_mode']['form_select'];
  }

  /**
   * {@inheritdoc}
   */
  public function access() {
    return $this->entityTypeManager
      ->getAccessControlHandler($this->configuration['entity_type'])
      ->createAccess($this->configuration['bundle'], NULL, [], TRUE);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entityDisplayRepository protected property The entity display repository.
EntityForm::$entityTypeBundleInfo protected property The entity type bundle info service.
EntityForm::access public function Defines if the widget is visible / accessible in a given context. Overrides WidgetBase::access
EntityForm::buildConfigurationForm public function Implements PluginFormInterface::buildConfigurationForm(). Overrides WidgetBase::buildConfigurationForm
EntityForm::create public static function Creates an instance of the plugin. Overrides WidgetBase::create
EntityForm::defaultConfiguration public function Gets default configuration for this plugin. Overrides WidgetBase::defaultConfiguration
EntityForm::getForm public function Returns widget form. Overrides WidgetBase::getForm
EntityForm::prepareEntities protected function Prepares the entities without saving them. Overrides WidgetBase::prepareEntities
EntityForm::submit public function Submits form. Overrides WidgetBase::submit
EntityForm::submitConfigurationForm public function Implements PluginFormInterface::submitConfigurationForm(). Overrides PluginConfigurationFormTrait::submitConfigurationForm
EntityForm::updateBundle public function AJAX callback for bundle dropdown update.
EntityForm::updateFormElements public function AJAX callback to update the two form elements: bundle and form_mode.
EntityForm::updateFormMode public function AJAX callback for the Form Mode dropdown update.
EntityForm::__construct public function Constructs widget plugin. Overrides WidgetBase::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginConfigurationFormTrait::validateConfigurationForm public function Implements PluginFormInterface::validateConfigurationForm(). 2
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
WidgetBase::$entityTypeManager protected property Entity type manager service.
WidgetBase::$eventDispatcher protected property Event dispatcher service.
WidgetBase::$id protected property Plugin id.
WidgetBase::$label protected property Plugin label.
WidgetBase::$uuid protected property Plugin uuid.
WidgetBase::$validationManager protected property The Widget Validation Manager service.
WidgetBase::$weight protected property Plugin weight.
WidgetBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 1
WidgetBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
WidgetBase::getWeight public function Returns the widget's weight. Overrides WidgetInterface::getWeight
WidgetBase::handleWidgetContext protected function Allow configuration overrides at runtime based on widget context passed to this widget from the Entity Browser element.
WidgetBase::id public function Returns the widget id. Overrides WidgetInterface::id
WidgetBase::label public function Returns the widget label. Overrides WidgetInterface::label
WidgetBase::requiresJsCommands public function Returns if widget requires JS commands support by selection display. Overrides WidgetInterface::requiresJsCommands
WidgetBase::runWidgetValidators protected function Run widget validators.
WidgetBase::selectEntities protected function Dispatches event that informs all subscribers about new selected entities.
WidgetBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
WidgetBase::setLabel public function Sets the widget's label. Overrides WidgetInterface::setLabel
WidgetBase::setWeight public function Sets the widget's weight. Overrides WidgetInterface::setWeight
WidgetBase::uuid public function Returns the widget UUID. Overrides WidgetInterface::uuid
WidgetBase::validate public function Validates form. Overrides WidgetInterface::validate 1