public function EntityFormField::saveEntities in Views Entity Form Field 8
Save the view's entities.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
File
- src/
Plugin/ views/ field/ EntityFormField.php, line 595
Class
- EntityFormField
- Defines a views form element for an entity field widget.
Namespace
Drupal\views_entity_form_field\Plugin\views\fieldCode
public function saveEntities(array &$form, FormStateInterface $form_state) {
// We only want to save the entity once per relationship.
if (is_null($form_state
->getTemporaryValue([
'saved_relationships',
$this->relationship,
]))) {
$storage = $this
->getEntityTypeManager()
->getStorage($this
->getEntityTypeId());
$rows_saved = [];
$rows_failed = [];
foreach ($this
->getView()->result as $row_index => $row) {
$entity = $this
->getEntity($row);
if ($entity) {
$entity = $this
->getEntityTranslation($entity, $row);
$original_entity = $this
->getEntityTranslation($storage
->loadUnchanged($entity
->id()), $row);
try {
if ($this
->entityShouldBeSaved($entity, $original_entity)) {
$storage
->save($entity);
$rows_saved[$row_index] = $entity
->label();
}
} catch (\Exception $exception) {
$rows_failed[$row_index] = $entity
->label();
}
}
}
// Let the user know how many entities were saved.
$messenger = \Drupal::messenger();
$entity_type_definition = $this->entityTypeManager
->getDefinition($this
->getEntityTypeId());
$messenger
->addStatus($this
->formatPlural(count($rows_saved), '@count @singular_label saved.', '@count @plural_label saved.', [
'@count' => count($rows_saved),
'@singular_label' => $entity_type_definition
->getSingularLabel(),
'@plural_label' => $entity_type_definition
->getPluralLabel(),
]));
// Let the user know which entities couldn't be saved.
if (count($rows_failed) > 0) {
$messenger
->addWarning($this
->formatPlural(count($rows_failed), '@count @singular_label failed to save: @labels', '@count @plural_label failed to save: @labels', [
'@count' => count($rows_failed),
'@singular_label' => $entity_type_definition
->getSingularLabel(),
'@plural_label' => $entity_type_definition
->getPluralLabel(),
'@labels' => implode(', ', $rows_failed),
]));
}
// Track that this relationship has been saved.
$form_state
->setTemporaryValue([
'saved_relationships',
$this->relationship,
], TRUE);
}
}