public function PollChoiceDefaultWidget::massageFormValues in Poll 8
Massages the form values into the format expected for field values.
Parameters
array $values: The submitted form values produced by the widget.
- If the widget does not manage multiple values itself, the array holds the values generated by the multiple copies of the $element generated by the formElement() method, keyed by delta.
- If the widget manages multiple values, the array holds the values of the form element generated by the formElement() method.
array $form: The form structure where field elements are attached to. This might be a full form structure, or a sub-element of a larger form.
\Drupal\Core\Form\FormStateInterface $form_state: The form state.
Return value
array An array of field values, keyed by delta.
Overrides WidgetBase::massageFormValues
File
- src/
Plugin/ Field/ FieldWidget/ PollChoiceDefaultWidget.php, line 98
Class
- PollChoiceDefaultWidget
- Plugin implementation of the 'poll_choice_default' widget.
Namespace
Drupal\poll\Plugin\Field\FieldWidgetCode
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as $delta => &$item_values) {
$entity_type_manager = \Drupal::entityTypeManager();
$storage = $entity_type_manager
->getStorage('poll_choice');
$langcode = $item_values['langcode'];
// Remove empty values. Removed choices will be deleted automatically.
if (empty($item_values['choice'])) {
unset($values[$delta]);
continue;
}
/** @var \Drupal\poll\PollChoiceInterface $choice */
$choice = !empty($item_values['target_id']) ? $storage
->load($item_values['target_id']) : $storage
->create([
'langcode' => $langcode,
]);
// If target translation is not yet available, populate it with data from the original choice.
if ($choice
->language()
->getId() != $langcode && !$choice
->hasTranslation($langcode)) {
$choice
->addTranslation($langcode, $choice
->toArray());
}
// Initiate the choice with the correct translation.
$choice = $choice
->getTranslation($langcode);
// If the choice is new or changed, resave it.
if ($choice
->isNew() || $item_values['choice'] != $choice->choice->value) {
$choice->choice->value = $item_values['choice'];
$choice
->needsSaving(TRUE);
}
unset($item_values['target_id'], $item_values['choice'], $item_values['langcode']);
$item_values['entity'] = $choice;
}
return $values;
}