如何解决如何将根名称和子名称添加到 drupal 视图 REST?
我有一个疑问,我已经用 View 创建了一个 REST 并且我的格式像 JSON,但输出是这样的:
[{"item1":"123","item2":"123","item3":"123","item4":"","item5":"123","item5":"123"},{"item1":"345","item2":"345","item3":"345","item5":"345","item5":"345"}]
我需要这样的东西:
{"elements":
[
{"element":
{"item1":"123","item4":"123","item5":"123"}
},{"element": {"item1":"345","item4":"345","item5":"345"}
}
]
}
如何添加根名称和子名称? 我可以做一些关于视图的配置吗?
我试过这样的 views_post_execute 钩子:
function mymodule_views_post_execute(ViewExecutable $view) {
if (isset($view) && ($view->storage->id() == 'myrestjson')) {
$result = ['elements' => array_map(
function ($subarray) {
return ['element' => $subarray];
},$view->result
)];
$view->result = $result;
}
}
但我收到此错误:
TypeError: Argument 1 passed to Drupal\views\Plugin\views\field\FieldPluginBase::advancedRender() must be an instance of Drupal\views\ResultRow,array given,called in mysite\core\modules\rest\src\Plugin\views\row\DataFieldRow.php on line 147 in Drupal\views\Plugin\views\field\FieldPluginBase->advancedRender() (line 1142 of core\modules\views\src\Plugin\views\field\FieldPluginBase.php).
你能帮我吗? 问候 马里奥
解决方法
您可以使用自定义 Serializer
来更改输出:
- 在您的自定义模块中创建一个新的自定义序列化程序类,路径为:
.../your_module/src/Plugin/views/style/CustomSerializer.php
。 - 自定义序列化程序类应该从核心
Serializer
类扩展而来:Drupal\rest\Plugin\views\style\Serializer.php
- 覆盖
render()
方法(您可以与核心Serializer
类进行比较以查看我修改的内容)
<?php
namespace Drupal\your_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 = [];
foreach ($this->view->result as $row_index => $row) {
$this->view->row_index = $row_index;
$rows[] = ['element' => $this->view->rowPlugin->render($row)];
}
unset($this->view->row_index);
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(['elements' => $rows],$content_type,['views_style_plugin' => $this]);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。