clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,207 @@
<?php
namespace Drupal\inline_entity_form\Element;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\RevisionLogInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\RenderElement;
use Drupal\inline_entity_form\ElementSubmit;
use Drupal\inline_entity_form\TranslationHelper;
/**
* Provides an inline entity form element.
*
* Usage example:
* @code
* $form['article'] = [
* '#type' => 'inline_entity_form',
* '#entity_type' => 'node',
* '#bundle' => 'article',
* // If the #default_value is NULL, a new entity will be created.
* '#default_value' => $loaded_article,
* ];
* @endcode
* To access the entity in validation or submission callbacks, use
* $form['article']['#entity']. Due to Drupal core limitations the entity
* can't be accessed via $form_state->getValue('article').
*
* @RenderElement("inline_entity_form")
*/
class InlineEntityForm extends RenderElement {
/**
* {@inheritdoc}
*/
public function getInfo() {
$class = get_class($this);
return [
'#ief_id' => '',
'#entity_type' => NULL,
'#bundle' => NULL,
'#langcode' => NULL,
// Instance of \Drupal\Core\Entity\EntityInterface. If NULL, a new
// entity will be created.
'#default_value' => NULL,
// The form mode used to display the entity form.
'#form_mode' => 'default',
// Will create a new revision if set to TRUE.
'#revision' => FALSE,
// Will save entity on submit if set to TRUE.
'#save_entity' => TRUE,
// 'add', 'edit' or 'duplicate'.
'#op' => NULL,
'#process' => [
// Core's #process for groups, don't remove it.
[$class, 'processGroup'],
// InlineEntityForm's #process must run after the above ::processGroup
// in case any new elements (like groups) were added in alter hooks.
[$class, 'processEntityForm'],
],
'#element_validate' => [
[$class, 'validateEntityForm'],
],
'#ief_element_submit' => [
[$class, 'submitEntityForm'],
],
'#theme_wrappers' => ['container'],
'#pre_render' => [
// Core's #pre_render for groups, don't remove it.
[$class, 'preRenderGroup'],
],
];
}
/**
* Builds the entity form using the inline form handler.
*
* @param array $entity_form
* The entity form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param array $complete_form
* The complete form structure.
*
* @throws \InvalidArgumentException
* Thrown when the #entity_type or #bundle properties are empty, or when
* the #default_value property is not an entity.
*
* @return array
* The built entity form.
*/
public static function processEntityForm(array $entity_form, FormStateInterface $form_state, array &$complete_form) {
if (empty($entity_form['#entity_type'])) {
throw new \InvalidArgumentException('The inline_entity_form element requires the #entity_type property.');
}
if (isset($entity_form['#default_value']) && !($entity_form['#default_value'] instanceof EntityInterface)) {
throw new \InvalidArgumentException('The inline_entity_form #default_value property must be an entity object.');
}
$entity_type = \Drupal::entityTypeManager()->getDefinition($entity_form['#entity_type']);
if (empty($entity_form['#ief_id'])) {
$entity_form['#ief_id'] = \Drupal::service('uuid')->generate();
}
if (isset($entity_form['#default_value'])) {
// Transfer the #default_value to #entity, as expected by inline forms.
$entity_form['#entity'] = $entity_form['#default_value'];
}
else {
// This is an add operation, create a new entity.
$storage = \Drupal::entityTypeManager()->getStorage($entity_form['#entity_type']);
$values = [];
if ($langcode_key = $entity_type->getKey('langcode')) {
if (!empty($entity_form['#langcode'])) {
$values[$langcode_key] = $entity_form['#langcode'];
}
}
if ($bundle_key = $entity_type->getKey('bundle')) {
$values[$bundle_key] = $entity_form['#bundle'];
}
$entity_form['#entity'] = $storage->create($values);
}
if (!isset($entity_form['#op'])) {
// When duplicating entities, the entity is new, but already has a UUID.
if ($entity_form['#entity']->isNew() && $entity_form['#entity']->uuid()) {
$entity_form['#op'] = 'duplicate';
}
else {
$entity_form['#op'] = $entity_form['#entity']->isNew() ? 'add' : 'edit';
}
}
// Prepare the entity form and the entity itself for translating.
$entity_form['#entity'] = TranslationHelper::prepareEntity($entity_form['#entity'], $form_state);
$entity_form['#translating'] = TranslationHelper::isTranslating($form_state) && $entity_form['#entity']->isTranslatable();
// Handle revisioning if the entity supports it.
if ($entity_type->isRevisionable() && $entity_form['#revision']) {
$entity_form['#entity']->setNewRevision($entity_form['#revision']);
// @see \Drupal\Core\Entity\ContentEntityForm::buildEntity
if ($entity_form['#entity'] instanceof RevisionLogInterface) {
$entity_form['#entity']->setRevisionUserId(\Drupal::currentUser()->id());
$entity_form['#entity']->setRevisionCreationTime(\Drupal::time()->getRequestTime());
}
}
$inline_form_handler = static::getInlineFormHandler($entity_form['#entity_type']);
$entity_form = $inline_form_handler->entityForm($entity_form, $form_state);
// The form element can't rely on inline_entity_form_form_alter() calling
// ElementSubmit::attach() since form alters run before #process callbacks.
ElementSubmit::attach($complete_form, $form_state);
return $entity_form;
}
/**
* Validates the entity form using the inline form handler.
*
* @param array $entity_form
* The entity form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public static function validateEntityForm(array &$entity_form, FormStateInterface $form_state) {
$inline_form_handler = static::getInlineFormHandler($entity_form['#entity_type']);
$inline_form_handler->entityFormValidate($entity_form, $form_state);
}
/**
* Handles the submission of the entity form using the inline form handler.
*
* @param array $entity_form
* The entity form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public static function submitEntityForm(array &$entity_form, FormStateInterface $form_state) {
$inline_form_handler = static::getInlineFormHandler($entity_form['#entity_type']);
$inline_form_handler->entityFormSubmit($entity_form, $form_state);
if ($entity_form['#save_entity']) {
$inline_form_handler->save($entity_form['#entity']);
}
}
/**
* Gets the inline form handler for the given entity type.
*
* @param string $entity_type
* The entity type id.
*
* @throws \InvalidArgumentException
* Thrown when the entity type has no inline form handler defined.
*
* @return \Drupal\inline_entity_form\InlineFormInterface
* The inline form handler.
*/
public static function getInlineFormHandler($entity_type) {
$inline_form_handler = \Drupal::entityTypeManager()->getHandler($entity_type, 'inline_form');
if (empty($inline_form_handler)) {
throw new \InvalidArgumentException(sprintf('The %s entity type has no inline form handler.', $entity_type));
}
return $inline_form_handler;
}
}
@@ -0,0 +1,114 @@
<?php
namespace Drupal\inline_entity_form;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
/**
* Provides #ief_element_submit, the submit version of #element_validate.
*
* #ief_element_submit callbacks are invoked by a #submit callback added
* to the form's main submit button.
*/
class ElementSubmit {
/**
* Attaches the #ief_element_submit functionality to the given form.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
public static function attach(array &$form, FormStateInterface $form_state) {
// attach() is called for each IEF form element, but the callbacks only
// need to be added once per form build.
if (isset($form['#ief_element_submit_attached'])) {
return;
}
$form['#ief_element_submit_attached'] = TRUE;
// Entity form actions.
foreach (['submit', 'publish', 'unpublish'] as $action) {
if (!empty($form['actions'][$action])) {
self::addCallback($form['actions'][$action], $form);
}
}
// Generic submit button.
if (!empty($form['submit'])) {
self::addCallback($form['submit'], $form);
}
}
/**
* Adds the trigger callback to the given submit element.
*
* @param array $element
* The submit element.
* @param array $complete_form
* The complete form.
*/
public static function addCallback(array &$element, array $complete_form) {
if (empty($element['#submit'])) {
// Drupal runs either the button-level callbacks or the form-level ones.
// Having no button-level callbacks indicates that the form has relied
// on form-level callbacks, which now need to be transferred.
$element['#submit'] = $complete_form['#submit'];
}
$element['#submit'] = array_merge([[get_called_class(), 'trigger']], $element['#submit']);
// Used to distinguish between an inline form submit and main form submit.
$element['#ief_submit_trigger'] = TRUE;
$element['#ief_submit_trigger_all'] = TRUE;
}
/**
* Button #submit callback: Triggers submission of element forms.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
public static function trigger(array &$form, FormStateInterface $form_state) {
$triggered_element = $form_state->getTriggeringElement();
if (!empty($triggered_element['#ief_submit_trigger_all'])) {
// The parent form was submitted, process all IEFs and their children.
static::doSubmit($form, $form_state);
}
else {
// A specific element was submitted, process it and all of its children.
$array_parents = $triggered_element['#array_parents'];
$array_parents = array_slice($array_parents, 0, -2);
$element = NestedArray::getValue($form, $array_parents);
static::doSubmit($element, $form_state);
}
}
/**
* Submits elements by calling their #ief_element_submit callbacks.
*
* @param array $element
* The element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
public static function doSubmit(array &$element, FormStateInterface $form_state) {
// Recurse through all children.
foreach (Element::children($element) as $key) {
if (!empty($element[$key])) {
static::doSubmit($element[$key], $form_state);
}
}
// If there are callbacks on this level, run them.
if (!empty($element['#ief_element_submit'])) {
foreach ($element['#ief_element_submit'] as $callback) {
call_user_func_array($callback, [&$element, &$form_state]);
}
}
}
}
@@ -0,0 +1,366 @@
<?php
namespace Drupal\inline_entity_form\Form;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Render\Element;
use Drupal\inline_entity_form\InlineFormInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Generic entity inline form handler.
*/
class EntityInlineForm implements InlineFormInterface {
use StringTranslationTrait;
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity type managed by this handler.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* Module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* Constructs the inline entity form controller.
*
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*/
public function __construct(EntityFieldManagerInterface $entity_field_manager, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, EntityTypeInterface $entity_type) {
$this->entityFieldManager = $entity_field_manager;
$this->entityTypeManager = $entity_type_manager;
$this->moduleHandler = $module_handler;
$this->entityType = $entity_type;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$container->get('entity_field.manager'),
$container->get('entity_type.manager'),
$container->get('module_handler'),
$entity_type
);
}
/**
* {@inheritdoc}
*/
public function getEntityType() {
return $this->entityType;
}
/**
* {@inheritdoc}
*/
public function getEntityTypeLabels() {
$lowercase_label = $this->entityType->getSingularLabel();
return [
'singular' => $lowercase_label,
'plural' => $this->t('@entity_type entities', ['@entity_type' => $lowercase_label]),
];
}
/**
* {@inheritdoc}
*/
public function getEntityLabel(EntityInterface $entity) {
return $entity->label();
}
/**
* {@inheritdoc}
*/
public function getTableFields($bundles) {
$definitions = $this->entityFieldManager->getBaseFieldDefinitions($this->entityType->id());
$label_key = $this->entityType->getKey('label');
$label_field_label = $this->t('Label');
if ($label_key && isset($definitions[$label_key])) {
$label_field_label = $definitions[$label_key]->getLabel();
}
$bundle_key = $this->entityType->getKey('bundle');
$bundle_field_label = $this->t('Type');
if ($bundle_key && isset($definitions[$bundle_key])) {
$bundle_field_label = $definitions[$bundle_key]->getLabel();
}
$fields = [];
$fields['label'] = [
'type' => 'label',
'label' => $label_field_label,
'weight' => 1,
];
if (count($bundles) > 1) {
$fields[$bundle_key] = [
'type' => 'field',
'label' => $bundle_field_label,
'weight' => 2,
'display_options' => [
'type' => 'entity_reference_label',
'settings' => ['link' => FALSE],
],
];
}
return $fields;
}
/**
* {@inheritdoc}
*/
public function isTableDragEnabled($element) {
$children = Element::children($element);
// If there is only one row, disable tabledrag.
if (count($children) == 1) {
return FALSE;
}
// If one of the rows is in form context, disable tabledrag.
foreach ($children as $key) {
if (!empty($element[$key]['form'])) {
return FALSE;
}
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function entityForm(array $entity_form, FormStateInterface $form_state) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $entity_form['#entity'];
$form_display = $this->getFormDisplay($entity, $entity_form['#form_mode']);
$form_display->buildForm($entity, $entity_form, $form_state);
$entity_form['#ief_element_submit'][] = [
get_class($this),
'submitCleanFormState',
];
// Inline entities inherit the parent language.
$langcode_key = $this->entityType->getKey('langcode');
if ($langcode_key && isset($entity_form[$langcode_key])) {
$entity_form[$langcode_key]['#access'] = FALSE;
}
if (!empty($entity_form['#translating'])) {
// Hide the non-translatable fields.
foreach ($entity->getFieldDefinitions() as $field_name => $definition) {
if (isset($entity_form[$field_name]) && $field_name != $langcode_key) {
$entity_form[$field_name]['#access'] = $definition->isTranslatable();
}
}
}
// Hide the log message field for revisionable entity types. It cannot be
// disabled in UI and does not make sense in inline entity form context.
if (($this->entityType instanceof ContentEntityTypeInterface)) {
if ($log_message_key = $this->entityType->getRevisionMetadataKey('revision_log_message')) {
$entity_form[$log_message_key]['#access'] = FALSE;
}
}
// Determine the children of the entity form before it has been altered.
$children_before = Element::children($entity_form);
// Allow other modules to alter the form.
$this->moduleHandler->alter('inline_entity_form_entity_form', $entity_form, $form_state);
// Determine the children of the entity form after it has been altered.
$children_after = Element::children($entity_form);
// Ensure that any new children added have #tree, #parents, #array_parents
// and handle setting the proper #group if it's referencing a local element.
// Note: the #tree, #parents and #array_parents code is a direct copy from
// \Drupal\Core\Form\FormBuilder::doBuildForm.
$children_diff = array_diff($children_after, $children_before);
foreach ($children_diff as $child) {
// Don't squash an existing tree value.
if (!isset($entity_form[$child]['#tree'])) {
$entity_form[$child]['#tree'] = $entity_form['#tree'];
}
// Don't squash existing parents value.
if (!isset($entity_form[$child]['#parents'])) {
// Check to see if a tree of child elements is present. If so,
// continue down the tree if required.
$entity_form[$child]['#parents'] = $entity_form[$child]['#tree'] && $entity_form['#tree'] ? array_merge($entity_form['#parents'], [$child]) : [$child];
}
// Ensure #array_parents follows the actual form structure.
$array_parents = $entity_form['#array_parents'];
$array_parents[] = $child;
$entity_form[$child]['#array_parents'] = $array_parents;
// Detect if there is a #group and it specifies a local element. If so,
// change it to use the proper local element's #parents group name.
if (isset($entity_form[$child]['#group']) && isset($entity_form[$entity_form[$child]['#group']])) {
$entity_form[$child]['#group'] = implode('][', $entity_form[$entity_form[$child]['#group']]['#parents']);
}
}
$entity_form['#attached']['library'][] = 'core/drupal.form';
return $entity_form;
}
/**
* {@inheritdoc}
*/
public function entityFormValidate(array &$entity_form, FormStateInterface $form_state) {
// Perform entity validation only if the inline form was submitted,
// skipping other requests such as file uploads.
$triggering_element = $form_state->getTriggeringElement();
if (!empty($triggering_element['#ief_submit_trigger'])) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $entity_form['#entity'];
$this->buildEntity($entity_form, $entity, $form_state);
$form_display = $this->getFormDisplay($entity, $entity_form['#form_mode']);
$form_display->validateFormValues($entity, $entity_form, $form_state);
$entity->setValidationRequired(FALSE);
foreach ($form_state->getErrors() as $message) {
// $name may be unknown in $form_state and
// $form_state->setErrorByName($name, $message) may suppress the error
// message.
$form_state->setError($triggering_element, $message);
}
}
}
/**
* {@inheritdoc}
*/
public function entityFormSubmit(array &$entity_form, FormStateInterface $form_state) {
$form_state->cleanValues();
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $entity_form['#entity'];
$this->buildEntity($entity_form, $entity, $form_state);
}
/**
* {@inheritdoc}
*/
public function save(EntityInterface $entity) {
$entity->save();
}
/**
* {@inheritdoc}
*/
public function delete($ids, $context) {
$storage_handler = $this->entityTypeManager->getStorage($this->entityType->id());
$entities = $storage_handler->loadMultiple($ids);
$storage_handler->delete($entities);
}
/**
* Builds an updated entity object based upon the submitted form values.
*
* @param array $entity_form
* The entity form.
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
protected function buildEntity(array $entity_form, ContentEntityInterface $entity, FormStateInterface $form_state) {
$form_display = $this->getFormDisplay($entity, $entity_form['#form_mode']);
$form_display->extractFormValues($entity, $entity_form, $form_state);
// Invoke all specified builders for copying form values to entity fields.
if (isset($entity_form['#entity_builders'])) {
foreach ($entity_form['#entity_builders'] as $function) {
call_user_func_array(
$function,
[$entity->getEntityTypeId(), $entity, &$entity_form, &$form_state]
);
}
}
}
/**
* Cleans up the form state for a submitted entity form.
*
* After field_attach_submit() has run and the form has been closed, the form
* state still contains field data in $form_state->get('field'). Unless that
* data is removed, the next form with the same #parents (reopened add
* form, for example) will contain data (i.e. uploaded files) from the
* previous form.
*
* @param array $entity_form
* The entity form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* The form state of the parent form.
*/
public static function submitCleanFormState(array &$entity_form, FormStateInterface $form_state) {
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $entity_form['#entity'];
$bundle = $entity->bundle();
/** @var \Drupal\Core\Field\FieldDefinitionInterface[] $instances */
$instances = \Drupal::service('entity_field.manager')->getFieldDefinitions($entity_form['#entity_type'], $bundle);
foreach ($instances as $instance) {
$field_name = $instance->getName();
if (!empty($entity_form[$field_name]['#parents'])) {
$parents = $entity_form[$field_name]['#parents'];
array_pop($parents);
if (!empty($parents)) {
$field_state = [];
WidgetBase::setWidgetState($parents, $field_name, $form_state, $field_state);
}
}
}
}
/**
* Gets the form display for the given entity.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity.
* @param string $form_mode
* The form mode.
*
* @return \Drupal\Core\Entity\Display\EntityFormDisplayInterface
* The form display.
*/
protected function getFormDisplay(ContentEntityInterface $entity, $form_mode) {
return EntityFormDisplay::collectRenderDisplay($entity, $form_mode);
}
}
@@ -0,0 +1,47 @@
<?php
namespace Drupal\inline_entity_form\Form;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Node inline form handler.
*/
class NodeInlineForm extends EntityInlineForm {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
public function getEntityTypeLabels() {
$labels = [
'singular' => $this->t('node'),
'plural' => $this->t('nodes'),
];
return $labels;
}
/**
* {@inheritdoc}
*/
public function getTableFields($bundles) {
$fields = parent::getTableFields($bundles);
$fields['status'] = [
'type' => 'field',
'label' => $this->t('Status'),
'weight' => 100,
'display_options' => [
'settings' => [
'format' => 'custom',
'format_custom_false' => $this->t('Unpublished'),
'format_custom_true' => $this->t('Published'),
],
],
];
return $fields;
}
}
@@ -0,0 +1,146 @@
<?php
namespace Drupal\inline_entity_form;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Defines the interface for inline form handlers.
*/
interface InlineFormInterface extends EntityHandlerInterface {
/**
* Gets the entity type managed by this handler.
*
* @return \Drupal\Core\Entity\EntityTypeInterface
* The entity type.
*/
public function getEntityType();
/**
* Gets the entity type labels (singular, plural).
*
* @todo Remove when #1850080 lands and IEF starts requiring Drupal 8.1.x
*
* @return array
* An array with two values:
* - singular: The lowercase singular label.
* - plural: The lowercase plural label.
*/
public function getEntityTypeLabels();
/**
* Gets the label of the given entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The given entity.
*
* @return string
* The entity label.
*/
public function getEntityLabel(EntityInterface $entity);
/**
* Gets the columns used to represent an entity in the IEF table.
*
* Modules can alter the output of this method through
* hook_inline_entity_form_table_fields_alter().
*
* @param string[] $bundles
* An array of allowed bundles for this widget.
*
* @return array
* An array of data about table columns keyed by column name. Each column is
* represented by an associative array containing the following keys:
* - type: One of 'label', 'field' or 'callback', which indicates how this
* column should be handled:
* - 'label': The entity's label.
* - 'field': A field value from the entity. The name of the field is
* given by the key in this array.
* - 'callback': A callback, given by the 'callback' property.
* @see template_preprocess_inline_entity_form_entity_table()
* - label: the title of the table field's column in the IEF table.
* - weight: the sort order of the column in the IEF table.
* - display_options: (optional) used for 'field' type table columns, an
* array of display settings. See EntityViewBuilderInterface::viewField().
* - callback: for 'callback' type table columns, a callable that returns a
* renderable array.
* - callback_arguments: (optional) an array of additional arguments to pass
* to the callback. The entity and the theme variables are always passed
* as as the first two arguments.
*/
public function getTableFields(array $bundles);
/**
* Checks whether tabledrag should be enabled for the given table.
*
* @param array $element
* The form element representing the IEF table.
*
* @return bool
* TRUE if tabledrag should be enabled, FALSE otherwise.
*/
public function isTableDragEnabled(array $element);
/**
* Builds the entity form.
*
* @param array $entity_form
* The entity form, containing the following basic properties:
* - #entity: The entity for the current entity form.
* - #op: The form operation. 'add' or 'edit'.
* - #form_mode: The form mode used to display the entity form.
* - #parents: Identifies the position of the entity form in the overall
* parent form, and identifies the location where the field values are
* placed within $form_state->getValues().
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state of the parent form.
*/
public function entityForm(array $entity_form, FormStateInterface $form_state);
/**
* Validates the entity form.
*
* @param array $entity_form
* The entity form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state of the parent form.
*/
public function entityFormValidate(array &$entity_form, FormStateInterface $form_state);
/**
* Handles the submission of an entity form.
*
* @param array $entity_form
* The entity form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state of the parent form.
*/
public function entityFormSubmit(array &$entity_form, FormStateInterface $form_state);
/**
* Saves the given entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
*
* @return int
* Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
*/
public function save(EntityInterface $entity);
/**
* Delete permanently saved entities.
*
* @param int[] $ids
* An array of entity IDs.
* @param array $context
* Available keys:
* - parent_entity_type: The type of the parent entity.
* - parent_entity: The parent entity.
*/
public function delete(array $ids, array $context);
}
@@ -0,0 +1,178 @@
<?php
namespace Drupal\inline_entity_form;
use Drupal\Component\Utility\NestedArray;
use Drupal\field\Plugin\migrate\source\d7\FieldInstance;
use Drupal\field\Plugin\migrate\source\d7\FieldInstancePerFormDisplay;
use Drupal\migrate\Exception\RequirementsException;
use Drupal\migrate\Plugin\MigrateSourceInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
/**
* Helper for migration hooks in inline_entity_form.module.
*/
class MigrationHelper {
/**
* Alters the field migrations for the inline_entity_form widget.
*
* @param array $migrations
* An array of migrations.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
public function alterPlugins(array &$migrations) {
foreach ($migrations as &$migration) {
/** @var \Drupal\migrate\Plugin\MigrateSourcePluginManager $source_plugin_manager */
$source_plugin_manager = \Drupal::service('plugin.manager.migrate.source');
$source = NULL;
if (!empty($migration['migration_group'])) {
// Integrate shared group configuration into the migration, in order to
// have full migration definitions in place.
$this->getMigrationWithSharedConfiguration($migration);
}
if (isset($migration['source']['plugin'])) {
$source = $source_plugin_manager->getDefinition($migration['source']['plugin']);
}
if (isset($source['class'])) {
// Field instance.
if ($source['class'] === FieldInstance::class) {
$settings = $migration['process']['settings'];
if (isset($settings['plugin'])) {
// Prepare for multiple plugins,
// as there was only one before:
$settings = [$settings];
}
$addition = [
'inline_entity_form' => [
'plugin' => 'inline_entity_form_field_instance_settings',
],
];
$settings = NestedArray::mergeDeepArray([$settings, $addition], TRUE);
$migration['process']['settings'] = $settings;
}
if (is_a($source['class'], FieldInstancePerFormDisplay::class, TRUE)) {
// Ensure the map exists and is an array:
if (!empty($migration['process']['options/type']['type']['map']) && is_array($migration['process']['options/type']['type']['map'])) {
$map_addition = [
'inline_entity_form_single' => 'inline_entity_form_simple',
'inline_entity_form' => 'inline_entity_form_complex',
];
$migration['process']['options/type']['type']['map'] = array_merge($migration['process']['options/type']['type']['map'], $map_addition);
}
}
}
}
}
/**
* Adds all bundles for the entity type to the row.
*
* Drupal 7 inline_entity_form set the target bundles to an empty array to
* indicate all bundles are referenced. In Drupal 8+ all the target bundles
* are listed in the handler settings. Therefore, when the target bundle is an
* empty array get all the bundles and put them on the row.
*
* @param \Drupal\migrate\Row $row
* The current row.
* @param \Drupal\migrate\Plugin\MigrateSourceInterface $source
* The source for this migration.
* @param \Drupal\migrate\Plugin\MigrationInterface $migration
* The migration.
*
* @throws \Exception
*/
public function alterRow(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
if ($source) {
if (get_class($source) === FieldInstance::class && $row->get('type') === 'entityreference') {
$widget = $row->get('widget/type');
if ($widget === 'inline_entity_form_single' || $widget === 'inline_entity_form') {
$data = $row->get('field_definition/data');
$definition = unserialize($data);
if (empty($definition['settings']['handler_settings']['target_bundles'])) {
$entity_type = $row->get('entity_type');
$bundles = $this->getBundles($source, $entity_type);
}
}
}
$bundles = $bundles ?? [];
$row->setSourceProperty('target_bundles', $bundles);
}
}
/**
* Helper to get the bundles for an entity type.
*
* This currently only works for nodes. To add other entity types add a new
* case to the switch statement below and either use a query to get the
* bundles or hard code the values for you source site.
*
* @param \Drupal\migrate\Plugin\MigrateSourceInterface $source_plugin
* The source plugin.
* @param string $entity_type
* The entity type.
*
* @return array
* The product types.
*/
protected function getBundles(MigrateSourceInterface $source_plugin, $entity_type) {
$bundles = NULL;
$connection = NULL;
try {
$connection = $source_plugin->getDatabase();
}
catch (RequirementsException $e) {
}
if ($connection) {
switch ($entity_type) {
case 'node':
if ($connection->schema()->tableExists('node_type')) {
$query = $connection->select('node_type', 't')->fields('t');
$bundles = $query->execute()->fetchCol();
}
break;
default:
break;
}
}
return $bundles;
}
/**
* Helper to get the full migration with shared configuration.
*
* @param array $migration
* The migration to process.
*/
protected function getMigrationWithSharedConfiguration(array &$migration) {
// Integrate shared group configuration into the migration.
if (!empty($migration['migration_group'])) {
$group = \Drupal\migrate_plus\Entity\MigrationGroup::load($migration['migration_group']);
$shared_configuration = !empty($group) ? $group->get('shared_configuration') : [];
if (!empty($shared_configuration)) {
foreach ($shared_configuration as $key => $group_value) {
$migration_value = $migration[$key] ?? NULL;
// Where both the migration and the group provide arrays, replace
// recursively (so each key collision is resolved in favor of the
// migration).
if (is_array($migration_value) && is_array($group_value)) {
$merged_values = array_replace_recursive($group_value, $migration_value);
$migration[$key] = $merged_values;
}
// Where the group provides a value the migration doesn't, use the group
// value.
elseif (is_null($migration_value)) {
$migration[$key] = $group_value;
}
// Otherwise, the existing migration value overrides the group value.
}
}
}
}
}
@@ -0,0 +1,609 @@
<?php
namespace Drupal\inline_entity_form\Plugin\Field\FieldWidget;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\inline_entity_form\TranslationHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Inline entity form widget base class.
*/
abstract class InlineEntityFormBase extends WidgetBase implements ContainerFactoryPluginInterface {
/**
* The inline entity form id.
*
* @var string
*/
protected $iefId;
/**
* The entity type bundle info.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The inline entity from handler.
*
* @var \Drupal\inline_entity_form\InlineFormInterface
*/
protected $inlineFormHandler;
/**
* The entity display repository.
*
* @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
*/
protected $entityDisplayRepository;
/**
* Constructs an InlineEntityFormBase object.
*
* @param string $plugin_id
* The plugin_id for the widget.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The definition of the field to which the widget is associated.
* @param array $settings
* The widget settings.
* @param array $third_party_settings
* Any third party settings.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
* The entity display repository.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityTypeBundleInfoInterface $entity_type_bundle_info, EntityTypeManagerInterface $entity_type_manager, EntityDisplayRepositoryInterface $entity_display_repository) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
$this->entityTypeBundleInfo = $entity_type_bundle_info;
$this->entityTypeManager = $entity_type_manager;
$this->entityDisplayRepository = $entity_display_repository;
$this->createInlineFormHandler();
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['third_party_settings'],
$container->get('entity_type.bundle.info'),
$container->get('entity_type.manager'),
$container->get('entity_display.repository')
);
}
/**
* Creates an instance of the inline form handler for the current entity type.
*/
protected function createInlineFormHandler() {
if (!isset($this->inlineFormHandler)) {
$target_type = $this->getFieldSetting('target_type');
$this->inlineFormHandler = $this->entityTypeManager->getHandler($target_type, 'inline_form');
}
}
/**
* {@inheritdoc}
*/
public function __sleep() {
$keys = array_diff(parent::__sleep(), ['inlineFormHandler']);
return $keys;
}
/**
* {@inheritdoc}
*/
public function __wakeup() {
parent::__wakeup();
$this->createInlineFormHandler();
}
/**
* Sets inline entity form ID.
*
* @param string $ief_id
* The inline entity form ID.
*
* @see ::makeIefId
*/
protected function setIefId($ief_id) {
$this->iefId = $ief_id;
}
/**
* Gets inline entity form ID.
*
* @return string
* Inline entity form ID.
*/
protected function getIefId() {
return $this->iefId;
}
/**
* Makes an IEF ID from array parents.
*
* IEF ID is used a) for element ID, b) for form state keys.
* We need the IEF form ID to reflect the tree structure of IEFs, so that
* the form state keys can be sorted to ensure inside-out saving of entities.
*
* Also, "add" and "edit" IEFs have different array parents, which messes up
* form state, so we fixup this here with a, errrm, pragmatic hack.
*
* @param string[] $parents
* The array parents.
*
* @see \Drupal\inline_entity_form\WidgetSubmit::doSubmit
*
* @return string
* The resulting inline entity form ID.
*/
protected function makeIefId(array $parents) {
$iefId = implode('-', $parents);
$iefId = preg_replace('#-inline_entity_form-entities-([0-9]+)-form-#', '-$1-', $iefId);
return $iefId;
}
/**
* Gets the target bundles for the current field.
*
* @return string[]
* A list of bundles.
*/
protected function getTargetBundles() {
$settings = $this->getFieldSettings();
if (!empty($settings['handler_settings']['target_bundles'])) {
$target_bundles = array_values($settings['handler_settings']['target_bundles']);
// Filter out target bundles which no longer exist.
$existing_bundles = array_keys($this->entityTypeBundleInfo->getBundleInfo($settings['target_type']));
$target_bundles = array_intersect($target_bundles, $existing_bundles);
}
else {
// If no target bundles have been specified then all are available.
$target_bundles = array_keys($this->entityTypeBundleInfo->getBundleInfo($settings['target_type']));
}
return $target_bundles;
}
/**
* Gets the bundles for which the current user has create access.
*
* @return string[]
* The list of bundles.
*/
protected function getCreateBundles() {
$create_bundles = [];
foreach ($this->getTargetBundles() as $bundle) {
if ($this->getAccessHandler()->createAccess($bundle)) {
$create_bundles[] = $bundle;
}
}
return $create_bundles;
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'form_mode' => 'default',
'revision' => FALSE,
'override_labels' => FALSE,
'label_singular' => '',
'label_plural' => '',
'collapsible' => FALSE,
'collapsed' => FALSE,
];
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$entity_type_id = $this->getFieldSetting('target_type');
$states_prefix = 'fields[' . $this->fieldDefinition->getName() . '][settings_edit_form][settings]';
$element = [];
$element['form_mode'] = [
'#type' => 'select',
'#title' => $this->t('Form mode'),
'#default_value' => $this->getSetting('form_mode'),
'#options' => $this->entityDisplayRepository->getFormModeOptions($entity_type_id),
'#required' => TRUE,
];
$element['revision'] = [
'#type' => 'checkbox',
'#title' => $this->t('Create new revision'),
'#default_value' => $this->getSetting('revision'),
];
$element['override_labels'] = [
'#type' => 'checkbox',
'#title' => $this->t('Override labels'),
'#default_value' => $this->getSetting('override_labels'),
];
$element['label_singular'] = [
'#type' => 'textfield',
'#title' => $this->t('Singular label'),
'#default_value' => $this->getSetting('label_singular'),
'#states' => [
'visible' => [
':input[name="' . $states_prefix . '[override_labels]"]' => ['checked' => TRUE],
],
],
];
$element['label_plural'] = [
'#type' => 'textfield',
'#title' => $this->t('Plural label'),
'#default_value' => $this->getSetting('label_plural'),
'#states' => [
'visible' => [
':input[name="' . $states_prefix . '[override_labels]"]' => ['checked' => TRUE],
],
],
];
$element['collapsible'] = [
'#type' => 'checkbox',
'#title' => $this->t('Collapsible'),
'#default_value' => $this->getSetting('collapsible'),
];
$element['collapsed'] = [
'#type' => 'checkbox',
'#title' => $this->t('Collapsed by default'),
'#default_value' => $this->getSetting('collapsed'),
'#states' => [
'visible' => [
':input[name="' . $states_prefix . '[collapsible]"]' => ['checked' => TRUE],
],
],
];
return $element;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
if ($entity_form_mode = $this->getEntityFormMode()) {
$form_mode_label = $entity_form_mode->label();
}
else {
$form_mode_label = $this->t('Default');
}
$summary[] = $this->t('Form mode: @mode', ['@mode' => $form_mode_label]);
if ($this->getSetting('override_labels')) {
$summary[] = $this->t(
'Overriden labels are used: %singular and %plural',
[
'%singular' => $this->getSetting('label_singular'),
'%plural' => $this->getSetting('label_plural'),
]
);
}
else {
$summary[] = $this->t('Default labels are used.');
}
if ($this->getSetting('revision')) {
$summary[] = $this->t('Create new revision');
}
if ($this->getSetting('collapsible')) {
$summary[] = $this->getSetting('collapsed') ? $this->t('Collapsible, collapsed by default') : $this->t('Collapsible');
}
return $summary;
}
/**
* Gets the entity type managed by this handler.
*
* @return \Drupal\Core\Entity\EntityTypeInterface
* The entity type.
*/
protected function getEntityTypeLabels() {
// The admin has specified the exact labels that should be used.
if ($this->getSetting('override_labels')) {
return [
'singular' => $this->getSetting('label_singular'),
'plural' => $this->getSetting('label_plural'),
];
}
else {
$this->createInlineFormHandler();
return $this->inlineFormHandler->getEntityTypeLabels();
}
}
/**
* Checks whether we can build entity form at all.
*
* - Is IEF handler loaded?
* - Are we on a "real" entity form and not on default value widget?
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*
* @return bool
* TRUE if we are able to proceed with form build and FALSE if not.
*/
protected function canBuildForm(FormStateInterface $form_state) {
if ($this->isDefaultValueWidget($form_state)) {
return FALSE;
}
if (!$this->inlineFormHandler) {
return FALSE;
}
return TRUE;
}
/**
* Prepares the form state for the current widget.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
* @param \Drupal\Core\Field\FieldItemListInterface $items
* The field values.
* @param bool $translating
* Whether there's a translation in progress.
*/
protected function prepareFormState(FormStateInterface $form_state, FieldItemListInterface $items, $translating = FALSE) {
$widget_state = $form_state->get(['inline_entity_form', $this->iefId]);
if (empty($widget_state)) {
$widget_state = [
'instance' => $this->fieldDefinition,
'form' => NULL,
'delete' => [],
'entities' => [],
];
// Store the $items entities in the widget state, for further
// manipulation.
foreach ($items->referencedEntities() as $delta => $entity) {
// Display the entity in the correct translation.
if ($translating) {
$entity = TranslationHelper::prepareEntity($entity, $form_state);
}
$widget_state['entities'][$delta] = [
'entity' => $entity,
'weight' => $delta,
'form' => NULL,
'needs_save' => $entity->isNew(),
];
}
$form_state->set(['inline_entity_form', $this->iefId], $widget_state);
}
}
/**
* Gets inline entity form element.
*
* @param string $operation
* The operation (i.e. 'add' or 'edit').
* @param string $bundle
* Entity bundle.
* @param string $langcode
* Entity langcode.
* @param string $delta
* Delta.
* @param array $parents
* Array of parent element names.
* @param \Drupal\Core\Entity\EntityInterface $entity
* Optional entity object.
*
* @return array
* IEF form element structure.
*/
protected function getInlineEntityForm($operation, $bundle, $langcode, $delta, array $parents, EntityInterface $entity = NULL) {
$element = [
'#type' => 'inline_entity_form',
'#entity_type' => $this->getFieldSetting('target_type'),
'#bundle' => $bundle,
'#langcode' => $langcode,
'#default_value' => $entity,
'#op' => $operation,
'#form_mode' => $this->getSetting('form_mode'),
'#revision' => $this->getSetting('revision'),
'#save_entity' => FALSE,
'#ief_row_delta' => $delta,
// Used by Field API and controller methods to find the relevant
// values in $form_state.
'#parents' => $parents,
// Labels could be overridden in field widget settings. We won't have
// access to those in static callbacks (#process, ...) so let's add
// them here.
'#ief_labels' => $this->getEntityTypeLabels(),
// Identifies the IEF widget to which the form belongs.
'#ief_id' => $this->getIefId(),
];
return $element;
}
/**
* Determines whether there's a translation in progress.
*
* Ensures that at least one target bundle has translations enabled.
* Otherwise the widget will skip translation even if it's happening
* on the parent form itself.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return bool
* TRUE if translating is in progress, FALSE otherwise.
*
* @see \Drupal\inline_entity_form\TranslationHelper::initFormLangcodes()
*
* @todo Replace line 472 \Drupal call with Dependency Injection.
*/
protected function isTranslating(FormStateInterface $form_state) {
if (\Drupal::hasService('content_translation.manager') && TranslationHelper::isTranslating($form_state)) {
$translation_manager = \Drupal::service('content_translation.manager');
$target_type = $this->getFieldSetting('target_type');
foreach ($this->getTargetBundles() as $bundle) {
if ($translation_manager->isEnabled($target_type, $bundle)) {
return TRUE;
}
}
}
return FALSE;
}
/**
* After-build callback for removing the translatability clue from the widget.
*
* IEF expects the entity reference field to not be translatable, to avoid
* different translations having different references.
* However, that causes ContentTranslationHandler::addTranslatabilityClue()
* to add an "(all languages)" suffix to the widget title. That suffix is
* incorrect, since IEF does ensure that specific entity translations are
* being edited.
*/
public static function removeTranslatabilityClue(array $element, FormStateInterface $form_state) {
$element['#title'] = $element['#field_title'];
return $element;
}
/**
* Adds submit callbacks to the inline entity form.
*
* @param array $element
* Form array structure.
*/
public static function addIefSubmitCallbacks(array $element) {
$element['#ief_element_submit'][] = [get_called_class(), 'submitSaveEntity'];
return $element;
}
/**
* Marks created/edited entity with "needs save" flag.
*
* Note that at this point the entity is not yet saved, since the user might
* still decide to cancel the parent form.
*
* @param array $entity_form
* The form of the entity being managed inline.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state of the parent form.
*/
public static function submitSaveEntity(array $entity_form, FormStateInterface $form_state) {
$ief_id = $entity_form['#ief_id'];
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $entity_form['#entity'];
if (in_array($entity_form['#op'], ['add', 'duplicate'])) {
// Determine the correct weight of the new element.
$weight = 0;
$entities = $form_state->get(['inline_entity_form', $ief_id, 'entities']);
if (!empty($entities)) {
$weight = max(array_keys($entities)) + 1;
}
// Add the entity to form state, mark it for saving, and close the form.
$entities[] = [
'entity' => $entity,
'weight' => $weight,
'form' => NULL,
'needs_save' => TRUE,
];
$form_state->set(['inline_entity_form', $ief_id, 'entities'], $entities);
}
else {
$delta = $entity_form['#ief_row_delta'];
$entities = $form_state->get(['inline_entity_form', $ief_id, 'entities']);
$entities[$delta]['entity'] = $entity;
$entities[$delta]['needs_save'] = TRUE;
$form_state->set(['inline_entity_form', $ief_id, 'entities'], $entities);
}
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$dependencies = parent::calculateDependencies();
if ($entity_form_mode = $this->getEntityFormMode()) {
$dependencies['config'][] = $entity_form_mode->getConfigDependencyName();
}
return $dependencies;
}
/**
* Gets the entity form mode instance for this widget.
*
* @return \Drupal\Core\Entity\EntityFormModeInterface|null
* The form mode instance, or NULL if the default one is used.
*/
protected function getEntityFormMode() {
$form_mode = $this->getSetting('form_mode');
if ($form_mode != 'default') {
$entity_type_id = $this->getFieldSetting('target_type');
return $this->entityTypeManager->getStorage('entity_form_mode')->load($entity_type_id . '.' . $form_mode);
}
return NULL;
}
/**
* Gets the access handler for the target entity type.
*
* @return \Drupal\Core\Entity\EntityAccessControlHandlerInterface
* The access handler.
*/
protected function getAccessHandler() {
$entity_type_id = $this->getFieldSetting('target_type');
return $this->entityTypeManager->getAccessControlHandler($entity_type_id);
}
/**
* {@inheritdoc}
*/
public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
if ($this->canBuildForm($form_state)) {
return parent::form($items, $form, $form_state, $get_delta);
}
return [];
}
/**
* Determines if the current user can add any new entities.
*
* @return bool
* Returns bool to allow or not new entity additions.
*/
protected function canAddNew() {
$create_bundles = $this->getCreateBundles();
return !empty($create_bundles);
}
}
@@ -0,0 +1,221 @@
<?php
namespace Drupal\inline_entity_form\Plugin\Field\FieldWidget;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\inline_entity_form\TranslationHelper;
/**
* Simple inline widget.
*
* @FieldWidget(
* id = "inline_entity_form_simple",
* label = @Translation("Inline entity form - Simple"),
* field_types = {
* "entity_reference",
* "entity_reference_revisions",
* },
* multiple_values = false
* )
*/
class InlineEntityFormSimple extends InlineEntityFormBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
// Trick inline_entity_form_form_alter() into attaching the handlers,
// WidgetSubmit will be needed once extractFormValues fills the $form_state.
$parents = array_merge($element['#field_parents'], [$items->getName()]);
$ief_id = $this->makeIefId($parents);
$form_state->set(['inline_entity_form', $ief_id], []);
$element = [
'#type' => $this->getSetting('collapsible') ? 'details' : 'fieldset',
'#field_title' => $this->fieldDefinition->getLabel(),
'#after_build' => [
[get_class($this), 'removeTranslatabilityClue'],
],
] + $element;
if ($element['#type'] == 'details') {
// If there's user input, keep the details open. Otherwise, use settings.
$element['#open'] = $form_state->getUserInput() ?: !$this->getSetting('collapsed');
}
$item = $items->get($delta);
if ($item->target_id && !$item->entity) {
$element['warning']['#markup'] = $this->t('Unable to load the referenced entity.');
return $element;
}
$entity = $item->entity;
$op = $entity ? 'edit' : 'add';
$langcode = $items->getEntity()->language()->getId();
$parents = array_merge($element['#field_parents'], [
$items->getName(),
$delta,
'inline_entity_form',
]);
$bundle = $this->getBundle();
$element['inline_entity_form'] = $this->getInlineEntityForm($op, $bundle, $langcode, $delta, $parents, $entity);
if ($op == 'edit') {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
if (!$entity->access('update')) {
// The user isn't allowed to edit the entity, but still needs to see
// it, to be able to reorder values.
$element['entity_label'] = [
'#type' => 'markup',
'#markup' => $entity->label(),
];
// Hide the inline form. getInlineEntityForm() still needed to be
// called because otherwise the field re-ordering doesn't work.
$element['inline_entity_form']['#access'] = FALSE;
}
}
return $element;
}
/**
* {@inheritdoc}
*/
protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
$element = parent::formMultipleElements($items, $form, $form_state);
// If we're using unlimited cardinality we don't display one empty item.
// Form validation will kick in if left empty which essentially means
// people won't be able to submit without creating another entity.
if (!$form_state->isSubmitted() && $element['#cardinality'] == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && $element['#max_delta'] > 0) {
$max = $element['#max_delta'];
unset($element[$max]);
$element['#max_delta'] = $max - 1;
$items->removeItem($max);
// Decrement the items count.
$field_name = $element['#field_name'];
$parents = $element[0]['#field_parents'];
$field_state = static::getWidgetState($parents, $field_name, $form_state);
$field_state['items_count']--;
static::setWidgetState($parents, $field_name, $form_state, $field_state);
}
// Remove add options if the user cannot add new entities.
if (!$this->canAddNew()) {
if (isset($element['add_more'])) {
unset($element['add_more']);
}
foreach (Element::children($element) as $delta) {
if (isset($element[$delta]['inline_entity_form'])) {
if ($element[$delta]['inline_entity_form']['#op'] == 'add') {
unset($element[$delta]);
}
}
}
}
return $element;
}
/**
* {@inheritdoc}
*/
public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state) {
if ($this->isDefaultValueWidget($form_state)) {
$items->filterEmptyItems();
return;
}
$field_name = $this->fieldDefinition->getName();
$parents = array_merge($form['#parents'], [$field_name]);
$submitted_values = $form_state->getValue($parents);
$values = [];
foreach ($items as $delta => $value) {
if ($element = NestedArray::getValue(
$form,
[$field_name, 'widget', $delta]
)) {
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $element['inline_entity_form']['#entity'];
$weight = $submitted_values[$delta]['_weight'] ?? 0;
$values[$weight] = ['entity' => $entity];
}
}
// Sort items base on weights.
ksort($values);
$values = array_values($values);
// Let the widget massage the submitted values.
$values = $this->massageFormValues($values, $form, $form_state);
// Assign the values and remove the empty ones.
$items->setValue($values);
$items->filterEmptyItems();
// Populate the IEF form state with $items so that WidgetSubmit can
// perform the necessary saves.
$ief_id = $this->makeIefId($parents);
$widget_state = [
'instance' => $this->fieldDefinition,
'delete' => [],
'entities' => [],
];
foreach ($items as $delta => $value) {
TranslationHelper::updateEntityLangcode($value->entity, $form_state);
$widget_state['entities'][$delta] = [
'entity' => $value->entity,
'needs_save' => TRUE,
];
}
$form_state->set(['inline_entity_form', $ief_id], $widget_state);
// Put delta mapping in $form_state, so that flagErrors() can use it.
$field_name = $this->fieldDefinition->getName();
$field_state = WidgetBase::getWidgetState($form['#parents'], $field_name, $form_state);
foreach ($items as $delta => $item) {
$field_state['original_deltas'][$delta] = $item->_original_delta ?? $delta;
unset($item->_original_delta, $item->weight);
}
WidgetBase::setWidgetState($form['#parents'], $field_name, $form_state, $field_state);
}
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
$handler_settings = $field_definition->getSettings()['handler_settings'];
$target_entity_type_id = $field_definition->getFieldStorageDefinition()->getSetting('target_type');
$target_entity_type = \Drupal::entityTypeManager()->getDefinition($target_entity_type_id);
// The target entity type doesn't use bundles, no need to validate them.
if (!$target_entity_type->getKey('bundle')) {
return TRUE;
}
if (empty($handler_settings['target_bundles'])) {
return FALSE;
}
if (count($handler_settings['target_bundles']) != 1) {
return FALSE;
}
return TRUE;
}
/**
* Gets the bundle for the inline entity.
*
* @return string|null
* The bundle, or NULL if not known.
*/
protected function getBundle() {
if (!empty($this->getFieldSetting('handler_settings')['target_bundles'])) {
return reset($this->getFieldSetting('handler_settings')['target_bundles']);
}
}
}
@@ -0,0 +1,38 @@
<?php
namespace Drupal\inline_entity_form\Plugin\migrate\process;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
/**
* Configure field instance settings for inline_form_entity.
*
* @MigrateProcessPlugin(
* id = "inline_entity_form_field_instance_settings"
* )
*/
class InlineFormEntityFieldInstanceSettings extends ProcessPluginBase {
/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
if ($row->getSourceProperty('type') === 'entityreference') {
$widget = $row->get('widget/type');
if ($widget === 'inline_entity_form_single' || $widget === 'inline_entity_form') {
$target_bundles = $row->get('target_bundles');
// The previous process,
// \Drupal\Tests\field\Unit\Plugin\migrate\process\d7\FieldInstanceSettingsTest
// sets target_bundles to NULL when the source target_bundles is an
// empty array.
if (is_null($value['handler_settings']['target_bundles'])) {
$value['handler_settings']['target_bundles'] = $target_bundles;
}
}
}
return $value;
}
}
@@ -0,0 +1,67 @@
<?php
namespace Drupal\inline_entity_form;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\TypedData\FieldItemDataDefinitionInterface;
/**
* Class ReferenceUpgrader.
*
* When saving nested IEFs inside-out, after saving an inner entity, we must
* "upgrade" its reference item with e.g. revision ID information.
*
* @see \Drupal\inline_entity_form\WidgetSubmit
*/
final class ReferenceUpgrader {
/**
* Registered entities, keyed by entity type, then ID.
*
* @var array
*/
private $entities = [];
/**
* Registers entities.
*/
public function registerEntity(EntityInterface $entity) {
$entityId = $entity->id() ?? $this->throwNeedsId();
$this->entities[$entity->getEntityTypeId()][$entityId] = $entity;
}
/**
* Throws exceptions on trying to register entities without id.
*/
private function throwNeedsId() {
throw new \RuntimeException("Can only register entity with ID.");
}
/**
* Upgrades entities references.
*/
public function upgradeEntityReferences(FieldableEntityInterface $entity) {
foreach ($entity as $fieldItemList) {
if (
$fieldItemList instanceof EntityReferenceFieldItemListInterface
&& ($targetEntityType = $fieldItemList->getFieldDefinition()->getSetting('target_type'))
&& ($itemDefinition = $fieldItemList->getItemDefinition())
&& $itemDefinition instanceof FieldItemDataDefinitionInterface
&& $itemDefinition->getPropertyDefinition('target_id')
) {
foreach ($fieldItemList as $fieldItem) {
assert($fieldItem instanceof FieldItemInterface);
if ($targetId = $fieldItem->target_id) {
if ($targetEntity = $this->entities[$targetEntityType][$targetId] ?? NULL) {
$fieldItem->setValue($targetEntity);
}
}
}
}
}
}
}
@@ -0,0 +1,117 @@
<?php
namespace Drupal\inline_entity_form;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides content translation helpers.
*/
class TranslationHelper {
/**
* Prepares the inline entity for translation.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The inline entity.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return \Drupal\Core\Entity\ContentEntityInterface
* The prepared entity.
*
* @see \Drupal\Core\Entity\ContentEntityForm::initFormLangcodes()
*/
public static function prepareEntity(ContentEntityInterface $entity, FormStateInterface $form_state) {
$form_langcode = $form_state->get('langcode');
if (empty($form_langcode) || !$entity->isTranslatable()) {
return $entity;
}
$entity_langcode = $entity->language()->getId();
if (self::isTranslating($form_state) && !$entity->hasTranslation($form_langcode)) {
// Create a translation from the source language values.
$source = $form_state->get(['content_translation', 'source']);
$source_langcode = $source ? $source->getId() : $entity_langcode;
if (!$entity->hasTranslation($source_langcode)) {
$entity->addTranslation($source_langcode, $entity->toArray());
}
$source_translation = $entity->getTranslation($source_langcode);
$entity->addTranslation($form_langcode, $source_translation->toArray());
$translation = $entity->getTranslation($form_langcode);
$translation->set('content_translation_source', $source_langcode);
// Make sure we do not inherit the affected status from the source values.
if ($entity->getEntityType()->isRevisionable()) {
$translation->setRevisionTranslationAffected(NULL);
}
}
if ($entity_langcode != $form_langcode && $entity->hasTranslation($form_langcode)) {
// Switch to the needed translation.
$entity = $entity->getTranslation($form_langcode);
}
return $entity;
}
/**
* Updates the entity langcode to match the form langcode.
*
* Called on submit to allow the user to select a different language through
* the langcode form element, which is then transferred to form state.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return bool
* TRUE if the entity langcode was updated, FALSE otherwise.
*/
public static function updateEntityLangcode(ContentEntityInterface $entity, FormStateInterface $form_state) {
$changed = FALSE;
// This method is first called during form validation, at which point
// the 'langcode' form state flag hasn't been updated with the new value.
$form_langcode = $form_state->getValue(['langcode', 0, 'value'], $form_state->get('langcode'));
if (empty($form_langcode) || !$entity->isTranslatable()) {
return $changed;
}
$entity_langcode = $entity->language()->getId();
if ($entity_langcode != $form_langcode && !$entity->hasTranslation($form_langcode)) {
$langcode_key = $entity->getEntityType()->getKey('langcode');
$entity->set($langcode_key, $form_langcode);
$changed = TRUE;
}
return $changed;
}
/**
* Determines whether there's a translation in progress.
*
* If the root entity is being translated, then all of the inline entities
* are candidates for translating as well.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return bool
* TRUE if translating is in progress, FALSE otherwise.
*
* @see \Drupal\Core\Entity\ContentEntityForm::initFormLangcodes()
*/
public static function isTranslating(FormStateInterface $form_state) {
$form_langcode = $form_state->get('langcode');
$default_langcode = $form_state->get('entity_default_langcode');
if (empty($form_langcode) && empty($default_langcode)) {
// The top-level form is not a content entity form.
return FALSE;
}
else {
return $form_langcode != $default_langcode;
}
}
}
@@ -0,0 +1,70 @@
<?php
namespace Drupal\inline_entity_form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\inline_entity_form\Element\InlineEntityForm;
/**
* Performs widget submission.
*
* Widgets don't save changed entities, nor do they delete removed entities.
* Instead, they flag them so that changes are only applied when the main form
* is submitted.
*/
class WidgetSubmit {
/**
* Attaches the widget submit functionality to the given form.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
public static function attach(array &$form, FormStateInterface $form_state) {
// $form['#ief_element_submit'] runs after the #ief_element_submit
// callbacks of all subelements, which means that doSubmit() has
// access to the final IEF $form_state.
$form['#ief_element_submit'][] = [get_called_class(), 'doSubmit'];
}
/**
* Submits the widget elements, saving and deleted entities where needed.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
public static function doSubmit(array $form, FormStateInterface $form_state) {
$referenceUpgrader = new ReferenceUpgrader();
$widget_states =& $form_state->get('inline_entity_form');
// Widget states can be in an arbitrary order depending on user's form
// interaction. We sort them lexicographically in reverse order to get inner
// forms before outer forms, to ensure inside-out saving of entities.
// @see \Drupal\inline_entity_form\Plugin\Field\FieldWidget\InlineEntityFormBase::makeIefId
krsort($widget_states, SORT_STRING);
foreach ($widget_states as &$widget_state) {
$widget_state += ['entities' => [], 'delete' => []];
foreach ($widget_state['entities'] as &$entity_item) {
if (!empty($entity_item['entity']) && !empty($entity_item['needs_save'])) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $entity_item['entity'];
$handler = InlineEntityForm::getInlineFormHandler($entity->getEntityTypeId());
$referenceUpgrader->upgradeEntityReferences($entity);
$handler->save($entity);
$referenceUpgrader->registerEntity($entity);
$entity_item['needs_save'] = FALSE;
}
}
/** @var \Drupal\Core\Entity\ContentEntityInterface $entities */
foreach ($widget_state['delete'] as $entity) {
$entity->delete();
}
unset($widget_state['delete']);
}
}
}