-
-
Save msankhala/04cef07da6e8a5b6ab38d70c3816dca7 to your computer and use it in GitHub Desktop.
Drupal 8 : Custom serializer example to render result as array instead of objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\MY_MODULE\Plugin\views\style; | |
use Drupal\rest\Plugin\views\style\Serializer; | |
/** | |
* The style plugin for serialized output formats. | |
* | |
* @ingroup views_style_plugins | |
* | |
* @ViewsStyle( | |
* id = "custom_serializer", | |
* title = @Translation("Custom serializer"), | |
* help = @Translation("Serializes views row data using the Serializer | |
* component."), display_types = {"data"} | |
* ) | |
*/ | |
class CustomSerializer extends Serializer { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function render() { | |
$rows = []; | |
// If the Data Entity row plugin is used, this will be an array of entities | |
// which will pass through Serializer to one of the registered Normalizers, | |
// which will transform it to arrays/scalars. If the Data field row plugin | |
// is used, $rows will not contain objects and will pass directly to the | |
// Encoder. | |
foreach ($this->view->result as $row_index => $row) { | |
$this->view->row_index = $row_index; | |
$row_render = $this->view->rowPlugin->render($row); | |
$iot_integer = 0; | |
if (isset($row_render["field_iot_integer"]) && $row_render["field_iot_integer"] instanceof \Drupal\Core\Render\Markup){ | |
$iot_integer = (int) $row_render["field_iot_integer"]->__toString(); | |
} | |
$rows[] = [ | |
$row_render["created"]->__toString(), | |
$iot_integer | |
]; | |
} | |
unset($this->view->row_index); | |
// Get the content type configured in the display or fallback to the | |
// default. | |
if ((empty($this->view->live_preview))) { | |
$content_type = $this->displayHandler->getContentType(); | |
} | |
else { | |
$content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json'; | |
} | |
return $this->serializer->serialize($rows, $content_type, ['views_style_plugin' => $this]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment