You are here

public function SerialFields::attach in Serial Field 7

Attach existing fields into entity.

Parameters

string $entity_type: Entity machine name.

string $bundle_name: Entity bundle name.

Return value

self Object instance.

Throws

\FieldException When instance cannot be created.

File

tests/serial.fields.inc, line 93
Serial (Fields Helper).

Class

SerialFields
Class SerialFields.

Code

public function attach($entity_type, $bundle_name) {
  $attached_fields = field_info_instances($entity_type, $bundle_name);
  foreach ($this->fields as $field_name => $data) {
    if (empty($attached_fields[$field_name]) && field_info_field($field_name)) {

      // Provide a possibility to specify field weight, depending on
      // another one.
      //
      // @code
      // $fields = array(
      //   'field_title' => array(
      //     'type' => 'text',
      //     'label' => 'Title',
      //     'widget' => array(
      //       'weight' => 10,
      //     ),
      //   ),
      //   'field_description' => array(
      //     'type' => 'text',
      //     'label' => 'Description',
      //     'widget' => array(
      //       // Weight of this field will be "9".
      //       'weight' => array('field_title', -1),
      //     ),
      //   ),
      // );
      // @endcode
      if (isset($data['widget']['weight']) && is_array($data['widget']['weight'])) {
        list($dependent, $calc) = $data['widget']['weight'];
        $dependent = field_info_instance($entity_type, $dependent, $bundle_name);
        if (!empty($dependent)) {
          $data['widget']['weight'] = $dependent['widget']['weight'] + $calc;
        }
      }
      field_create_instance($data + array(
        'bundle' => $bundle_name,
        'field_name' => $field_name,
        'entity_type' => $entity_type,
      ));
    }
  }
  return $this;
}