computed_field.module 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <?php
  2. /**
  3. * @file
  4. * Functionality for the computed field.
  5. */
  6. /**
  7. * Implements hook_field_info().
  8. */
  9. function computed_field_field_info() {
  10. return array(
  11. 'computed' => array(
  12. 'label' => t('Computed'),
  13. 'description' => t('Create field data via PHP code.'),
  14. 'settings' => array(
  15. 'code' => '$entity_field[0][\'value\'] = "";',
  16. 'display_format' => '$display_output = $entity_field_item[\'value\'];',
  17. 'store' => 1,
  18. 'recalculate' => FALSE,
  19. 'database' => array(
  20. 'data_type' => 'varchar',
  21. 'data_length' => 32,
  22. 'data_size' => 'normal',
  23. 'data_precision' => 10,
  24. 'data_scale' => 2,
  25. 'data_not_NULL' => FALSE,
  26. 'data_default' => NULL,
  27. 'data_index' => FALSE,
  28. ),
  29. ),
  30. 'default_widget' => 'computed',
  31. 'default_formatter' => 'computed_field_plain',
  32. // If we followed the core convention of separate fields for each data
  33. // type we could make Entity API happy by just setting a property_type.
  34. // Instead we have to use our own callback to determine the type then
  35. // rerun theirs to setup the rest of the field properties.
  36. 'property_callbacks' => array('computed_field_entity_property_callback'),
  37. ),
  38. );
  39. }
  40. /**
  41. * Callback to setup Entity API's field properties.
  42. */
  43. function computed_field_entity_property_callback(&$info, $entity_type, $field, $instance, $field_type) {
  44. $property_types = array(
  45. 'int' => 'integer',
  46. 'float' => 'decimal',
  47. 'numeric' => 'decimal',
  48. 'varchar' => 'text',
  49. 'text' => 'text',
  50. 'longtext' => 'text',
  51. );
  52. if (isset($field['columns']['value']) && isset($property_types[$field['columns']['value']['type']])) {
  53. // Entity API's defaults are pretty good so set the property_type and let them do the work for us.
  54. $field_type['property_type'] = $property_types[$field['columns']['value']['type']];
  55. entity_metadata_field_default_property_callback($info, $entity_type, $field, $instance, $field_type);
  56. // The only thing is that a setter doesn't make sense, so let's disable it.
  57. $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];
  58. unset($property['setter callback']);
  59. }
  60. }
  61. /**
  62. * Implements hook_field_settings_form().
  63. */
  64. function computed_field_field_settings_form($field, $instance, $has_data) {
  65. $form = array();
  66. $compute_func = 'computed_field_' . $field['field_name'] . '_compute';
  67. $display_func = 'computed_field_' . $field['field_name'] . '_display';
  68. $settings = $field['settings'];
  69. $form['#element_validate'] = array('computed_field_field_settings_form_validate');
  70. $form['code'] = array(
  71. '#type' => 'textarea',
  72. '#rows' => 15,
  73. '#title' => t('Computed Code (PHP)'),
  74. '#description' => t('<p>The variables available to your code include: <code>@fields</code>. To set the value of the field, set <code>@entity_field</code>. For multi-value computed fields continue with <code>@entity_field_multi</code>. Here\'s a simple example which sets the computed field\'s value to the value of the sum of the number fields (<code>@field_a</code> and <code>@field_b</code>) in a node entity:</p> !example <p>Alternately, this code can be supplied by your own custom function named: <code>@compute_func(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items)</code>.</p>', array(
  75. '@fields' => '&$entity_field, $entity_type, $entity, $field, $instance, $langcode, and $items',
  76. '@entity_field' => '$entity_field[0][\'value\']',
  77. '@entity_field_multi' => '$entity_field[1][\'value\']',
  78. '@field_a' => 'field_a',
  79. '@field_b' => 'field_b',
  80. '!example' => '<p><code>$field_a = field_get_items($entity_type, $entity, "field_a");<br />
  81. $field_b = field_get_items($entity_type, $entity, "field_b");<br />
  82. $entity_field[0]["value"] = $field_a[0]["value"] + $field_b[0]["value"];</code></p>
  83. ',
  84. '@compute_func' => $compute_func,
  85. )),
  86. '#default_value' => !empty($settings['code']) ? $settings['code'] : '$entity_field[0][\'value\'] = "";',
  87. '#access' => !function_exists($compute_func),
  88. );
  89. if (function_exists($compute_func)) {
  90. $form['compute_func'] = array(
  91. '#type' => 'item',
  92. '#markup' => t('<strong>This field is COMPUTED using <code>@compute_func()</code>.</strong>', array('@compute_func' => $compute_func)),
  93. );
  94. }
  95. $form['display_format'] = array(
  96. '#type' => 'textarea',
  97. '#title' => t('Display Code (PHP)'),
  98. '#description' => t('This code should assign a string to the <code>@display_output</code> variable, which will be printed when the field is displayed. The raw computed value of the field is in <code>@value</code>. <strong>Note:</strong> this code has no effect if you use the "Raw computed value" display formatter.<p> Alternately, this code can be supplied by your own custom function named: <code>@display_func($field, $entity_field_item, $entity_lang, $langcode, $entity)</code>. Return the value to be displayed. Original value is in $entity_field_item[\'value\'].', array(
  99. '@display_output' => '$display_output',
  100. '@value' => '$entity_field_item[\'value\']',
  101. '@display_func' => $display_func,
  102. )),
  103. '#default_value' => !empty($settings['display_format']) ? $settings['display_format'] : '$display_output = $entity_field_item[\'value\'];',
  104. '#access' => !function_exists($display_func),
  105. );
  106. if (function_exists($display_func)) {
  107. $form['display_func'] = array(
  108. '#type' => 'item',
  109. '#markup' => t('<strong>This field is DISPLAYED using <code>@display_func()</code>.</strong>', array('@display_func' => $display_func)),
  110. );
  111. }
  112. $form['recalculate'] = array(
  113. '#type' => 'checkbox',
  114. '#title' => t('Recalculate the field value every time.'),
  115. '#description' => t('By default, Drupal will cache the value of this field even if it is not stored in the database (and even if Page Caching is disabled). This option will cause computed_field to recalculate the value every time this field is displayed. For example, a time-based calculated value may change more often than field cache is cleared. (Note that Drupal page caching will still cache the field value.)'),
  116. '#default_value' => is_numeric($settings['recalculate']) ? $settings['recalculate'] : FALSE,
  117. );
  118. $form['store'] = array(
  119. '#type' => 'checkbox',
  120. '#title' => t('Store value in the database'),
  121. '#description' => t('The value will be stored in the database with the settings below. As a result, it will only be recalculated when the entity is updated. This option is required when accessing the field through Views.'),
  122. '#default_value' => is_numeric($settings['store']) ? $settings['store'] : 1 ,
  123. '#disabled' => $has_data,
  124. );
  125. $form['database'] = array('#type' => 'fieldset', '#title' => t('Database Storage Settings'));
  126. if ($has_data) {
  127. $form['database']['warning'] = array(
  128. '#type' => 'item',
  129. '#markup' => t('<strong>**This field currently has stored data, so modifications to its DB settings are not allowed.**</strong>'),
  130. );
  131. }
  132. $form['database']['data_type'] = array(
  133. '#type' => 'radios',
  134. '#title' => t('Data Type'),
  135. '#description' => t('The SQL datatype to store this field in.'),
  136. '#default_value' => !empty($settings['database']['data_type']) ? $settings['database']['data_type'] : 'varchar',
  137. '#options' => array(
  138. 'varchar' => 'varchar',
  139. 'text' => 'text',
  140. 'longtext' => 'longtext',
  141. 'int' => 'int',
  142. 'float' => 'float',
  143. 'numeric' => 'decimal',
  144. ),
  145. '#required' => FALSE,
  146. '#disabled' => $has_data,
  147. );
  148. $form['database']['data_length'] = array(
  149. '#type' => 'textfield',
  150. '#title' => t('Data Length (varchar/text)'),
  151. '#description' => t('<strong>Only</strong> valid for <strong>varchar</strong> or <strong>text</strong> fields. The length of the field stored in the database.'),
  152. '#default_value' => !empty($settings['database']['data_length']) ? $settings['database']['data_length'] : 32,
  153. '#required' => FALSE,
  154. '#disabled' => $has_data,
  155. );
  156. $form['database']['data_size'] = array(
  157. '#type' => 'select',
  158. '#title' => t('Data Size (int/float)'),
  159. '#description' => t('<strong>Only</strong> valid for <strong>int</strong> or <strong>float</strong> fields. The size of the field stored in the database.'),
  160. '#default_value' => !empty($settings['database']['data_size']) ? $settings['database']['data_size'] : 'normal',
  161. '#options' => array(
  162. 'tiny' => 'tiny',
  163. 'small' => 'small',
  164. 'medium' => 'medium',
  165. 'normal' => 'normal',
  166. 'big' => 'big',
  167. ),
  168. '#required' => FALSE,
  169. '#disabled' => $has_data,
  170. );
  171. $form['database']['data_precision'] = array(
  172. '#type' => 'select',
  173. '#title' => t('Decimal Precision (decimal)'),
  174. '#description' => t('<strong>Only</strong> valid for <strong>decimal</strong> fields. The total number of digits to store in the database, including those to the right of the decimal.'),
  175. '#options' => drupal_map_assoc(range(10, 32)),
  176. '#default_value' => !empty($settings['database']['data_precision']) ? $settings['database']['data_precision'] : 10,
  177. '#required' => FALSE,
  178. '#disabled' => $has_data,
  179. );
  180. $form['database']['data_scale'] = array(
  181. '#type' => 'select',
  182. '#title' => t('Decimal Scale (decimal)'),
  183. '#description' => t('<strong>Only</strong> valid for <strong>decimal</strong> fields. The number of digits to the right of the decimal. '),
  184. '#options' => drupal_map_assoc(range(0, 10)),
  185. '#default_value' => !empty($settings['database']['data_scale']) ? $settings['database']['data_scale'] : 2,
  186. '#required' => FALSE,
  187. '#disabled' => $has_data,
  188. );
  189. $form['database']['data_default'] = array(
  190. '#type' => 'textfield',
  191. '#title' => t('Default Value'),
  192. '#default_value' => $settings['database']['data_default'],
  193. '#required' => FALSE,
  194. '#disabled' => $has_data,
  195. );
  196. $form['database']['data_not_NULL'] = array(
  197. '#type' => 'checkbox',
  198. '#title' => t('Not NULL'),
  199. '#default_value' => is_numeric($settings['database']['data_not_NULL']) ? $settings['database']['data_not_NULL'] : FALSE,
  200. '#disabled' => $has_data,
  201. );
  202. $form['database']['data_index'] = array(
  203. '#type' => 'checkbox',
  204. '#title' => t('Index computed values in the database (Does not apply to text or longtext fields.)'),
  205. '#default_value' => is_numeric($settings['database']['data_index']) ? $settings['database']['data_index'] : FALSE,
  206. '#disabled' => $has_data,
  207. );
  208. return $form;
  209. }
  210. /**
  211. * #element_validate callback for computed_field_field_settings_form().
  212. */
  213. function computed_field_field_settings_form_validate($element, &$form_state) {
  214. $settings = $form_state['values']['field']['settings'];
  215. if ($settings['store']) {
  216. if (empty($settings['database']['data_type'])) {
  217. form_set_error('field][settings][data_type', t('To store this field in the database, please specify a data type.'));
  218. }
  219. if (($settings['database']['data_type'] == 'text' || $settings['database']['data_type'] == 'varchar') && empty($settings['database']['data_length'])) {
  220. form_set_error('field][settings][database][data_length', t('To store this field in the database, please specify the data length.'));
  221. }
  222. if (($settings['database']['data_type'] == 'int' || $settings['database']['data_type'] == 'float') && (!empty($settings['database']['data_default']) && !is_numeric($settings['database']['data_default']))) {
  223. form_set_error('field][settings][database][data_default', t('Your default value should be numeric given your data type.'));
  224. }
  225. }
  226. }
  227. /**
  228. * Implements hook_field_load().
  229. */
  230. function computed_field_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
  231. $settings = $field['settings'];
  232. // Compute field values on load if they aren't stored in the database.
  233. if (!$settings['store']) {
  234. foreach ($entities as $etid => $entity) {
  235. _computed_field_compute_value($entity_type, $entity, $field, $instances, $langcode, $items[$etid]);
  236. }
  237. }
  238. }
  239. /**
  240. * Implements hook_field_prepare_view().
  241. */
  242. function computed_field_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
  243. $settings = $field['settings'];
  244. // Compute field values in case user is "previewing" an entity.
  245. foreach ($entities as $etid => $entity) {
  246. if ((isset($entity->op) && $entity->op == 'Preview') || $settings['recalculate']) {
  247. _computed_field_compute_value($entity_type, $entity, $field, $instances, $langcode, $items[$etid]);
  248. }
  249. }
  250. }
  251. /**
  252. * Implements hook_field_insert().
  253. */
  254. function computed_field_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  255. _computed_field_compute_value($entity_type, $entity, $field, $instance, $langcode, $items);
  256. }
  257. /**
  258. * Implements hook_field_update().
  259. */
  260. function computed_field_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  261. _computed_field_compute_value($entity_type, $entity, $field, $instance, $langcode, $items);
  262. }
  263. /**
  264. * Implements hook_field_widget_info().
  265. */
  266. function computed_field_field_widget_info() {
  267. return array(
  268. 'computed' => array(
  269. 'label' => t('Computed'),
  270. 'field types' => array('computed'),
  271. 'behaviors' => array(
  272. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  273. 'default value' => FIELD_BEHAVIOR_NONE,
  274. ),
  275. ),
  276. );
  277. }
  278. /**
  279. * Implements hook_field_widget_form().
  280. */
  281. function computed_field_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  282. // If there are no items yet, add a null item value to avoid
  283. // preview errors when selecting a different language.
  284. if (empty($items)) {
  285. $items[0]['value'] = NULL;
  286. }
  287. foreach ($items as $item_delta => $item) {
  288. $element[$item_delta]['value'] = array(
  289. '#type' => 'value',
  290. '#tree' => TRUE,
  291. '#default_value' => isset($item['value']) ? $item['value'] : NULL,
  292. );
  293. }
  294. return $element;
  295. }
  296. /**
  297. * Implements hook_field_formatter_info().
  298. */
  299. function computed_field_field_formatter_info() {
  300. return array(
  301. 'computed_field_unsanitized' => array(
  302. 'label' => t('Unsanitized'),
  303. 'field types' => array('computed'),
  304. ),
  305. 'computed_field_plain' => array(
  306. 'label' => t('Plain text'),
  307. 'field types' => array('computed'),
  308. ),
  309. 'computed_field_markup' => array(
  310. 'label' => t('Filtered markup'),
  311. 'field types' => array('computed'),
  312. ),
  313. 'computed_field_computed_value' => array(
  314. 'label' => t('Raw value, no display code'),
  315. 'field types' => array('computed'),
  316. ),
  317. );
  318. }
  319. /**
  320. * Implements hook_field_formatter_view().
  321. */
  322. function computed_field_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  323. $element = array();
  324. $data_to_display = FALSE;
  325. // Special case formatter that returns the raw computed values without any display code processing.
  326. if ($display['type'] == "computed_field_computed_value") {
  327. foreach ($items as $delta => $item) {
  328. if (!isset($entity_field_item['value'])) {
  329. $entity_field_item['value'] = NULL;
  330. }
  331. $element[$delta] = array('#markup' => $item['value']);
  332. }
  333. return $element;
  334. }
  335. // Other display formatters which run through display code processing.
  336. // Check if the value is to be formatted by a display function outside the DB.
  337. $display_func = 'computed_field_' . $field['field_name'] . '_display';
  338. $display_in_code = function_exists($display_func) ? TRUE : FALSE;
  339. // Loop the items to display.
  340. foreach ($items as $delta => $item) {
  341. // For "some" backwards compatibility.
  342. $entity_field_item = $item;
  343. // Setup a variable with the entity language if available.
  344. if (isset($entity->language)) {
  345. $entity_lang = $entity->language;
  346. }
  347. else {
  348. $entity_lang = LANGUAGE_NONE;
  349. }
  350. // If there are value "holes" in the field array let's set the value to NULL.
  351. // to avoid undefined index errors in typical PHP display code.
  352. if (!isset($entity_field_item['value'])) {
  353. $entity_field_item['value'] = NULL;
  354. }
  355. // Execute the display code.
  356. $display_output = NULL;
  357. if ($display_in_code) {
  358. $display_output = $display_func($field, $entity_field_item, $entity_lang, $langcode, $entity);
  359. }
  360. else {
  361. eval($field['settings']['display_format']);
  362. }
  363. // Track if any of our items produce non-empty output.
  364. if (!empty($display_output) || is_numeric($display_output)) {
  365. $data_to_display = TRUE;
  366. }
  367. // Output the formatted display item.
  368. switch ($display['type']) {
  369. case 'computed_field_unsanitized':
  370. $element[$delta] = array('#markup' => $display_output);
  371. break;
  372. case 'computed_field_plain':
  373. $element[$delta] = array('#markup' => check_plain($display_output));
  374. break;
  375. case 'computed_field_markup':
  376. $element[$delta] = array('#markup' => check_markup($display_output));
  377. break;
  378. }
  379. }
  380. // If all items are empty then we should not return anything. This helps
  381. // ensure that empty fields are not displayed at all. This check does not
  382. // apply to fields stored in the DB as those are instead checked on save.
  383. if (isset($field['settings']['store']) && !$field['settings']['store'] && !$data_to_display) {
  384. return;
  385. }
  386. return $element;
  387. }
  388. /**
  389. * Implements hook_field_is_empty().
  390. */
  391. function computed_field_field_is_empty($item, $field) {
  392. unset($empty);
  393. // This will depend on the class of data type.
  394. switch ($field['settings']['database']['data_type']) {
  395. case 'int':
  396. case 'float':
  397. case 'numeric':
  398. // For numbers, the field is empty if the value isn't numeric.
  399. $empty = !is_numeric($item['value']);
  400. break;
  401. case 'varchar':
  402. case 'text':
  403. case 'longtext':
  404. // For strings, the field is empty if it doesn't match the empty string.
  405. $empty = ($item['value'] === "");
  406. break;
  407. }
  408. return $empty;
  409. }
  410. /**
  411. * Private function to compute the fields value.
  412. */
  413. function _computed_field_compute_value($entity_type, $entity, $field, $instance, $langcode, &$items) {
  414. $settings = $field['settings'];
  415. // Setup a variable with the field values.
  416. $entity_field =& $items;
  417. // Setup a variable with the entity language if available.
  418. if (isset($entity->language)) {
  419. $entity_lang = $entity->language;
  420. }
  421. else {
  422. $entity_lang = LANGUAGE_NONE;
  423. }
  424. // Allow the value to be computed from code not stored in DB.
  425. $compute_func = 'computed_field_' . $field['field_name'] . '_compute';
  426. if (function_exists($compute_func)) {
  427. $compute_func($entity_field, $entity_type, $entity, $field, $instance, $langcode, $items);
  428. }
  429. else {
  430. if (isset($settings['code'])) {
  431. eval($settings['code']);
  432. }
  433. }
  434. }