-
Notifications
You must be signed in to change notification settings - Fork 173
2.3. Defining a custom field class (2.x)
@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;
}
}