Make custom field indexable by Search API

Public

When you code up yur custom field you may want to make it indexable by Search API. The trick is to make the field exposed to Entity API, because Search API widely utilizes Entity API. This snippet is adopted version of this article: http://www.thecarneyeffect.co.uk/describe-field-properties-make-custom-f...

Ok, at first, you need to add 'property_type' and 'property_callbacks' to your custom hook_field_info():

</> CopyGet raw version
php
  1. function field_example_rgb_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  2. $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];
  3.  
  4. $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  5. $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  6. unset($property['query callback']);
  7.  
  8. $property['property info']['rgb'] = array(
  9. 'type' => 'text',
  10. 'label' => t('RGB'),
  11. 'setter callback' => 'entity_property_verbatim_set',
  12. );
  13. $property['property info']['someothervalue'] = array(
  14. 'type' => 'text',
  15. 'label' => t('Some other value'),
  16. 'setter callback' => 'entity_property_verbatim_set',
  17. );
  18. }

The 'property info' callback tells the Entity module that our field uses two values: 'rgb' and 'someothervalue'. The code itself is very generic:

</> CopyGet raw version
php
  1. function MODULE_NAME_rgb_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  2. $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];
  3.  
  4. $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  5. $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  6. unset($property['query callback']);
  7.  
  8. $property['property info']['rgb'] = array(
  9. 'type' => 'text',
  10. 'label' => t('RGB'),
  11. 'setter callback' => 'entity_property_verbatim_set',
  12. );
  13. $property['property info']['someothervalue'] = array(
  14. 'type' => 'text',
  15. 'label' => t('Some other value'),
  16. 'setter callback' => 'entity_property_verbatim_set',
  17. );
  18. }

Comments

iamweird's picture

Aren't those 2 pieces of code exactly the same except field_example is replaced with MODULE_NAME? Got to be different I guess.