Skip to content

2. Defining the public fields

jeff-h edited this page Dec 21, 2015 · 5 revisions

Resources will usually want to provide public fields, which are the fields that the API makes available for requests to that endpoint.

Your resource plugin will need to implement the method publicFields (previously publicFieldsInfo in 1.x) which returns a keyed array describing the fields you wish to make public.

These fields are either Drupal fields, Drupal entity properties (such as nid, status, created etc) or completely arbitrary API fields that return anything you want.

The most typical case would be returning a field or property of the entity you're exposing in this resource.

Example arbitrary field.

A simple example array item for an arbitrary field would look like the following:

$public_fields['myField'] = array(
  'callback' => array($this, 'myFieldDataProviderCallbackWithALongName'), // Additional array elements will be passed as arguments to the callback.
);

which will call the specified function on the resource class your publicFields method is defined in:

  public static function myFieldDataProviderCallbackWithALongName(DataInterpreterInterface $value) {
    return 'barry';
  }

Example entity property

The following example exposes the author user ID:

$public_fields['uid'] = array(
  'property' => 'author',
  'sub_property' => 'uid',
);

Field classes

Each public field is mapped to a Field class. RESTful assigns a class to each field automatically if none is provided, based on the the field's type (e.g. entity reference, text, text-long, file, image etc). This is done in ResourceField::fieldClassName().

If you wish, you may specify each field's class explicitly inside publicFields() e.g.

$public_fields['myNewField'] = array(
  'class' => '\Drupal\restful\Plugin\resource\Field\ResourceFieldKeyValue',
  // etc...
}
Clone this wiki locally