1

I am working on exposing the article type content via REST in JSON format. I am using Normalizers to generate the required data format.

Normalizer:

use Drupal\serialization\Normalizer\ContentEntityNormalizer;

/**
 * StdClass normalizer.
 */
class NewsFeedNormalizer extends ContentEntityNormalizer {

  /**
   * @inheritDoc
   */
  public function normalize($entity, $format = NULL, array $context = []) {
    $node_detail = parent::normalize($entity, $format, $context);
    // $news_data = [];
    $news_data['id'] = $node_detail['nid'][0]['value'];
    $news_data['type'] = $node_detail['field_story_type'][0]['target_id'];
    $news_data['title'] = $node_detail['title'][0]['value'];
    $news_data['summary'] = $node_detail['body'][0]['summary'];

    return $news_data;
  }

}

Tha above code will return target_id in $news_data['type']. But I need to pass label of the term which is referred. I tried with another Normalizer called EntityReferenceFieldItemNormalizer But there also i didn't get the required result. Can anyone help me in this regard? Any suggestions will be apprceiated.

0

you have the target id so just load the term and send the label instead of target id, something like :

$tid = $node_detail['field_story_type'][0]['target_id'];
$term  =  \Drupal\taxonomy\Entity\Term::load($tid);
$news_data['type'] = $term->label();

Note: you are in class it's better to inject entity.manager service and change the line \Drupal\taxonomy\Entity\Term::load($tid); with something like:

$this->entityManager->getStorage('taxonomy_term')->load($tid);
1
  • Hi @berramou. I agree with this. But I was looking for like instead of loading the terms is there any direct way to get the names of terms. As there is a separate normalizer call EntityReferenceFieldItemNormalizer. So i just wondering whether it could help in this way. – Suraj May 1 '20 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.