field_example.module 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. /**
  3. * @file
  4. * An example field using the Field Types API.
  5. */
  6. /**
  7. * @defgroup field_example Example: Field Types API
  8. * @ingroup examples
  9. * @{
  10. * Examples using Field Types API.
  11. *
  12. * This is updated from Barry Jaspan's presentation at Drupalcon Paris,
  13. * @link http://acquia.com/community/resources/acquia-tv/intro-field-api-module-developers Video Presentation @endlink
  14. *
  15. * Providing a field requires:
  16. * - Defining a field:
  17. * - hook_field_info()
  18. * - hook_field_schema()
  19. * - hook_field_validate()
  20. * - hook_field_is_empty()
  21. *
  22. * - Defining a formatter for the field (the portion that outputs the field for
  23. * display):
  24. * - hook_field_formatter_info()
  25. * - hook_field_formatter_view()
  26. *
  27. * - Defining a widget for the edit form:
  28. * - hook_field_widget_info()
  29. * - hook_field_widget_form()
  30. *
  31. * Our module defines the field in field_example_field_info(),
  32. * field_example_field_validate() and field_example_field_is_empty().
  33. * field_example_field_schema() is implemented in field_example.install.
  34. *
  35. * Our module sets up a formatter in field_example_field_formatter_info() and
  36. * field_example_field_formatter_view(). These are the API hooks that present
  37. * formatted and themed output to the user.
  38. *
  39. * And finally, our module defines the widget in
  40. * field_example_field_widget_info() and field_example_field_widget_form().
  41. * The widget is the form element used to receive input from the user
  42. * when the field is being populated.
  43. *
  44. * @see field_types
  45. * @see field
  46. */
  47. /***************************************************************
  48. * Field Type API hooks
  49. ***************************************************************/
  50. /**
  51. * Implements hook_field_info().
  52. *
  53. * Provides the description of the field.
  54. */
  55. function field_example_field_info() {
  56. return array(
  57. // We name our field as the associative name of the array.
  58. 'field_example_rgb' => array(
  59. 'label' => t('Example Color RGB'),
  60. 'description' => t('Demonstrates a field composed of an RGB color.'),
  61. 'default_widget' => 'field_example_3text',
  62. 'default_formatter' => 'field_example_simple_text',
  63. ),
  64. );
  65. }
  66. /**
  67. * Implements hook_field_validate().
  68. *
  69. * This hook gives us a chance to validate content that's in our
  70. * field. We're really only interested in the $items parameter, since
  71. * it holds arrays representing content in the field we've defined.
  72. * We want to verify that the items only contain RGB hex values like
  73. * this: #RRGGBB. If the item validates, we do nothing. If it doesn't
  74. * validate, we add our own error notification to the $errors parameter.
  75. *
  76. * @see field_example_field_widget_error()
  77. */
  78. function field_example_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  79. foreach ($items as $delta => $item) {
  80. if (!empty($item['rgb'])) {
  81. if (!preg_match('@^#[0-9a-f]{6}$@', $item['rgb'])) {
  82. $errors[$field['field_name']][$langcode][$delta][] = array(
  83. 'error' => 'field_example_invalid',
  84. 'message' => t('Color must be in the HTML format #abcdef.'),
  85. );
  86. }
  87. }
  88. }
  89. }
  90. /**
  91. * Implements hook_field_is_empty().
  92. *
  93. * hook_field_is_empty() is where Drupal asks us if this field is empty.
  94. * Return TRUE if it does not contain data, FALSE if it does. This lets
  95. * the form API flag an error when required fields are empty.
  96. */
  97. function field_example_field_is_empty($item, $field) {
  98. return empty($item['rgb']);
  99. }
  100. /**
  101. * Implements hook_field_formatter_info().
  102. *
  103. * We need to tell Drupal that we have two different types of formatters
  104. * for this field. One will change the text color, and the other will
  105. * change the background color.
  106. *
  107. * @see field_example_field_formatter_view()
  108. */
  109. function field_example_field_formatter_info() {
  110. return array(
  111. // This formatter just displays the hex value in the color indicated.
  112. 'field_example_simple_text' => array(
  113. 'label' => t('Simple text-based formatter'),
  114. 'field types' => array('field_example_rgb'),
  115. ),
  116. // This formatter changes the background color of the content region.
  117. 'field_example_color_background' => array(
  118. 'label' => t('Change the background of the output text'),
  119. 'field types' => array('field_example_rgb'),
  120. ),
  121. );
  122. }
  123. /**
  124. * Implements hook_field_formatter_view().
  125. *
  126. * Two formatters are implemented.
  127. * - field_example_simple_text just outputs markup indicating the color that
  128. * was entered and uses an inline style to set the text color to that value.
  129. * - field_example_color_background does the same but also changes the
  130. * background color of div.region-content.
  131. *
  132. * @see field_example_field_formatter_info()
  133. */
  134. function field_example_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  135. $element = array();
  136. switch ($display['type']) {
  137. // This formatter simply outputs the field as text and with a color.
  138. case 'field_example_simple_text':
  139. foreach ($items as $delta => $item) {
  140. $element[$delta] = array(
  141. // We create a render array to produce the desired markup,
  142. // "<p style="color: #hexcolor">The color code ... #hexcolor</p>".
  143. // See theme_html_tag().
  144. '#type' => 'html_tag',
  145. '#tag' => 'p',
  146. '#attributes' => array(
  147. 'style' => 'color: ' . $item['rgb'],
  148. ),
  149. '#value' => t('The color code in this field is @code', array('@code' => $item['rgb'])),
  150. );
  151. }
  152. break;
  153. // This formatter adds css to the page changing the '.region-content' area's
  154. // background color. If there are many fields, the last one will win.
  155. case 'field_example_color_background':
  156. foreach ($items as $delta => $item) {
  157. $element[$delta] = array(
  158. '#type' => 'html_tag',
  159. '#tag' => 'p',
  160. '#value' => t('The content area color has been changed to @code', array('@code' => $item['rgb'])),
  161. '#attached' => array(
  162. 'css' => array(
  163. array(
  164. 'data' => 'div.region-content { background-color:' . $item['rgb'] . ';}',
  165. 'type' => 'inline',
  166. ),
  167. ),
  168. ),
  169. );
  170. }
  171. break;
  172. }
  173. return $element;
  174. }
  175. /**
  176. * Implements hook_field_widget_info().
  177. *
  178. * Three widgets are provided.
  179. * - A simple text-only widget where the user enters the '#ffffff'.
  180. * - A 3-textfield widget that gathers the red, green, and blue values
  181. * separately.
  182. * - A farbtastic colorpicker widget that chooses the value graphically.
  183. *
  184. * These widget types will eventually show up in hook_field_widget_form,
  185. * where we will have to flesh them out.
  186. *
  187. * @see field_example_field_widget_form()
  188. */
  189. function field_example_field_widget_info() {
  190. return array(
  191. 'field_example_text' => array(
  192. 'label' => t('RGB value as #ffffff'),
  193. 'field types' => array('field_example_rgb'),
  194. ),
  195. 'field_example_3text' => array(
  196. 'label' => t('RGB text field'),
  197. 'field types' => array('field_example_rgb'),
  198. ),
  199. 'field_example_colorpicker' => array(
  200. 'label' => t('Color Picker'),
  201. 'field types' => array('field_example_rgb'),
  202. ),
  203. );
  204. }
  205. /**
  206. * Implements hook_field_widget_form().
  207. *
  208. * hook_widget_form() is where Drupal tells us to create form elements for
  209. * our field's widget.
  210. *
  211. * We provide one of three different forms, depending on the widget type of
  212. * the Form API item provided.
  213. *
  214. * The 'field_example_colorpicker' and 'field_example_text' are essentially
  215. * the same, but field_example_colorpicker adds a javascript colorpicker
  216. * helper.
  217. *
  218. * field_example_3text displays three text fields, one each for red, green,
  219. * and blue. However, the field type defines a single text column,
  220. * rgb, which needs an HTML color spec. Define an element validate
  221. * handler that converts our r, g, and b fields into a simulated single
  222. * 'rgb' form element.
  223. */
  224. function field_example_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  225. $value = isset($items[$delta]['rgb']) ? $items[$delta]['rgb'] : '';
  226. $widget = $element;
  227. $widget['#delta'] = $delta;
  228. switch ($instance['widget']['type']) {
  229. case 'field_example_colorpicker':
  230. $widget += array(
  231. '#suffix' => '<div class="field-example-colorpicker"></div>',
  232. '#attributes' => array('class' => array('edit-field-example-colorpicker')),
  233. '#attached' => array(
  234. // Add Farbtastic color picker.
  235. 'library' => array(
  236. array('system', 'farbtastic'),
  237. ),
  238. // Add javascript to trigger the colorpicker.
  239. 'js' => array(drupal_get_path('module', 'field_example') . '/field_example.js'),
  240. ),
  241. );
  242. // DELIBERATE fall-through: From here on the field_example_text and
  243. // field_example_colorpicker are exactly the same.
  244. case 'field_example_text':
  245. $widget += array(
  246. '#type' => 'textfield',
  247. '#default_value' => $value,
  248. // Allow a slightly larger size that the field length to allow for some
  249. // configurations where all characters won't fit in input field.
  250. '#size' => 7,
  251. '#maxlength' => 7,
  252. );
  253. break;
  254. case 'field_example_3text':
  255. // Convert rgb value into r, g, and b for #default_value.
  256. if (!empty($value)) {
  257. preg_match_all('@..@', substr($value, 1), $match);
  258. }
  259. else {
  260. $match = array(array());
  261. }
  262. // Make this a fieldset with the three text fields.
  263. $widget += array(
  264. '#type' => 'fieldset',
  265. '#element_validate' => array('field_example_3text_validate'),
  266. // #delta is set so that the validation function will be able
  267. // to access external value information which otherwise would be
  268. // unavailable.
  269. '#delta' => $delta,
  270. '#attached' => array(
  271. 'css' => array(drupal_get_path('module', 'field_example') . '/field_example.css'),
  272. ),
  273. );
  274. // Create a textfield for saturation values for Red, Green, and Blue.
  275. foreach (array('r' => t('Red'), 'g' => t('Green'), 'b' => t('Blue')) as $key => $title) {
  276. $widget[$key] = array(
  277. '#type' => 'textfield',
  278. '#title' => $title,
  279. '#size' => 2,
  280. '#default_value' => array_shift($match[0]),
  281. '#attributes' => array('class' => array('rgb-entry')),
  282. '#description' => t('The 2-digit hexadecimal representation of @color saturation, like "a1" or "ff"', array('@color' => $title)),
  283. );
  284. // Since Form API doesn't allow a fieldset to be required, we
  285. // have to require each field element individually.
  286. if ($instance['required'] == 1) {
  287. $widget[$key]['#required'] = 1;
  288. }
  289. }
  290. break;
  291. }
  292. $element['rgb'] = $widget;
  293. return $element;
  294. }
  295. /**
  296. * Validate the individual fields and then convert to RGB string.
  297. */
  298. function field_example_3text_validate($element, &$form_state) {
  299. // @todo: Isn't there a better way to find out which element?
  300. $delta = $element['#delta'];
  301. $field = $form_state['field'][$element['#field_name']][$element['#language']]['field'];
  302. $field_name = $field['field_name'];
  303. if (isset($form_state['values'][$field_name][$element['#language']][$delta]['rgb'])) {
  304. $values = $form_state['values'][$field_name][$element['#language']][$delta]['rgb'];
  305. foreach (array('r', 'g', 'b') as $colorfield) {
  306. $colorfield_value = hexdec($values[$colorfield]);
  307. // If they left any empty, we'll set the value empty and quit.
  308. if (strlen($values[$colorfield]) == 0) {
  309. form_set_value($element, '', $form_state);
  310. return;
  311. }
  312. // If they gave us anything that's not hex, reject it.
  313. if ((strlen($values[$colorfield]) != 2) || $colorfield_value < 0 || $colorfield_value > 255) {
  314. form_error($element[$colorfield], t("Saturation value must be a 2-digit hexadecimal value between 00 and ff."));
  315. }
  316. }
  317. $value = sprintf('#%02s%02s%02s', $values['r'], $values['g'], $values['b']);
  318. form_set_value($element, $value, $form_state);
  319. }
  320. }
  321. /**
  322. * Implements hook_field_widget_error().
  323. *
  324. * hook_field_widget_error() lets us figure out what to do with errors
  325. * we might have generated in hook_field_validate(). Generally, we'll just
  326. * call form_error().
  327. *
  328. * @see field_example_field_validate()
  329. * @see form_error()
  330. */
  331. function field_example_field_widget_error($element, $error, $form, &$form_state) {
  332. switch ($error['error']) {
  333. case 'field_example_invalid':
  334. form_error($element, $error['message']);
  335. break;
  336. }
  337. }
  338. /**
  339. * Implements hook_menu().
  340. *
  341. * Provides a simple user interface that tells the developer where to go.
  342. */
  343. function field_example_menu() {
  344. $items['examples/field_example'] = array(
  345. 'title' => 'Field Example',
  346. 'page callback' => '_field_example_page',
  347. 'access callback' => TRUE,
  348. );
  349. return $items;
  350. }
  351. /**
  352. * A simple page to explain to the developer what to do.
  353. */
  354. function _field_example_page() {
  355. return t("The Field Example provides a field composed of an HTML RGB value, like #ff00ff. To use it, add the field to a content type.");
  356. }
  357. /**
  358. * @} End of "defgroup field_example".
  359. */