Entity Parser custom entity fields output

Last updated on
6 May 2018

In this example , we want to custom the fields  changed  and uid for  the current node . 

  1. Create a Class for example EntityParserDemo.php extend Drupal\entity_parser\EntityParser
    namespace  Drupal\entity_parser_demo;
    use Drupal\entity_parser\EntityParser;
    class EntityParserDemo extend EntityParser {
       //**** field hook ALIAS = blockA  ***//  
       function blockA_changed($entity, $field) {
         $item =$this->string($entity, $field);   
         $changed_date = date("F j, Y, g:i a", array_shift($item));
         return  $changed_date ;
       }
       function blockA_uid($entity, $field) {
          $uid =  array_shift ($this->integer($entity, $field));
          $item_user = \Drupal\user\Entity\User::load($uid);
          $result=[];
          if (is_object($item_user)) {
            $result = [
              "user_object" => $item_user,
              "name" => $item_user->getUsername(),
              "email"  => $item_user->getEmail()
            ];
         }
         return  $result ;
       }
      //**** field hook ALIAS = blockB  ***//  
      function blockB_changed($entity, $field) {
           return $this->string($entity, $field);   
       }
     
    }

HOW TO USE 

    $parser = new EntityParserDemo();
    $nid = 1;
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

    // getting default fields in array format 
    $node_array_full = $parser->node_parser($node);

    // get field hook ALIAS = blockA 
    $options =array( '#hook_alias' => 'blockA');
    $fields = ['changed','uid'] ;
    $node_blookA = $parser->node_parser($node,$fields,$options));

    // get field hook ALIAS = blockB 
    $options =array( '#hook_alias' => 'blockB');
    $fields = ['changed'] ;
    $node_blookB = $parser->node_parser($node,$fields,$options));

     print "1- changed date for ALIAS blockA : " . $node_blookA['changed'];  
     print "2- user name :" . reset($node_blookA['uid'])['name'];  
     print "3- changed date for ALIAS blockB : " . $node_blookB['changed']; 

     //output result
     // 1- changed date for ALIAS blockA :  March 10, 2001, 5:16 pm
     // 2- user name : miandry
     // 3- changed date for ALIAS blockB :  20010310

Tags

Help improve this page

Page status: No known problems

You can: