微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

来自自定义模板的文章中的附加字段

如何解决来自自定义模板的文章中的附加字段

我有问题。在弹性搜索中,我们返回的数据如下:

"uuid": "8f39a450-64c2-407c-9836-32ed3b4db1ce","locale": "de","title": "Blah nedvsger","route_path": "/articles/blah-nedvsger","type": "news","type_translation": "sulu_article.news","structure_type": "news","changer_full_name": "Adam Ministrator","creator_full_name": "Adam Ministrator","changed": "2021-07-06T09:52:42+0000","created": "2021-07-06T09:49:50+0000","excerpt": {},"SEO": {},"authored": "2021-07-06T09:49:50+0000","author_full_name": "Adam Ministrator","teaser_description": "","published": "2021-07-06T09:49:51+0000","published_state": true,"localization_state": {},"author_id": 1,"creator_contact_id": 1,"changer_contact_id": 1,"pages": [],"content_data": "{\"title\":\"Blah nedvsger\",\"routePath\":\"\\/articles\\/blah-nedvsger\",\"hero_image\":{\"id\":null},\"overline\":\"asfdafasdf\",\"headline\":\"adfgasdf\",\"auth\":[\"c1\"],\"introduction\":\"asdfd\",\"blocks\":[],\"related\":{\"audiencetargeting\":null,\"categories\":null,\"categoryOperator\":\"or\",\"dataSource\":null,\"includeSubFolders\":null,\"limitResult\":null,\"presentAs\":null,\"sortBy\":\"published\",\"sortMethod\":\"asc\",\"tagOperator\":\"or\",\"types\":[\"country\",\"default\",\"fascination\",\"news\"],\"tags\":null}}","main_webspace": "magazine","additional_webspaces": [
"olympics2021"
],"content_fields": []

现在,我想显示 content_data 中字段“headline”的值,我们已经做到了:

将articles.xml 列添加为:

<property
                name="contentData"
                visibility="always"
                translation="Content data"
        >
            <transformer type="json.headline" />
        </property>

使用代码(npm run build 等)创建 Json.js:

import React from 'react';
import type {Node} from 'react';
import type {FieldTransformer} from 'sulu-admin-bundle/types';

export default class JsonHeadlineTransformer implements FieldTransformer {
    transform(value: *): Node
    {

        console.log(value);

        let json = {};

        try
        {
            json = JSON.parse(value);
        }
        catch (error)
        {
           return;
        }

        if('headline' in json)
        {
            return json.headline;
        }
    }
}

它返回空字符串。在控制台中它返回未定义。我们错在哪里?

解决方法

我用最简单的方法做了,我在 src/Admin/Controller 文件中创建了 ArticleController 并继承了 Bundle 一,只是更改了 getFieldDescriptors 方法,例如:

<?php


namespace App\Controller\Admin;

use Sulu\Bundle\ArticleBundle\Controller\ArticleController as SuluArticleController;
use FOS\RestBundle\View\ViewHandlerInterface;
use ONGR\ElasticsearchBundle\Service\Manager;
use Sulu\Bundle\ArticleBundle\Document\Index\DocumentFactoryInterface;
use Sulu\Bundle\ArticleBundle\ListBuilder\ElasticSearchFieldDescriptor;
use Sulu\Component\Content\Mapper\ContentMapperInterface;
use Sulu\Component\DocumentManager\DocumentManagerInterface;
use Sulu\Component\DocumentManager\MetadataFactoryInterface;
use Sulu\Component\Hash\RequestHashCheckerInterface;
use Sulu\Component\Rest\ListBuilder\FieldDescriptorInterface;
use Sulu\Component\Rest\ListBuilder\ListRestHelperInterface;
use Sulu\Component\Security\Authorization\SecurityCheckerInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

/**
 * Provides API for articles.
 */
class ArticleController extends SuluArticleController
//    AbstractRestController implements ClassResourceInterface,SecuredControllerInterface
{

    /**
     * @var bool
     */
    private $displayTabAll;


    public function __construct(
        ViewHandlerInterface $viewHandler,DocumentManagerInterface $documentManager,ContentMapperInterface $contentMapper,MetadataFactoryInterface $metadataFactory,ListRestHelperInterface $restHelper,Manager $manager,DocumentFactoryInterface $documentFactory,FormFactoryInterface $formFactory,RequestHashCheckerInterface $requestHashChecker,SecurityCheckerInterface $securityChecker,bool $displayTabAll = true,?TokenStorageInterface $tokenStorage = null
    )
    {
        parent::__construct(
            $viewHandler,$documentManager,$contentMapper,$metadataFactory,$restHelper,$manager,$documentFactory,$formFactory,$requestHashChecker,$securityChecker,$displayTabAll,$tokenStorage
        );
    }


    /**
     * Create field-descriptor array.
     *
     * @return ElasticSearchFieldDescriptor[]
     */
    protected function getFieldDescriptors(): array
    {
        return [
            'uuid' => ElasticSearchFieldDescriptor::create('id','public.id')
                ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO)
                ->build(),'typeTranslation' => ElasticSearchFieldDescriptor::create('typeTranslation','sulu_article.list.type')
                ->setSortField('typeTranslation.raw')
                ->setVisibility(
                    $this->displayTabAll ?
                        FieldDescriptorInterface::VISIBILITY_YES :
                        FieldDescriptorInterface::VISIBILITY_NEVER
                )
                ->build(),'title' => ElasticSearchFieldDescriptor::create('title','public.title')
                ->setSortField('title.raw')
                ->build(),'creatorFullName' => ElasticSearchFieldDescriptor::create('creatorFullName','sulu_article.list.creator')
                ->setSortField('creatorFullName.raw')
                ->build(),'changerFullName' => ElasticSearchFieldDescriptor::create('changerFullName','sulu_article.list.changer')
                ->setSortField('changerFullName.raw')
                ->build(),'authorFullName' => ElasticSearchFieldDescriptor::create('authorFullName','sulu_article.author')
                ->setSortField('authorFullName.raw')
                ->build(),'created' => ElasticSearchFieldDescriptor::create('created','public.created')
                ->setSortField('created')
                ->setType('datetime')
                ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO)
                ->build(),'changed' => ElasticSearchFieldDescriptor::create('changed','public.changed')
                ->setSortField('changed')
                ->setType('datetime')
                ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO)
                ->build(),'authored' => ElasticSearchFieldDescriptor::create('authored','sulu_article.authored')
                ->setSortField('authored')
                ->setType('datetime')
                ->build(),'localizationState' => ElasticSearchFieldDescriptor::create('localizationState')
                ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO)
                ->build(),'published' => ElasticSearchFieldDescriptor::create('published')
                ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO)
                ->build(),'publishedState' => ElasticSearchFieldDescriptor::create('publishedState')
                ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO)
                ->build(),'routePath' => ElasticSearchFieldDescriptor::create('routePath')
                ->setVisibility(FieldDescriptorInterface::VISIBILITY_NO)
                ->build(),'contentData' => ElasticSearchFieldDescriptor::create('contentData')
                ->setVisibility(FieldDescriptorInterface::VISIBILITY_YES)
                ->build(),];
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。