Submitted by elnk on
Bonjour,
Je viens de suivre la doc pour créer un champs personnalisé. Mais lorsque je souhaite faire de même sur un projet que j'ai déjà avancé, lorsque je sélectionne mon champs personnalisé dans l'onglet "Gérer les champs" d'un type de contenu, et que je souhaite l'enregistrer, il me vient l'erreur suivante :
This value should be of the correct primitive type.
J'ai bien trouvé ce poste qui en parle, https://www.drupal.org/node/2821260
Mais je ne vois pas comment utiliser la méthode massageFormValues() de WidgetBase.
Voici ma classe concernant le widget pour mon custom field :
<?php
namespace Drupal\custom_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Field\WidgetBaseInterface;
use Drupal\Core\Form\FormStateInterface;
/
* Plugin implementation of the 'Program' widget.
*
* @FieldWidget(
* id = "program_default",
* label = @Translation("Programmation"),
* field_types = {
* "program"
* }
* )
*/
class ProgramWidget extends WidgetBase implements WidgetBaseInterface {
/
* @param FieldItemListInterface $items
* @param int $delta
* @param array $element
* @param array $form
* @param FormStateInterface $form_state
* @return array
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['date'] = array(
'#type' => 'textfield',
'#title' => $this->t('Date'),
'#placeholder' => $this->getSetting('placeholder_date'),
'#default_value' => isset($items[$delta]->date) ? $items[$delta]->date : NULL,
'#required' => $element['#required'],
);
$element['programmation'] = array(
'#type' => 'text_format',
'#title' => $this->t('Programmation'),
'#placeholder' => $this->getSetting('placeholder_programmation'),
'#default_value' => isset($items[$delta]->programmation) ? $items[$delta]->programmation : NULL,
'#format' => 'full_html',
);
$element['field_widget_display']['#access'] = true;
$element['field_widget_display_settings']['#access'] = true;
return $element;
}
}
Je suis preneur pour un petit coup de main.
Solution :
Permalien Soumis par elnk le 6 Décembre, 2016 - 15:35
Solution :
/**
* {@inheritdoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as &$value) {
if (count($value['programmation'])) {
$value['programmation'] = $value['programmation']['value'];
} else {
$value['programmation'] = $value['programmation'] !== '' ? $value['programmation'] : '0';
}
}
return $values;
}