eZ Platform Discussions

How to get html from richtext field


#1

Hello,

I extended the REST API and I created a query to get content.
How to get HTML from richtext ?

$searchService = $this->repository->getSearchService();
$location = $searchService->findLocations($query)->searchHits->valueObject;
$location->getContent()->getField('body')->value->xml->textContent

I can’t find a method to have the text converted to html. “textContent” delete all tags.

Any idea ?


#2

Use the template engine.

in crontroller

$html = $this->renderView('MyBundle:api:richtext.html.twig', ['content'=>$location->getContent(), 'field' => 'body']);

richtext.html.twig

{{ ez_render_field(content, field) }}

Of course, I haven’t tested :sunny:


#3

Thank you but I have an controller that extend RestController. I can’t use $this->renderView() in Faq class.
See below the source code.

class FaqController extends RestController
{
    public function getFaq()
    {
        $query = new LocationQuery;
        $query->query = new Criterion\LogicalAnd(
            [
                new Criterion\Subtree('/1/2/'),
                new Criterion\Visibility(Criterion\Visibility::VISIBLE),
                new Criterion\ContentTypeIdentifier(['faq']),
            ]
        );

        $searchService = $this->repository->getSearchService();
 
        return new FaqValue ($searchService->findLocations($query)->searchHits);
    }
}

And I have Faq class

class Faq extends RestValue
{
    public $faqs;
    
    protected function getFaqs(array $faqs)
    {

        $results = [];
        /** @var SearchHit $faq */
        foreach ($faqs as $faq)
       {
            /** @var Location $content */
            $location = $faq->valueObject;

            $item = [
                'title' => $location->getContent()->getField('title')->value->text,
                'body' =>  $location->getContent()->getField('body')->value->xml->textContent,
            ];
        
            $results[] = $item;
        }

        return $results;
    }
}

#4

You can use the template engine using the “templating” service.

$this->container->get('templating')->render($view, $parameters);

Just inject the service to your class.

Or you could use the ControllerTrait:

use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait

Voila