3 namespace Drupal\views\Plugin\views\field;
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\views\ResultRow;
9 * Field handler to show data of serialized fields.
11 * @ingroup views_field_handlers
13 * @ViewsField("serialized")
15 class Serialized extends FieldPluginBase {
20 protected function defineOptions() {
21 $options = parent::defineOptions();
22 $options['format'] = ['default' => 'unserialized'];
23 $options['key'] = ['default' => ''];
30 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
31 parent::buildOptionsForm($form, $form_state);
35 '#title' => $this->t('Display format'),
36 '#description' => $this->t('How should the serialized data be displayed. You can choose a custom array/object key or a print_r on the full output.'),
38 'unserialized' => $this->t('Full data (unserialized)'),
39 'serialized' => $this->t('Full data (serialized)'),
40 'key' => $this->t('A certain key'),
42 '#default_value' => $this->options['format'],
45 '#type' => 'textfield',
46 '#title' => $this->t('Which key should be displayed'),
47 '#default_value' => $this->options['key'],
50 ':input[name="options[format]"]' => ['value' => 'key'],
59 public function validateOptionsForm(&$form, FormStateInterface $form_state) {
60 // Require a key if the format is key.
61 if ($form_state->getValue(['options', 'format']) == 'key' && $form_state->getValue(['options', 'key']) == '') {
62 $form_state->setError($form['key'], $this->t('You have to enter a key if you want to display a key of the data.'));
69 public function render(ResultRow $values) {
70 $value = $values->{$this->field_alias};
72 if ($this->options['format'] == 'unserialized') {
73 return $this->sanitizeValue(print_r(unserialize($value), TRUE));
75 elseif ($this->options['format'] == 'key' && !empty($this->options['key'])) {
76 $value = (array) unserialize($value);
77 return $this->sanitizeValue($value[$this->options['key']]);