field.crud.inc 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. <?php
  2. /**
  3. * @file
  4. * Field CRUD API, handling field and field instance creation and deletion.
  5. */
  6. /**
  7. * @defgroup field_crud Field CRUD API
  8. * @{
  9. * Create, update, and delete Field API fields, bundles, and instances.
  10. *
  11. * Modules use this API, often in hook_install(), to create custom
  12. * data structures. UI modules will use it to create a user interface.
  13. *
  14. * The Field CRUD API uses
  15. * @link field Field API data structures @endlink.
  16. *
  17. * See @link field Field API @endlink for information about the other parts of
  18. * the Field API.
  19. */
  20. /**
  21. * Retrieves the schema for a field.
  22. *
  23. * @param array $field
  24. * The field array to get the schema definition against.
  25. * @return array
  26. * The field schema definition array.
  27. */
  28. function field_retrieve_schema($field) {
  29. // Make sure the installation API is available.
  30. include_once DRUPAL_ROOT . '/includes/install.inc';
  31. module_load_all_includes('install');
  32. $schema = (array) module_invoke($field['module'], 'field_schema', $field);
  33. $schema += array('columns' => array(), 'indexes' => array(), 'foreign keys' => array());
  34. // Give other modules a chance to alter this definition.
  35. // @see hook_field_schema_alter()
  36. drupal_alter('field_schema', $schema, $field);
  37. return $schema;
  38. }
  39. /**
  40. * Creates a field.
  41. *
  42. * This function does not bind the field to any bundle; use
  43. * field_create_instance() for that.
  44. *
  45. * @param $field
  46. * A field definition array. The field_name and type properties are required.
  47. * Other properties, if omitted, will be given the following default values:
  48. * - cardinality: 1
  49. * - locked: FALSE
  50. * - indexes: the field-type indexes, specified by the field type's
  51. * hook_field_schema(). The indexes specified in $field are added
  52. * to those default indexes. It is possible to override the
  53. * definition of a field-type index by providing an index with the
  54. * same name, or to remove it by redefining it as an empty array
  55. * of columns. Overriding field-type indexes should be done
  56. * carefully, for it might seriously affect the site's performance.
  57. * - settings: each omitted setting is given the default value defined in
  58. * hook_field_info().
  59. * - storage:
  60. * - type: the storage backend specified in the 'field_storage_default'
  61. * system variable.
  62. * - settings: each omitted setting is given the default value specified in
  63. * hook_field_storage_info().
  64. *
  65. * @return
  66. * The $field array with the id property filled in.
  67. *
  68. * @throws FieldException
  69. *
  70. * See: @link field Field API data structures @endlink.
  71. */
  72. function field_create_field($field) {
  73. // Field name is required.
  74. if (empty($field['field_name'])) {
  75. throw new FieldException('Attempt to create an unnamed field.');
  76. }
  77. // Field type is required.
  78. if (empty($field['type'])) {
  79. throw new FieldException(format_string('Attempt to create field @field_name with no type.', array('@field_name' => $field['field_name'])));
  80. }
  81. // Field name cannot contain invalid characters.
  82. if (!preg_match('/^[_a-z]+[_a-z0-9]*$/', $field['field_name'])) {
  83. throw new FieldException(format_string('Attempt to create a field @field_name with invalid characters. Only lowercase alphanumeric characters and underscores are allowed, and only lowercase letters and underscore are allowed as the first character', array('@field_name' => $field['field_name'])));
  84. }
  85. // Field name cannot be longer than 32 characters. We use drupal_strlen()
  86. // because the DB layer assumes that column widths are given in characters,
  87. // not bytes.
  88. if (drupal_strlen($field['field_name']) > 32) {
  89. throw new FieldException(t('Attempt to create a field with a name longer than 32 characters: %name',
  90. array('%name' => $field['field_name'])));
  91. }
  92. // Ensure the field name is unique over active and disabled fields.
  93. // We do not care about deleted fields.
  94. $prior_field = field_read_field($field['field_name'], array('include_inactive' => TRUE));
  95. if (!empty($prior_field)) {
  96. $message = $prior_field['active']?
  97. t('Attempt to create field name %name which already exists and is active.', array('%name' => $field['field_name'])):
  98. t('Attempt to create field name %name which already exists, although it is inactive.', array('%name' => $field['field_name']));
  99. throw new FieldException($message);
  100. }
  101. // Disallow reserved field names. This can't prevent all field name
  102. // collisions with existing entity properties, but some is better
  103. // than none.
  104. foreach (entity_get_info() as $type => $info) {
  105. if (in_array($field['field_name'], $info['entity keys'])) {
  106. throw new FieldException(t('Attempt to create field name %name which is reserved by entity type %type.', array('%name' => $field['field_name'], '%type' => $type)));
  107. }
  108. }
  109. $field += array(
  110. 'entity_types' => array(),
  111. 'cardinality' => 1,
  112. 'translatable' => FALSE,
  113. 'locked' => FALSE,
  114. 'settings' => array(),
  115. 'storage' => array(),
  116. 'deleted' => 0,
  117. );
  118. // Check that the field type is known.
  119. $field_type = field_info_field_types($field['type']);
  120. if (!$field_type) {
  121. throw new FieldException(t('Attempt to create a field of unknown type %type.', array('%type' => $field['type'])));
  122. }
  123. // Create all per-field-type properties (needed here as long as we have
  124. // settings that impact column definitions).
  125. $field['settings'] += field_info_field_settings($field['type']);
  126. $field['module'] = $field_type['module'];
  127. $field['active'] = 1;
  128. // Provide default storage.
  129. $field['storage'] += array(
  130. 'type' => variable_get('field_storage_default', 'field_sql_storage'),
  131. 'settings' => array(),
  132. );
  133. // Check that the storage type is known.
  134. $storage_type = field_info_storage_types($field['storage']['type']);
  135. if (!$storage_type) {
  136. throw new FieldException(t('Attempt to create a field with unknown storage type %type.', array('%type' => $field['storage']['type'])));
  137. }
  138. // Provide default storage settings.
  139. $field['storage']['settings'] += field_info_storage_settings($field['storage']['type']);
  140. $field['storage']['module'] = $storage_type['module'];
  141. $field['storage']['active'] = 1;
  142. // Collect storage information.
  143. $schema = field_retrieve_schema($field);
  144. // 'columns' are hardcoded in the field type.
  145. $field['columns'] = $schema['columns'];
  146. // 'foreign keys' are hardcoded in the field type.
  147. $field['foreign keys'] = $schema['foreign keys'];
  148. // 'indexes' can be both hardcoded in the field type, and specified in the
  149. // incoming $field definition.
  150. $field += array(
  151. 'indexes' => array(),
  152. );
  153. $field['indexes'] += $schema['indexes'];
  154. // The serialized 'data' column contains everything from $field that does not
  155. // have its own column and is not automatically populated when the field is
  156. // read.
  157. $data = $field;
  158. unset($data['columns'], $data['field_name'], $data['type'], $data['active'], $data['module'], $data['storage_type'], $data['storage_active'], $data['storage_module'], $data['locked'], $data['cardinality'], $data['deleted']);
  159. // Additionally, do not save the 'bundles' property populated by
  160. // field_info_field().
  161. unset($data['bundles']);
  162. $record = array(
  163. 'field_name' => $field['field_name'],
  164. 'type' => $field['type'],
  165. 'module' => $field['module'],
  166. 'active' => $field['active'],
  167. 'storage_type' => $field['storage']['type'],
  168. 'storage_module' => $field['storage']['module'],
  169. 'storage_active' => $field['storage']['active'],
  170. 'locked' => $field['locked'],
  171. 'data' => $data,
  172. 'cardinality' => $field['cardinality'],
  173. 'translatable' => $field['translatable'],
  174. 'deleted' => $field['deleted'],
  175. );
  176. // Store the field and get the id back.
  177. drupal_write_record('field_config', $record);
  178. $field['id'] = $record['id'];
  179. // Invoke hook_field_storage_create_field after the field is
  180. // complete (e.g. it has its id).
  181. try {
  182. // Invoke hook_field_storage_create_field after
  183. // drupal_write_record() sets the field id.
  184. module_invoke($storage_type['module'], 'field_storage_create_field', $field);
  185. }
  186. catch (Exception $e) {
  187. // If storage creation failed, remove the field_config record before
  188. // rethrowing the exception.
  189. db_delete('field_config')
  190. ->condition('id', $field['id'])
  191. ->execute();
  192. throw $e;
  193. }
  194. // Clear caches
  195. field_cache_clear();
  196. // Invoke external hooks after the cache is cleared for API consistency.
  197. module_invoke_all('field_create_field', $field);
  198. return $field;
  199. }
  200. /**
  201. * Updates a field.
  202. *
  203. * Any module may forbid any update for any reason. For example, the
  204. * field's storage module might forbid an update if it would change
  205. * the storage schema while data for the field exists. A field type
  206. * module might forbid an update if it would change existing data's
  207. * semantics, or if there are external dependencies on field settings
  208. * that cannot be updated.
  209. *
  210. * @param $field
  211. * A field structure. $field['field_name'] must provided; it
  212. * identifies the field that will be updated to match this
  213. * structure. Any other properties of the field that are not
  214. * specified in $field will be left unchanged, so it is not
  215. * necessary to pass in a fully populated $field structure.
  216. * @return
  217. * Throws a FieldException if the update cannot be performed.
  218. * @see field_create_field()
  219. */
  220. function field_update_field($field) {
  221. // Check that the specified field exists.
  222. $prior_field = field_read_field($field['field_name']);
  223. if (empty($prior_field)) {
  224. throw new FieldException('Attempt to update a non-existent field.');
  225. }
  226. // Use the prior field values for anything not specifically set by the new
  227. // field to be sure that all values are set.
  228. $field += $prior_field;
  229. $field['settings'] += $prior_field['settings'];
  230. // Some updates are always disallowed.
  231. if ($field['type'] != $prior_field['type']) {
  232. throw new FieldException("Cannot change an existing field's type.");
  233. }
  234. if ($field['entity_types'] != $prior_field['entity_types']) {
  235. throw new FieldException("Cannot change an existing field's entity_types property.");
  236. }
  237. if ($field['storage']['type'] != $prior_field['storage']['type']) {
  238. throw new FieldException("Cannot change an existing field's storage type.");
  239. }
  240. // Collect the new storage information, since what is in
  241. // $prior_field may no longer be right.
  242. $schema = field_retrieve_schema($field);
  243. // 'columns' are hardcoded in the field type.
  244. $field['columns'] = $schema['columns'];
  245. // 'foreign keys' are hardcoded in the field type.
  246. $field['foreign keys'] = $schema['foreign keys'];
  247. // 'indexes' can be both hardcoded in the field type, and specified in the
  248. // incoming $field definition.
  249. $field += array(
  250. 'indexes' => array(),
  251. );
  252. $field['indexes'] += $schema['indexes'];
  253. $has_data = field_has_data($field);
  254. // See if any module forbids the update by throwing an exception.
  255. foreach (module_implements('field_update_forbid') as $module) {
  256. $function = $module . '_field_update_forbid';
  257. $function($field, $prior_field, $has_data);
  258. }
  259. // Tell the storage engine to update the field. Do this before
  260. // saving the new definition since it still might fail.
  261. $storage_type = field_info_storage_types($field['storage']['type']);
  262. module_invoke($storage_type['module'], 'field_storage_update_field', $field, $prior_field, $has_data);
  263. // Save the new field definition. @todo: refactor with
  264. // field_create_field.
  265. // The serialized 'data' column contains everything from $field that does not
  266. // have its own column and is not automatically populated when the field is
  267. // read.
  268. $data = $field;
  269. unset($data['columns'], $data['field_name'], $data['type'], $data['locked'], $data['module'], $data['cardinality'], $data['active'], $data['deleted']);
  270. // Additionally, do not save the 'bundles' property populated by
  271. // field_info_field().
  272. unset($data['bundles']);
  273. $field['data'] = $data;
  274. // Store the field and create the id.
  275. $primary_key = array('id');
  276. drupal_write_record('field_config', $field, $primary_key);
  277. // Clear caches
  278. field_cache_clear();
  279. // Invoke external hooks after the cache is cleared for API consistency.
  280. module_invoke_all('field_update_field', $field, $prior_field, $has_data);
  281. }
  282. /**
  283. * Reads a single field record directly from the database.
  284. *
  285. * Generally, you should use the field_info_field() instead.
  286. *
  287. * This function will not return deleted fields. Use
  288. * field_read_fields() instead for this purpose.
  289. *
  290. * @param $field_name
  291. * The field name to read.
  292. * @param array $include_additional
  293. * The default behavior of this function is to not return a field that
  294. * is inactive. Setting
  295. * $include_additional['include_inactive'] to TRUE will override this
  296. * behavior.
  297. * @return
  298. * A field definition array, or FALSE.
  299. */
  300. function field_read_field($field_name, $include_additional = array()) {
  301. $fields = field_read_fields(array('field_name' => $field_name), $include_additional);
  302. return $fields ? current($fields) : FALSE;
  303. }
  304. /**
  305. * Reads in fields that match an array of conditions.
  306. *
  307. * @param array $params
  308. * An array of conditions to match against. Keys are columns from the
  309. * 'field_config' table, values are conditions to match. Additionally,
  310. * conditions on the 'entity_type' and 'bundle' columns from the
  311. * 'field_config_instance' table are supported (select fields having an
  312. * instance on a given bundle).
  313. * @param array $include_additional
  314. * The default behavior of this function is to not return fields that
  315. * are inactive or have been deleted. Setting
  316. * $include_additional['include_inactive'] or
  317. * $include_additional['include_deleted'] to TRUE will override this
  318. * behavior.
  319. * @return
  320. * An array of fields matching $params. If
  321. * $include_additional['include_deleted'] is TRUE, the array is keyed
  322. * by field id, otherwise it is keyed by field name.
  323. */
  324. function field_read_fields($params = array(), $include_additional = array()) {
  325. $query = db_select('field_config', 'fc', array('fetch' => PDO::FETCH_ASSOC));
  326. $query->fields('fc');
  327. // Turn the conditions into a query.
  328. foreach ($params as $key => $value) {
  329. // Allow filtering on the 'entity_type' and 'bundle' columns of the
  330. // field_config_instance table.
  331. if ($key == 'entity_type' || $key == 'bundle') {
  332. if (empty($fci_join)) {
  333. $fci_join = $query->join('field_config_instance', 'fci', 'fc.id = fci.field_id');
  334. }
  335. $key = 'fci.' . $key;
  336. }
  337. else {
  338. $key = 'fc.' . $key;
  339. }
  340. $query->condition($key, $value);
  341. }
  342. if (!isset($include_additional['include_inactive']) || !$include_additional['include_inactive']) {
  343. $query
  344. ->condition('fc.active', 1)
  345. ->condition('fc.storage_active', 1);
  346. }
  347. $include_deleted = (isset($include_additional['include_deleted']) && $include_additional['include_deleted']);
  348. if (!$include_deleted) {
  349. $query->condition('fc.deleted', 0);
  350. }
  351. $fields = array();
  352. $results = $query->execute();
  353. foreach ($results as $record) {
  354. $field = unserialize($record['data']);
  355. $field['id'] = $record['id'];
  356. $field['field_name'] = $record['field_name'];
  357. $field['type'] = $record['type'];
  358. $field['module'] = $record['module'];
  359. $field['active'] = $record['active'];
  360. $field['storage']['type'] = $record['storage_type'];
  361. $field['storage']['module'] = $record['storage_module'];
  362. $field['storage']['active'] = $record['storage_active'];
  363. $field['locked'] = $record['locked'];
  364. $field['cardinality'] = $record['cardinality'];
  365. $field['translatable'] = $record['translatable'];
  366. $field['deleted'] = $record['deleted'];
  367. module_invoke_all('field_read_field', $field);
  368. // Populate storage information.
  369. $schema = field_retrieve_schema($field);
  370. $field['columns'] = $schema['columns'];
  371. $field_name = $field['field_name'];
  372. if ($include_deleted) {
  373. $field_name = $field['id'];
  374. }
  375. $fields[$field_name] = $field;
  376. }
  377. return $fields;
  378. }
  379. /**
  380. * Marks a field and its instances and data for deletion.
  381. *
  382. * @param $field_name
  383. * The field name to delete.
  384. */
  385. function field_delete_field($field_name) {
  386. // Delete all non-deleted instances.
  387. $field = field_info_field($field_name);
  388. if (isset($field['bundles'])) {
  389. foreach ($field['bundles'] as $entity_type => $bundles) {
  390. foreach ($bundles as $bundle) {
  391. $instance = field_info_instance($entity_type, $field_name, $bundle);
  392. field_delete_instance($instance, FALSE);
  393. }
  394. }
  395. }
  396. // Mark field data for deletion.
  397. module_invoke($field['storage']['module'], 'field_storage_delete_field', $field);
  398. // Mark the field for deletion.
  399. db_update('field_config')
  400. ->fields(array('deleted' => 1))
  401. ->condition('field_name', $field_name)
  402. ->execute();
  403. // Clear the cache.
  404. field_cache_clear();
  405. module_invoke_all('field_delete_field', $field);
  406. }
  407. /**
  408. * Creates an instance of a field, binding it to a bundle.
  409. *
  410. * @param $instance
  411. * A field instance definition array. The field_name, entity_type and
  412. * bundle properties are required. Other properties, if omitted,
  413. * will be given the following default values:
  414. * - label: the field name
  415. * - description: empty string
  416. * - required: FALSE
  417. * - default_value_function: empty string
  418. * - settings: each omitted setting is given the default value specified in
  419. * hook_field_info().
  420. * - widget:
  421. * - type: the default widget specified in hook_field_info().
  422. * - settings: each omitted setting is given the default value specified in
  423. * hook_field_widget_info().
  424. * - display:
  425. * Settings for the 'default' view mode will be added if not present, and
  426. * each view mode in the definition will be completed with the following
  427. * default values:
  428. * - label: 'above'
  429. * - type: the default formatter specified in hook_field_info().
  430. * - settings: each omitted setting is given the default value specified in
  431. * hook_field_formatter_info().
  432. * View modes not present in the definition are left empty, and the field
  433. * will not be displayed in this mode.
  434. *
  435. * @return
  436. * The $instance array with the id property filled in.
  437. *
  438. * @throws FieldException
  439. *
  440. * See: @link field Field API data structures @endlink.
  441. * @see hook_field_schema_alter()
  442. */
  443. function field_create_instance($instance) {
  444. $field = field_read_field($instance['field_name']);
  445. if (empty($field)) {
  446. throw new FieldException(t("Attempt to create an instance of a field @field_name that doesn't exist or is currently inactive.", array('@field_name' => $instance['field_name'])));
  447. }
  448. // Check that the required properties exists.
  449. if (empty($instance['entity_type'])) {
  450. throw new FieldException(t('Attempt to create an instance of field @field_name without an entity type.', array('@field_name' => $instance['field_name'])));
  451. }
  452. if (empty($instance['bundle'])) {
  453. throw new FieldException(t('Attempt to create an instance of field @field_name without a bundle.', array('@field_name' => $instance['field_name'])));
  454. }
  455. // Check that the field can be attached to this entity type.
  456. if (!empty($field['entity_types']) && !in_array($instance['entity_type'], $field['entity_types'])) {
  457. throw new FieldException(t('Attempt to create an instance of field @field_name on forbidden entity type @entity_type.', array('@field_name' => $instance['field_name'], '@entity_type' => $instance['entity_type'])));
  458. }
  459. // Set the field id.
  460. $instance['field_id'] = $field['id'];
  461. // Note that we do *not* prevent creating a field on non-existing bundles,
  462. // because that would break the 'Body as field' upgrade for contrib
  463. // node types.
  464. // TODO: Check that the widget type is known and can handle the field type ?
  465. // TODO: Check that the formatters are known and can handle the field type ?
  466. // TODO: Check that the display view modes are known for the entity type ?
  467. // Those checks should probably happen in _field_write_instance() ?
  468. // Problem : this would mean that a UI module cannot update an instance with a disabled formatter.
  469. // Ensure the field instance is unique within the bundle.
  470. // We only check for instances of active fields, since adding an instance of
  471. // a disabled field is not supported.
  472. $prior_instance = field_read_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
  473. if (!empty($prior_instance)) {
  474. $message = t('Attempt to create an instance of field @field_name on bundle @bundle that already has an instance of that field.', array('@field_name' => $instance['field_name'], '@bundle' => $instance['bundle']));
  475. throw new FieldException($message);
  476. }
  477. _field_write_instance($instance);
  478. // Clear caches
  479. field_cache_clear();
  480. // Invoke external hooks after the cache is cleared for API consistency.
  481. module_invoke_all('field_create_instance', $instance);
  482. return $instance;
  483. }
  484. /**
  485. * Updates an instance of a field.
  486. *
  487. * @param $instance
  488. * An associative array representing an instance structure. The following
  489. * required array elements specify which field instance is being updated:
  490. * - entity_type: The type of the entity the field is attached to.
  491. * - bundle: The bundle this field belongs to.
  492. * - field_name: The name of an existing field.
  493. * The other array elements represent properties of the instance, and all
  494. * properties must be specified or their default values will be used (except
  495. * internal-use properties, which are assigned automatically). To avoid
  496. * losing the previously stored properties of the instance when making a
  497. * change, first load the instance with field_info_instance(), then override
  498. * the values you want to override, and finally save using this function.
  499. * Example:
  500. * @code
  501. * // Fetch an instance info array.
  502. * $instance_info = field_info_instance($entity_type, $field_name, $bundle_name);
  503. * // Change a single property in the instance definition.
  504. * $instance_info['required'] = TRUE;
  505. * // Write the changed definition back.
  506. * field_update_instance($instance_info);
  507. * @endcode
  508. *
  509. * @throws FieldException
  510. *
  511. * @see field_info_instance()
  512. * @see field_create_instance()
  513. */
  514. function field_update_instance($instance) {
  515. // Check that the specified field exists.
  516. $field = field_read_field($instance['field_name']);
  517. if (empty($field)) {
  518. throw new FieldException(t('Attempt to update an instance of a nonexistent field @field.', array('@field' => $instance['field_name'])));
  519. }
  520. // Check that the field instance exists (even if it is inactive, since we
  521. // want to be able to replace inactive widgets with new ones).
  522. $prior_instance = field_read_instance($instance['entity_type'], $instance['field_name'], $instance['bundle'], array('include_inactive' => TRUE));
  523. if (empty($prior_instance)) {
  524. throw new FieldException(t("Attempt to update an instance of field @field on bundle @bundle that doesn't exist.", array('@field' => $instance['field_name'], '@bundle' => $instance['bundle'])));
  525. }
  526. $instance['id'] = $prior_instance['id'];
  527. $instance['field_id'] = $prior_instance['field_id'];
  528. _field_write_instance($instance, TRUE);
  529. // Clear caches.
  530. field_cache_clear();
  531. module_invoke_all('field_update_instance', $instance, $prior_instance);
  532. }
  533. /**
  534. * Stores an instance record in the field configuration database.
  535. *
  536. * @param $instance
  537. * An instance structure.
  538. * @param $update
  539. * Whether this is a new or existing instance.
  540. */
  541. function _field_write_instance($instance, $update = FALSE) {
  542. $field = field_read_field($instance['field_name']);
  543. $field_type = field_info_field_types($field['type']);
  544. // Set defaults.
  545. $instance += array(
  546. 'settings' => array(),
  547. 'display' => array(),
  548. 'widget' => array(),
  549. 'required' => FALSE,
  550. 'label' => $instance['field_name'],
  551. 'description' => '',
  552. 'deleted' => 0,
  553. );
  554. // Set default instance settings.
  555. $instance['settings'] += field_info_instance_settings($field['type']);
  556. // Set default widget and settings.
  557. $instance['widget'] += array(
  558. // TODO: what if no 'default_widget' specified ?
  559. 'type' => $field_type['default_widget'],
  560. 'settings' => array(),
  561. );
  562. // If no weight specified, make sure the field sinks at the bottom.
  563. if (!isset($instance['widget']['weight'])) {
  564. $max_weight = field_info_max_weight($instance['entity_type'], $instance['bundle'], 'form');
  565. $instance['widget']['weight'] = isset($max_weight) ? $max_weight + 1 : 0;
  566. }
  567. // Check widget module.
  568. $widget_type = field_info_widget_types($instance['widget']['type']);
  569. $instance['widget']['module'] = $widget_type['module'];
  570. $instance['widget']['settings'] += field_info_widget_settings($instance['widget']['type']);
  571. // Make sure there are at least display settings for the 'default' view mode,
  572. // and fill in defaults for each view mode specified in the definition.
  573. $instance['display'] += array(
  574. 'default' => array(),
  575. );
  576. foreach ($instance['display'] as $view_mode => $display) {
  577. $display += array(
  578. 'label' => 'above',
  579. 'type' => isset($field_type['default_formatter']) ? $field_type['default_formatter'] : 'hidden',
  580. 'settings' => array(),
  581. );
  582. if ($display['type'] != 'hidden') {
  583. $formatter_type = field_info_formatter_types($display['type']);
  584. $display['module'] = $formatter_type['module'];
  585. $display['settings'] += field_info_formatter_settings($display['type']);
  586. }
  587. // If no weight specified, make sure the field sinks at the bottom.
  588. if (!isset($display['weight'])) {
  589. $max_weight = field_info_max_weight($instance['entity_type'], $instance['bundle'], $view_mode);
  590. $display['weight'] = isset($max_weight) ? $max_weight + 1 : 0;
  591. }
  592. $instance['display'][$view_mode] = $display;
  593. }
  594. // The serialized 'data' column contains everything from $instance that does
  595. // not have its own column and is not automatically populated when the
  596. // instance is read.
  597. $data = $instance;
  598. unset($data['id'], $data['field_id'], $data['field_name'], $data['entity_type'], $data['bundle'], $data['deleted']);
  599. $record = array(
  600. 'field_id' => $instance['field_id'],
  601. 'field_name' => $instance['field_name'],
  602. 'entity_type' => $instance['entity_type'],
  603. 'bundle' => $instance['bundle'],
  604. 'data' => $data,
  605. 'deleted' => $instance['deleted'],
  606. );
  607. // We need to tell drupal_update_record() the primary keys to trigger an
  608. // update.
  609. if ($update) {
  610. $record['id'] = $instance['id'];
  611. $primary_key = array('id');
  612. }
  613. else {
  614. $primary_key = array();
  615. }
  616. drupal_write_record('field_config_instance', $record, $primary_key);
  617. }
  618. /**
  619. * Reads a single instance record from the database.
  620. *
  621. * Generally, you should use field_info_instance() instead, as it
  622. * provides caching and allows other modules the opportunity to
  623. * append additional formatters, widgets, and other information.
  624. *
  625. * @param $entity_type
  626. * The type of entity to which the field is bound.
  627. * @param $field_name
  628. * The field name to read.
  629. * @param $bundle
  630. * The bundle to which the field is bound.
  631. * @param array $include_additional
  632. * The default behavior of this function is to not return an instance that
  633. * has been deleted, or whose field is inactive. Setting
  634. * $include_additional['include_inactive'] or
  635. * $include_additional['include_deleted'] to TRUE will override this
  636. * behavior.
  637. * @return
  638. * An instance structure, or FALSE.
  639. */
  640. function field_read_instance($entity_type, $field_name, $bundle, $include_additional = array()) {
  641. $instances = field_read_instances(array('entity_type' => $entity_type, 'field_name' => $field_name, 'bundle' => $bundle), $include_additional);
  642. return $instances ? current($instances) : FALSE;
  643. }
  644. /**
  645. * Reads in field instances that match an array of conditions.
  646. *
  647. * @param $param
  648. * An array of properties to use in selecting a field
  649. * instance. Valid keys include any column of the
  650. * field_config_instance table. If NULL, all instances will be returned.
  651. * @param $include_additional
  652. * The default behavior of this function is to not return field
  653. * instances that have been marked deleted, or whose field is inactive.
  654. * Setting $include_additional['include_inactive'] or
  655. * $include_additional['include_deleted'] to TRUE will override this
  656. * behavior.
  657. * @return
  658. * An array of instances matching the arguments.
  659. */
  660. function field_read_instances($params = array(), $include_additional = array()) {
  661. $include_inactive = isset($include_additional['include_inactive']) && $include_additional['include_inactive'];
  662. $include_deleted = isset($include_additional['include_deleted']) && $include_additional['include_deleted'];
  663. $query = db_select('field_config_instance', 'fci', array('fetch' => PDO::FETCH_ASSOC));
  664. $query->join('field_config', 'fc', 'fc.id = fci.field_id');
  665. $query->fields('fci');
  666. // Turn the conditions into a query.
  667. foreach ($params as $key => $value) {
  668. $query->condition('fci.' . $key, $value);
  669. }
  670. if (!$include_inactive) {
  671. $query
  672. ->condition('fc.active', 1)
  673. ->condition('fc.storage_active', 1);
  674. }
  675. if (!$include_deleted) {
  676. $query->condition('fc.deleted', 0);
  677. $query->condition('fci.deleted', 0);
  678. }
  679. $instances = array();
  680. $query->orderBy('fci.id');
  681. $results = $query->execute();
  682. foreach ($results as $record) {
  683. // Filter out instances on unknown entity types (for instance because the
  684. // module exposing them was disabled).
  685. $entity_info = entity_get_info($record['entity_type']);
  686. if ($include_inactive || $entity_info) {
  687. $instance = unserialize($record['data']);
  688. $instance['id'] = $record['id'];
  689. $instance['field_id'] = $record['field_id'];
  690. $instance['field_name'] = $record['field_name'];
  691. $instance['entity_type'] = $record['entity_type'];
  692. $instance['bundle'] = $record['bundle'];
  693. $instance['deleted'] = $record['deleted'];
  694. module_invoke_all('field_read_instance', $instance);
  695. $instances[] = $instance;
  696. }
  697. }
  698. return $instances;
  699. }
  700. /**
  701. * Marks a field instance and its data for deletion.
  702. *
  703. * @param $instance
  704. * An instance structure.
  705. * @param $field_cleanup
  706. * If TRUE, the field will be deleted as well if its last instance is being
  707. * deleted. If FALSE, it is the caller's responsibility to handle the case of
  708. * fields left without instances. Defaults to TRUE.
  709. */
  710. function field_delete_instance($instance, $field_cleanup = TRUE) {
  711. // Mark the field instance for deletion.
  712. db_update('field_config_instance')
  713. ->fields(array('deleted' => 1))
  714. ->condition('field_name', $instance['field_name'])
  715. ->condition('entity_type', $instance['entity_type'])
  716. ->condition('bundle', $instance['bundle'])
  717. ->execute();
  718. // Clear the cache.
  719. field_cache_clear();
  720. // Mark instance data for deletion.
  721. $field = field_info_field($instance['field_name']);
  722. module_invoke($field['storage']['module'], 'field_storage_delete_instance', $instance);
  723. // Let modules react to the deletion of the instance.
  724. module_invoke_all('field_delete_instance', $instance);
  725. // Delete the field itself if we just deleted its last instance.
  726. if ($field_cleanup && count($field['bundles']) == 0) {
  727. field_delete_field($field['field_name']);
  728. }
  729. }
  730. /**
  731. * @} End of "defgroup field_crud".
  732. */
  733. /**
  734. * @defgroup field_purge Field API bulk data deletion
  735. * @{
  736. * Clean up after Field API bulk deletion operations.
  737. *
  738. * Field API provides functions for deleting data attached to individual
  739. * entities as well as deleting entire fields or field instances in a single
  740. * operation.
  741. *
  742. * Deleting field data items for an entity with field_attach_delete() involves
  743. * three separate operations:
  744. * - Invoking the Field Type API hook_field_delete() for each field on the
  745. * entity. The hook for each field type receives the entity and the specific
  746. * field being deleted. A file field module might use this hook to delete
  747. * uploaded files from the filesystem.
  748. * - Invoking the Field Storage API hook_field_storage_delete() to remove
  749. * data from the primary field storage. The hook implementation receives the
  750. * entity being deleted and deletes data for all of the entity's bundle's
  751. * fields.
  752. * - Invoking the global Field Attach API hook_field_attach_delete() for all
  753. * modules that implement it. Each hook implementation receives the entity
  754. * being deleted and can operate on whichever subset of the entity's bundle's
  755. * fields it chooses to.
  756. *
  757. * These hooks are invoked immediately when field_attach_delete() is
  758. * called. Similar operations are performed for field_attach_delete_revision().
  759. *
  760. * When a field, bundle, or field instance is deleted, it is not practical to
  761. * invoke these hooks immediately on every affected entity in a single page
  762. * request; there could be thousands or millions of them. Instead, the
  763. * appropriate field data items, instances, and/or fields are marked as deleted
  764. * so that subsequent load or query operations will not return them. Later, a
  765. * separate process cleans up, or "purges", the marked-as-deleted data by going
  766. * through the three-step process described above and, finally, removing
  767. * deleted field and instance records.
  768. *
  769. * Purging field data is made somewhat tricky by the fact that, while
  770. * field_attach_delete() has a complete entity to pass to the various deletion
  771. * hooks, the Field API purge process only has the field data it has previously
  772. * stored. It cannot reconstruct complete original entities to pass to the
  773. * deletion hooks. It is even possible that the original entity to which some
  774. * Field API data was attached has been itself deleted before the field purge
  775. * operation takes place.
  776. *
  777. * Field API resolves this problem by using "pseudo-entities" during purge
  778. * operations. A pseudo-entity contains only the information from the original
  779. * entity that Field API knows about: entity type, id, revision id, and
  780. * bundle. It also contains the field data for whichever field instance is
  781. * currently being purged. For example, suppose that the node type 'story' used
  782. * to contain a field called 'subtitle' but the field was deleted. If node 37
  783. * was a story with a subtitle, the pseudo-entity passed to the purge hooks
  784. * would look something like this:
  785. *
  786. * @code
  787. * $entity = stdClass Object(
  788. * [nid] => 37,
  789. * [vid] => 37,
  790. * [type] => 'story',
  791. * [subtitle] => array(
  792. * [0] => array(
  793. * 'value' => 'subtitle text',
  794. * ),
  795. * ),
  796. * );
  797. * @endcode
  798. *
  799. * See @link field Field API @endlink for information about the other parts of
  800. * the Field API.
  801. */
  802. /**
  803. * Purges a batch of deleted Field API data, instances, or fields.
  804. *
  805. * This function will purge deleted field data in batches. The batch size
  806. * is defined as an argument to the function, and once each batch is finished,
  807. * it continues with the next batch until all have completed. If a deleted field
  808. * instance with no remaining data records is found, the instance itself will
  809. * be purged. If a deleted field with no remaining field instances is found, the
  810. * field itself will be purged.
  811. *
  812. * @param $batch_size
  813. * The maximum number of field data records to purge before returning.
  814. */
  815. function field_purge_batch($batch_size) {
  816. // Retrieve all deleted field instances. We cannot use field_info_instances()
  817. // because that function does not return deleted instances.
  818. $instances = field_read_instances(array('deleted' => 1), array('include_deleted' => 1));
  819. foreach ($instances as $instance) {
  820. // field_purge_data() will need the field array.
  821. $field = field_info_field_by_id($instance['field_id']);
  822. // Retrieve some entities.
  823. $query = new EntityFieldQuery();
  824. $results = $query
  825. ->fieldCondition($field)
  826. ->entityCondition('bundle', $instance['bundle'])
  827. ->deleted(TRUE)
  828. ->range(0, $batch_size)
  829. ->execute();
  830. if ($results) {
  831. foreach ($results as $entity_type => $stub_entities) {
  832. field_attach_load($entity_type, $stub_entities, FIELD_LOAD_CURRENT, array('field_id' => $field['id'], 'deleted' => 1));
  833. foreach ($stub_entities as $stub_entity) {
  834. // Purge the data for the entity.
  835. field_purge_data($entity_type, $stub_entity, $field, $instance);
  836. }
  837. }
  838. }
  839. else {
  840. // No field data remains for the instance, so we can remove it.
  841. field_purge_instance($instance);
  842. }
  843. }
  844. // Retrieve all deleted fields. Any that have no instances can be purged.
  845. $fields = field_read_fields(array('deleted' => 1), array('include_deleted' => 1));
  846. foreach ($fields as $field) {
  847. $instances = field_read_instances(array('field_id' => $field['id']), array('include_deleted' => 1));
  848. if (empty($instances)) {
  849. field_purge_field($field);
  850. }
  851. }
  852. }
  853. /**
  854. * Purges the field data for a single field on a single pseudo-entity.
  855. *
  856. * This is basically the same as field_attach_delete() except it only applies
  857. * to a single field. The entity itself is not being deleted, and it is quite
  858. * possible that other field data will remain attached to it.
  859. *
  860. * @param $entity_type
  861. * The type of $entity; e.g. 'node' or 'user'.
  862. * @param $entity
  863. * The pseudo-entity whose field data is being purged.
  864. * @param $field
  865. * The (possibly deleted) field whose data is being purged.
  866. * @param $instance
  867. * The deleted field instance whose data is being purged.
  868. */
  869. function field_purge_data($entity_type, $entity, $field, $instance) {
  870. // Each field type's hook_field_delete() only expects to operate on a single
  871. // field at a time, so we can use it as-is for purging.
  872. $options = array('field_id' => $instance['field_id'], 'deleted' => TRUE);
  873. _field_invoke('delete', $entity_type, $entity, $dummy, $dummy, $options);
  874. // Tell the field storage system to purge the data.
  875. module_invoke($field['storage']['module'], 'field_storage_purge', $entity_type, $entity, $field, $instance);
  876. // Let other modules act on purging the data.
  877. foreach (module_implements('field_attach_purge') as $module) {
  878. $function = $module . '_field_attach_purge';
  879. $function($entity_type, $entity, $field, $instance);
  880. }
  881. }
  882. /**
  883. * Purges a field instance record from the database.
  884. *
  885. * This function assumes all data for the instance has already been purged, and
  886. * should only be called by field_purge_batch().
  887. *
  888. * @param $instance
  889. * The instance record to purge.
  890. */
  891. function field_purge_instance($instance) {
  892. db_delete('field_config_instance')
  893. ->condition('id', $instance['id'])
  894. ->execute();
  895. // Notify the storage engine.
  896. $field = field_info_field_by_id($instance['field_id']);
  897. module_invoke($field['storage']['module'], 'field_storage_purge_instance', $instance);
  898. // Clear the cache.
  899. field_info_cache_clear();
  900. // Invoke external hooks after the cache is cleared for API consistency.
  901. module_invoke_all('field_purge_instance', $instance);
  902. }
  903. /**
  904. * Purges a field record from the database.
  905. *
  906. * This function assumes all instances for the field has already been purged,
  907. * and should only be called by field_purge_batch().
  908. *
  909. * @param $field
  910. * The field record to purge.
  911. */
  912. function field_purge_field($field) {
  913. $instances = field_read_instances(array('field_id' => $field['id']), array('include_deleted' => 1));
  914. if (count($instances) > 0) {
  915. throw new FieldException(t('Attempt to purge a field @field_name that still has instances.', array('@field_name' => $field['field_name'])));
  916. }
  917. db_delete('field_config')
  918. ->condition('id', $field['id'])
  919. ->execute();
  920. // Notify the storage engine.
  921. module_invoke($field['storage']['module'], 'field_storage_purge_field', $field);
  922. // Clear the cache.
  923. field_info_cache_clear();
  924. // Invoke external hooks after the cache is cleared for API consistency.
  925. module_invoke_all('field_purge_field', $field);
  926. }
  927. /**
  928. * @} End of "defgroup field_purge".
  929. */