Skip to content

2.3. Defining a custom field class (2.x)

Dane Rossenrode edited this page Apr 9, 2016 · 2 revisions

@TODO Clean this up

Every public field is associated with an object implementing ResourceFieldInterface. All public field logic is defined by these resource field objects, with the help of the associated data provider.

Most of the time, RESTful will detect the best resource field class based on the field definition (e.g. ResourceFieldEntityReference for an entityreference field). If it doesn't find a specific class to use, it will default to using ResourceFieldEntity, as defined in ResourceEntity::processPublicFields().

If RESTful cannot find information it needs to choose the class, or you want to provide a custom class for a custom field type, use the new key class to specify the class to be used. For example:

    $public_fields['location'] = array(
      'property' => 'field_location',
      'class' => '\Drupal\casa_rest\Plugin\resource\fields\ResourceFieldEntityGeofield',
    );

That would create an object using the following example custom class:

<?php

/**
 * @file
 * Contains \Drupal\restful\Plugin\resource\fields\ResourceFieldEntityGeofield.
 */

namespace Drupal\casa_rest\Plugin\resource\fields;

use Drupal\restful\Plugin\resource\Field\ResourceFieldEntity;
use Drupal\restful\Plugin\resource\Field\ResourceFieldEntityInterface;

class ResourceFieldEntityGeofield extends ResourceFieldEntity implements ResourceFieldEntityInterface {

  /**
   * {@inheritdoc}
   */
  public function preprocess($value) {
    // dpm($value, 'preprocess $value');

    $valueOut = $value;

    // Change 'latitude' and 'longitude' to their accepted forms
    if (isset($value['longitude'])) {
      $valueOut['lon'] = $value['longitude'];
      unset($valueOut['longitude']);
    }
    if (isset($value['latitude'])) {
      $valueOut['lat'] = $value['latitude'];
      unset($valueOut['latitude']);
    }

    // dpm($valueOut, '$valueOut');
    return $valueOut;
  }

}
Clone this wiki locally