Home > rest > How can I get multiple values in a RESTful endpoint from a field who points to other resource?

How can I get multiple values in a RESTful endpoint from a field who points to other resource?

November 6Hits:3
Advertisement

I have a Drupal 7.x site with RESTful installed (version 2.5) and I want have one endpoint which shows a node view, and add a field which show a index of nodes ,extracted from another endpoint, which have a entity reference field pointing to the first node.

I tried adding 'resource' key in publicFields method but I can only get the first result.

I saw restful obtain a resource view using ResourceFieldEntity class, calling allways view method inside of singleValue method, which only can return first value. It guess it's made in this way because singleValue don't need return more than one value, but in my case its needed, because i need the resource retrieve the complete result.

Here is where method is called, in line 336 of ResourceFieldEntity class.

   try {      // Get the contents to embed in place of the reference ID.      /* @var ResourceFieldCollection $embedded_entity */      $embedded_entity = $embedded_resource        ->getDataProvider()        ->view($embedded_identifier);    } 

I solved this creating a custom resource getter class (extending ResourceFieldEntity), and overwrite singleValue method, and called index method instead of view method.

   try {      // Get the contents to embed in place of the reference ID.      /* @var ResourceFieldCollection $embedded_entity */      $embedded_entity = $embedded_resource        ->getDataProvider()        ->index($embedded_identifier);    } 

Are there any other proper way to do this?

Answers

I haven't used this module in a while, so I'm not sure if there's a major difference in the approach between 1.x and 2.x.

I would just implement a custom function for getting the single resource, so that you have full control over what is ret

/*
* Overrides \RestfulEntityBase::controllersInfo().
* Allows us to specify custom functions for different HTTP actions.
*/
public static function controllersInfo() {
  return array(
   '^.*$' => array(
     \RestfulInterface::GET => 'customGetSingleExample',
   ),
  );
}

/**
* Return custom data for getting single resource result
*/
public function customGetSingleExample() {

  //grab request values
  $request = $this->getRequest();
  static::cleanRequest($request);

  //do stuff with request (EntityFieldQuery etc)

  .....

  return $result;
}

This is within a custom resource class, which extends RestfulEntityBaseNode

class RestfulCustomResource extends RestfulEntityBaseNode {

Tags:rest

Related Articles

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 17 q. 0.516 s.