addressfield.module 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. <?php
  2. /**
  3. * @file
  4. * Defines a field for attaching country-specific addresses to entities.
  5. */
  6. /**
  7. * Implements hook_ctools_plugin_directory().
  8. */
  9. function addressfield_ctools_plugin_directory($module, $plugin) {
  10. if ($module == 'addressfield') {
  11. return 'plugins/' . $plugin;
  12. }
  13. }
  14. /**
  15. * Implements hook_ctools_plugin_type().
  16. */
  17. function addressfield_ctools_plugin_type() {
  18. $plugins['format'] = array(
  19. 'load themes' => TRUE,
  20. );
  21. return $plugins;
  22. }
  23. /**
  24. * Implements hook_views_api().
  25. */
  26. function addressfield_views_api() {
  27. return array(
  28. 'api' => 3,
  29. 'path' => drupal_get_path('module', 'addressfield') . '/views',
  30. );
  31. }
  32. /**
  33. * Implements hook_module_implements_alter().
  34. *
  35. * Moves the hook_token_info_alter() implementation to the bottom so it is
  36. * invoked after all modules implementing the same hook.
  37. */
  38. function addressfield_module_implements_alter(&$implementations, $hook) {
  39. if ($hook == 'token_info_alter') {
  40. // Make sure that the $implementations list is populated before altering it,
  41. // to work around a crash experienced by some people (#2181001).
  42. if (isset($implementations['addressfield'])) {
  43. $group = $implementations['addressfield'];
  44. unset($implementations['addressfield']);
  45. $implementations['addressfield'] = $group;
  46. }
  47. }
  48. }
  49. /**
  50. * Returns TRUE if a field map array value represents an addressfield.
  51. *
  52. * Provided for use as a callback by array_filter().
  53. */
  54. function addressfield_field_map_filter($field) {
  55. return !empty($field['type']) && $field['type'] == 'addressfield';
  56. }
  57. /**
  58. * Get the list of format plugins.
  59. */
  60. function addressfield_format_plugins() {
  61. ctools_include('plugins');
  62. $plugins = ctools_get_plugins('addressfield', 'format');
  63. uasort($plugins, 'ctools_plugin_sort');
  64. return $plugins;
  65. }
  66. /**
  67. * Get the list of format plugins in a format suitable for #options.
  68. */
  69. function addressfield_format_plugins_options() {
  70. $options = array();
  71. foreach (addressfield_format_plugins() as $widget => $info) {
  72. $options[$widget] = check_plain($info['title']);
  73. }
  74. return $options;
  75. }
  76. /**
  77. * @defgroup addressfield_format Address format API
  78. * @{
  79. * API for generating address forms and display formats.
  80. *
  81. * Addresses forms and display formats are collaboratively generated by one or
  82. * more format handler plugins. An address with a name and a company, for example,
  83. * will be generated by three handlers:
  84. * - 'address' that will generate the country, locality, street blocks
  85. * - 'organisation' that will add the organisation block to the address
  86. * - 'name-full' that will add a first name and last name block to the address
  87. *
  88. * A format handler is a CTools plugin of type 'addressfield' / 'format'. Each
  89. * handler is passed the format in turn, and can add to or modify the format.
  90. *
  91. * The format itself is a renderable array stub. This stub will be transformed
  92. * into either a Form API array suitable for use as part of a form or into a
  93. * renderable array suitable for use with drupal_render(). The following
  94. * modifications are done:
  95. * - when rendering as a form, every element which name (its key in the array)
  96. * is a valid addressfield column (see addressfield_field_schema()), will
  97. * be transformed into a form element, either using a type explicitly
  98. * defined in '#widget_type' or using 'select' if '#options' is set or
  99. * 'textfield' if it is not. In addition, the '#default_value' of every
  100. * field will be populated from the address being edited.
  101. * - when rendering as a formatter, every element which name (its key in the array)
  102. * is a valid addressfield column (see addressfield_field_schema()), will
  103. * be transformed into a renderable element, either using a type explicitly
  104. * defined in '#render_type' or else using 'addressfield_container'. When
  105. * the type is 'addressfield_container' the element will be rendered as
  106. * an HTML element set by '#tag' (default: span).
  107. */
  108. /**
  109. * Generate a format for a given address.
  110. *
  111. * @param $address
  112. * The address format being generated.
  113. * @param $handlers
  114. * The format handlers to use to generate the format.
  115. * @param $context
  116. * An associative array of context information pertaining to how the address
  117. * format should be generated. If no mode is given, it will initialize to the
  118. * default value. The remaining context keys should only be present when the
  119. * address format is being generated for a field:
  120. * - mode: either 'form' or 'render'; defaults to 'render'.
  121. * - field: the field info array.
  122. * - instance: the field instance array.
  123. * - langcode: the langcode of the language the field is being rendered in.
  124. * - delta: the delta value of the given address.
  125. *
  126. * @return
  127. * A renderable array suitable for use as part of a form (if 'mode' is 'form')
  128. * or for formatted address output when passed to drupal_render().
  129. */
  130. function addressfield_generate($address, array $handlers, array $context = array()) {
  131. // If no mode is given in the context array, default it to 'render'.
  132. if (empty($context['mode'])) {
  133. $context['mode'] = 'render';
  134. }
  135. ctools_include('plugins');
  136. $format = array();
  137. // Add the handlers, ordered by weight.
  138. $plugins = addressfield_format_plugins();
  139. $format['#handlers'] = array_intersect(array_keys($plugins), $handlers);
  140. foreach ($format['#handlers'] as $handler) {
  141. if ($callback = ctools_plugin_load_function('addressfield', 'format', $handler, 'format callback')) {
  142. $callback($format, $address, $context);
  143. }
  144. }
  145. // Store the address in the format, for processing.
  146. $format['#address'] = $address;
  147. // Post-process the format stub, depending on the rendering mode.
  148. if ($context['mode'] == 'form') {
  149. $format['#addressfield'] = TRUE;
  150. $format['#process'][] = 'addressfield_process_format_form';
  151. }
  152. elseif ($context['mode'] == 'render') {
  153. $format['#pre_render'][] = 'addressfield_render_address';
  154. }
  155. return $format;
  156. }
  157. /**
  158. * Generate a full-fledged form from a format snippet, as returned by addressfield_formats().
  159. */
  160. function addressfield_process_format_form($format, &$form_state, $complete_form) {
  161. // Make sure to load all the plugins that participated in this format.
  162. ctools_include('plugins');
  163. foreach ($format['#handlers'] as $handler) {
  164. ctools_plugin_load_function('addressfield', 'format', $handler, 'format callback');
  165. }
  166. _addressfield_process_format_form($format, $format['#address']);
  167. return $format;
  168. }
  169. function _addressfield_process_format_form(&$format, $address) {
  170. foreach (element_children($format) as $key) {
  171. $child = &$format[$key];
  172. // Automatically convert any element in the format array to an appropriate
  173. // form element that matches one of the address component names.
  174. if (in_array($key, array('name_line', 'first_name', 'last_name', 'organisation_name', 'country', 'administrative_area', 'sub_administrative_area', 'locality', 'dependent_locality', 'postal_code', 'thoroughfare', 'premise', 'sub_premise'))) {
  175. // Set the form element type for the address component to whatever the
  176. // address format specified in its #widget_type property.
  177. if (isset($child['#widget_type'])) {
  178. $child['#type'] = $child['#widget_type'];
  179. }
  180. else {
  181. // If the element didn't specify a #widget_type and has options, turn it
  182. // into a select list and unset its #size value, which is typically used
  183. // to provide the width of a textfield.
  184. if (isset($child['#options'])) {
  185. $child['#type'] = 'select';
  186. unset($child['#size']);
  187. }
  188. else {
  189. // Otherwise go ahead and make it a textfield.
  190. $child['#type'] = 'textfield';
  191. }
  192. }
  193. if (isset($address[$key])) {
  194. $child['#default_value'] = $address[$key];
  195. }
  196. }
  197. // Recurse through the element's children if it has any.
  198. _addressfield_process_format_form($child, $address);
  199. }
  200. }
  201. /**
  202. * Render an address in a given format.
  203. */
  204. function addressfield_render_address($format) {
  205. _addressfield_render_address($format, $format['#address']);
  206. return $format;
  207. }
  208. function _addressfield_render_address(&$format, $address) {
  209. foreach (element_children($format) as $key) {
  210. $child = &$format[$key];
  211. // Automatically expand elements that match one of the fields of the address
  212. // structure.
  213. if (in_array($key, array('name_line', 'first_name', 'last_name', 'organisation_name', 'country', 'administrative_area', 'sub_administrative_area', 'locality', 'dependent_locality', 'postal_code', 'thoroughfare', 'premise', 'sub_premise'), TRUE)) {
  214. if (isset($child['#render_type'])) {
  215. $child['#type'] = $child['#render_type'];
  216. }
  217. else {
  218. $child['#type'] = 'addressfield_container';
  219. if (!isset($child['#tag'])) {
  220. $child['#tag'] = 'span';
  221. }
  222. }
  223. // If the element instructs us to render the option value instead of the
  224. // raw address element value and its #options array has a matching key,
  225. // swap it out for the option value now.
  226. if (!empty($child['#render_option_value']) && isset($address[$key]) && isset($child['#options'][$address[$key]])) {
  227. $child['#children'] = check_plain($child['#options'][$address[$key]]);
  228. }
  229. elseif (isset($address[$key])) {
  230. $child['#children'] = check_plain($address[$key]);
  231. }
  232. else {
  233. $child['#children'] = '';
  234. }
  235. // Skip empty elements.
  236. if ((string) $child['#children'] === '') {
  237. $child['#access'] = FALSE;
  238. }
  239. // Add #field_prefix and #field_suffix to the prefixes and suffixes.
  240. if (isset($child['#field_prefix'])) {
  241. $child['#prefix'] = (isset($child['#prefix']) ? $child['#prefix'] : '') . $child['#field_prefix'];
  242. }
  243. if (isset($child['#field_suffix'])) {
  244. $child['#suffix'] = (isset($child['#suffix']) ? $child['#suffix'] : '') . $child['#field_suffix'];
  245. }
  246. }
  247. // Recurse through the child.
  248. _addressfield_render_address($child, $address);
  249. }
  250. }
  251. /**
  252. * @} End of "ingroup addressfield_format"
  253. */
  254. /**
  255. * Implementation of hook_theme().
  256. */
  257. function addressfield_theme() {
  258. $hooks['addressfield_container'] = array(
  259. 'render element' => 'element',
  260. );
  261. return $hooks;
  262. }
  263. /**
  264. * Render a container for a set of address fields.
  265. */
  266. function theme_addressfield_container($variables) {
  267. $element = $variables['element'];
  268. $element['#children'] = trim($element['#children']);
  269. // Remove the autocomplete attributes because the W3C validator complains.
  270. // They are only used on forms anyway.
  271. unset($element['#attributes']['autocomplete']);
  272. unset($element['#attributes']['x-autocompletetype']);
  273. if (strlen($element['#children']) > 0) {
  274. $output = '<' . $element['#tag'] . drupal_attributes($element['#attributes']) . '>';
  275. $output .= $element['#children'];
  276. $output .= '</' . $element['#tag'] . ">";
  277. return $output;
  278. }
  279. else {
  280. return '';
  281. }
  282. }
  283. /**
  284. * Implementation of hook_element_info().
  285. */
  286. function addressfield_element_info() {
  287. $types['addressfield_container'] = array(
  288. '#theme_wrappers' => array('addressfield_container'),
  289. '#process' => array('addressfield_widget_process'),
  290. '#attributes' => array(),
  291. '#tag' => 'div',
  292. );
  293. return $types;
  294. }
  295. /**
  296. * Form API process function: set the #parents of the children of this element so they appear at the same level as the parent.
  297. */
  298. function addressfield_widget_process($element) {
  299. foreach (element_children($element) as $key) {
  300. $element[$key]['#parents'] = $element['#parents'];
  301. $element[$key]['#parents'][count($element[$key]['#parents']) - 1] = $key;
  302. }
  303. return $element;
  304. }
  305. /**
  306. * Implements hook_field_info()
  307. */
  308. function addressfield_field_info() {
  309. $fields = array();
  310. $fields['addressfield'] = array(
  311. 'label' => t('Postal address'),
  312. 'description' => t('A field type used for storing postal addresses according the xNAL standard.'),
  313. 'settings' => array(),
  314. 'instance_settings' => array(),
  315. 'default_widget' => 'addressfield_standard',
  316. 'default_formatter' => 'addressfield_default',
  317. 'property_type' => 'addressfield',
  318. 'property_callbacks' => array('addressfield_property_info_callback'),
  319. );
  320. return $fields;
  321. }
  322. /**
  323. * Returns an array of default values for the addressfield form elements.
  324. *
  325. * @param $field
  326. * The field array.
  327. * @param $instance
  328. * The instance array.
  329. * @param $address
  330. * The current address values, if known. Allows for per-country defaults.
  331. *
  332. * @return
  333. * An array of default values.
  334. */
  335. function addressfield_default_values($field, $instance, array $address = array()) {
  336. $available_countries = _addressfield_country_options_list($field, $instance);
  337. $default_country = $instance['widget']['settings']['default_country'];
  338. // If the default country is not in the list of available countries,
  339. // fallback to the first country in the list.
  340. if ($default_country && !isset($available_countries[$default_country])) {
  341. $default_country = key($available_countries);
  342. }
  343. $default_values = array(
  344. 'country' => $default_country,
  345. 'name_line' => '',
  346. 'first_name' => '',
  347. 'last_name' => '',
  348. 'organisation_name' => '',
  349. 'administrative_area' => '',
  350. 'sub_administrative_area' => '',
  351. 'locality' => '',
  352. 'dependent_locality' => '',
  353. 'postal_code' => '',
  354. 'thoroughfare' => '',
  355. 'premise' => '',
  356. 'sub_premise' => '',
  357. 'data' => '',
  358. );
  359. // Allow other modules to alter the default values.
  360. $context = array(
  361. 'field' => $field,
  362. 'instance' => $instance,
  363. 'address' => $address,
  364. );
  365. drupal_alter('addressfield_default_values', $default_values, $context);
  366. return $default_values;
  367. }
  368. /**
  369. * Implements hook_field_is_empty().
  370. */
  371. function addressfield_field_is_empty($item, $field) {
  372. // Every address field must have at least a country value or it is considered
  373. // empty, even if it has name information.
  374. return empty($item['country']);
  375. }
  376. /**
  377. * Implements hook_field_presave().
  378. */
  379. function addressfield_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  380. foreach ($items as $delta => &$item) {
  381. // If the first name and last name are set but the name line isn't...
  382. if (isset($item['first_name']) && isset($item['last_name']) && !isset($item['name_line'])) {
  383. // Combine the first and last name to be the name line.
  384. $items[$delta]['name_line'] = $items[$delta]['first_name'] . ' ' . $items[$delta]['last_name'];
  385. }
  386. elseif (isset($item['name_line'])) {
  387. // Otherwise if the name line is set, separate it out into a best guess at
  388. // the first and last name.
  389. $names = explode(' ', $item['name_line']);
  390. $item['first_name'] = array_shift($names);
  391. $item['last_name'] = implode(' ', $names);
  392. }
  393. // Trim whitespace from all of the address components and convert any double
  394. // spaces to single spaces.
  395. foreach ($item as $key => &$value) {
  396. if (!in_array($key, array('data')) && is_string($value)) {
  397. $value = trim(str_replace(' ', ' ', $value));
  398. }
  399. }
  400. }
  401. }
  402. /**
  403. * Implements hook_field_widget_info()
  404. */
  405. function addressfield_field_widget_info() {
  406. $widgets = array();
  407. $widgets['addressfield_standard'] = array(
  408. 'label' => t('Dynamic address form'),
  409. 'field types' => array('addressfield'),
  410. 'settings' => array(
  411. 'available_countries' => array(),
  412. 'default_country' => '',
  413. 'format_handlers' => array('address'),
  414. ),
  415. );
  416. return $widgets;
  417. }
  418. /**
  419. * Implements hook_field_widget_settings_form()
  420. */
  421. function addressfield_field_widget_settings_form($field, $instance) {
  422. $widget = $instance['widget'];
  423. $defaults = field_info_widget_settings($widget['type']);
  424. $settings = array_merge($defaults, $widget['settings']);
  425. $form = array();
  426. if ($widget['type'] == 'addressfield_standard') {
  427. $form['available_countries'] = array(
  428. '#type' => 'select',
  429. '#multiple' => TRUE,
  430. '#title' => t('Available countries'),
  431. '#description' => t('If no countries are selected, all countries will be available.'),
  432. '#options' => _addressfield_country_options_list(),
  433. '#default_value' => $settings['available_countries'],
  434. );
  435. $form['default_country'] = array(
  436. '#type' => 'select',
  437. '#title' => t('Default country'),
  438. '#options' => _addressfield_country_options_list(),
  439. '#default_value' => $settings['default_country'],
  440. '#empty_value' => '',
  441. );
  442. $form['format_handlers'] = array(
  443. '#type' => 'checkboxes',
  444. '#title' => t('Format handlers'),
  445. '#options' => addressfield_format_plugins_options(),
  446. '#default_value' => $settings['format_handlers'],
  447. );
  448. }
  449. return $form;
  450. }
  451. /**
  452. * Implements hook_form_BASE_FORM_ID_alter().
  453. *
  454. * Removes the default values form from the field settings page.
  455. * Allows the module to implement its own, more predictable default value
  456. * handling, getting around #1253820 and other bugs.
  457. */
  458. function addressfield_form_field_ui_field_edit_form_alter(&$form, $form_state) {
  459. if ($form['#field']['type'] == 'addressfield') {
  460. $form['instance']['default_value_widget']['#access'] = FALSE;
  461. }
  462. }
  463. /**
  464. * Implements hook_field_widget_form()
  465. */
  466. function addressfield_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  467. $settings = $instance['widget']['settings'];
  468. $address = array();
  469. // If the form has been rebuilt via AJAX, use the form state values.
  470. // $form_state['values'] is empty because of #limit_validation_errors, so
  471. // $form_state['input'] needs to be used instead.
  472. $parents = array_merge($element['#field_parents'], array($element['#field_name'], $langcode, $delta));
  473. $input_address = drupal_array_get_nested_value($form_state['input'], $parents);
  474. if (!empty($input_address)) {
  475. $address = $input_address;
  476. }
  477. elseif (!empty($items[$delta]['country'])) {
  478. // Else use the saved value for the field.
  479. $address = $items[$delta];
  480. }
  481. // Determine the list of available countries, and if the currently selected
  482. // country is not in it, unset it so it can be reset to the default country.
  483. $countries = _addressfield_country_options_list($field, $instance);
  484. if (!empty($address['country']) && !isset($countries[$address['country']])) {
  485. unset($address['country']);
  486. }
  487. // Merge in default values.
  488. $address += addressfield_default_values($field, $instance, $address);
  489. // Add the form elements for the standard widget, which includes a country
  490. // select list at the top that reloads the available address elements when the
  491. // country is changed.
  492. if ($instance['widget']['type'] == 'addressfield_standard') {
  493. // Wrap everything in a fieldset. This is not the best looking element,
  494. // but it's the only wrapper available in Drupal we can properly use
  495. // in that context, and it is overridable if necessary.
  496. $element['#type'] = 'fieldset';
  497. if (!empty($instance['description'])) {
  498. // Checkout panes convert the fieldset into a container, causing
  499. // #description to not be rendered. Hence, a real element is added and
  500. // the old #description is removed.
  501. $element['#description'] = '';
  502. $element['element_description'] = array(
  503. '#markup' => $instance['description'],
  504. '#prefix' => '<div class="fieldset-description">',
  505. '#suffix' => '</div>',
  506. '#weight' => -999,
  507. );
  508. }
  509. // Generate the address form.
  510. $context = array(
  511. 'mode' => 'form',
  512. 'field' => $field,
  513. 'instance' => $instance,
  514. 'langcode' => $langcode,
  515. 'delta' => $delta,
  516. );
  517. $element += addressfield_generate($address, $settings['format_handlers'], $context);
  518. // Remove any already saved default value.
  519. // See addressfield_form_field_ui_field_edit_form_alter() for the reasoning.
  520. if ($form_state['build_info']['form_id'] == 'field_ui_field_edit_form') {
  521. $element['#address'] = array('country' => '');
  522. }
  523. }
  524. return $element;
  525. }
  526. /**
  527. * Element validate callback: rebuilds the form on country change.
  528. */
  529. function addressfield_standard_country_validate($element, &$form_state) {
  530. if ($element['#default_value'] != $element['#value']) {
  531. $parents = $element['#parents'];
  532. array_pop($parents);
  533. $address = drupal_array_get_nested_value($form_state['values'], $parents);
  534. // Clear the country-specific field values.
  535. $country_specific_data = array(
  536. 'dependent_locality' => '',
  537. 'locality' => '',
  538. 'administrative_area' => '',
  539. 'postal_code' => '',
  540. );
  541. $address = array_diff_key($address, $country_specific_data);
  542. drupal_array_set_nested_value($form_state['values'], $parents, $address);
  543. drupal_array_set_nested_value($form_state['input'], $parents, $address);
  544. $form_state['rebuild'] = TRUE;
  545. }
  546. }
  547. /**
  548. * Ajax callback in response to a change of country in an address field.
  549. *
  550. * The only thing we have to do is to find the proper element to render.
  551. */
  552. function addressfield_standard_widget_refresh($form, $form_state) {
  553. // The target element is one element below the triggering country selector.
  554. $array_parents = $form_state['triggering_element']['#array_parents'];
  555. array_pop($array_parents);
  556. // Iterate over the form parents to find the element.
  557. $element = $form;
  558. foreach ($array_parents as $name) {
  559. $element = &$element[$name];
  560. if (!empty($element['#addressfield'])) {
  561. break;
  562. }
  563. }
  564. // Return the address block, but remove the '_weight' element inserted
  565. // by the field API.
  566. unset($element['_weight']);
  567. // Replace the address field widget with the updated widget and focus on the
  568. // new country select list.
  569. $commands[] = ajax_command_replace(NULL, render($element));
  570. $commands[] = ajax_command_invoke('#' . $element['country']['#id'], 'focus');
  571. // Add the status messages inside the new addressfield's wrapper element,
  572. // just like core does.
  573. $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
  574. // Allow other modules to add arbitrary AJAX commands on the refresh.
  575. drupal_alter('addressfield_standard_widget_refresh', $commands, $form, $form_state);
  576. return array('#type' => 'ajax', '#commands' => $commands);
  577. }
  578. /**
  579. * Implements hook_field_formatter_info().
  580. */
  581. function addressfield_field_formatter_info() {
  582. return array(
  583. 'addressfield_default' => array(
  584. 'label' => t('Default'),
  585. 'field types' => array('addressfield'),
  586. 'settings' => array(
  587. 'use_widget_handlers' => 1,
  588. 'format_handlers' => array('address'),
  589. ),
  590. ),
  591. );
  592. }
  593. /**
  594. * Implements hook_field_formatter_settings_form().
  595. */
  596. function addressfield_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  597. $display = $instance['display'][$view_mode];
  598. $settings = $display['settings'];
  599. $element['use_widget_handlers'] = array(
  600. '#type' => 'checkbox',
  601. '#title' => t('Use the same configuration as the widget.'),
  602. '#default_value' => !empty($settings['use_widget_handlers']),
  603. );
  604. $element['format_handlers'] = array(
  605. '#type' => 'checkboxes',
  606. '#title' => t('Format handlers'),
  607. '#options' => addressfield_format_plugins_options(),
  608. '#default_value' => $settings['format_handlers'],
  609. '#process' => array('form_process_checkboxes', '_addressfield_field_formatter_settings_form_process_add_state'),
  610. '#element_validate' => array('_addressfield_field_formatter_settings_form_validate')
  611. );
  612. return $element;
  613. }
  614. /**
  615. * Helper function: set the proper #states to the use widget handlers checkbox.
  616. */
  617. function _addressfield_field_formatter_settings_form_process_add_state($element, $form_state) {
  618. // Build a #parents based on the current checkbox.
  619. $target_parents = array_slice($element['#parents'], 0, -1);
  620. $target_parents[] = 'use_widget_handlers';
  621. $target_parents = array_shift($target_parents) . ($target_parents ? '[' . implode('][', $target_parents) . ']' : '');
  622. $element['#states']['visible'] = array(
  623. ':input[name="' . $target_parents . '"]' => array('checked' => FALSE),
  624. );
  625. return $element;
  626. }
  627. /**
  628. * Helper function: filter the results of the checkboxes form element.
  629. */
  630. function _addressfield_field_formatter_settings_form_validate($element, &$element_state) {
  631. form_set_value($element, array_filter($element['#value']), $element_state);
  632. }
  633. /**
  634. * Implements hook_field_formatter_settings_summary().
  635. */
  636. function addressfield_field_formatter_settings_summary($field, $instance, $view_mode) {
  637. $display = $instance['display'][$view_mode];
  638. $settings = $display['settings'];
  639. $summary = '';
  640. if ($settings['use_widget_handlers']) {
  641. return t('Use widget configuration');
  642. }
  643. else {
  644. $summary = array();
  645. $plugins = addressfield_format_plugins();
  646. foreach ($settings['format_handlers'] as $handler) {
  647. $summary[] = $plugins[$handler]['title'];
  648. }
  649. return $summary ? implode(', ', $summary) : t('No handler');
  650. }
  651. }
  652. /**
  653. * Implements hook_field_formatter_view().
  654. */
  655. function addressfield_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  656. $settings = $display['settings'];
  657. $element = array();
  658. switch ($display['type']) {
  659. case 'addressfield_default':
  660. if (!empty($settings['use_widget_handlers'])) {
  661. $handlers = $instance['widget']['settings']['format_handlers'];
  662. }
  663. else {
  664. $handlers = $settings['format_handlers'];
  665. }
  666. foreach ($items as $delta => $address) {
  667. // Generate the address format.
  668. $context = array(
  669. 'mode' => 'render',
  670. 'field' => $field,
  671. 'instance' => $instance,
  672. 'langcode' => $langcode,
  673. 'delta' => $delta,
  674. );
  675. $element[$delta] = addressfield_generate($address, $handlers, $context);
  676. }
  677. break;
  678. }
  679. return $element;
  680. }
  681. /**
  682. * Callback to alter the property info of address fields.
  683. *
  684. * @see addressfield_field_info().
  685. */
  686. function addressfield_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  687. $name = $field['field_name'];
  688. $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];
  689. $property['type'] = ($field['cardinality'] != 1) ? 'list<addressfield>' : 'addressfield';
  690. $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  691. $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  692. $property['auto creation'] = 'addressfield_auto_creation';
  693. $property['property info'] = addressfield_data_property_info();
  694. unset($property['query callback']);
  695. }
  696. /**
  697. * Auto creation callback for an addressfield value array.
  698. *
  699. * @see addressfield_property_info_callback()
  700. */
  701. function addressfield_auto_creation($property_name, $context) {
  702. return addressfield_default_values($context['field'], $context['instance']);
  703. }
  704. /**
  705. * Defines info for the properties of the address field data structure.
  706. */
  707. function addressfield_data_property_info($name = NULL) {
  708. // Build an array of basic property information for the address field.
  709. $properties = array(
  710. 'country' => array(
  711. 'label' => t('Country'),
  712. 'options list' => '_addressfield_country_options_list',
  713. ),
  714. 'name_line' => array(
  715. 'label' => t('Full name'),
  716. ),
  717. 'first_name' => array(
  718. 'label' => t('First name'),
  719. ),
  720. 'last_name' => array(
  721. 'label' => t('Last name'),
  722. ),
  723. 'organisation_name' => array(
  724. 'label' => t('Company'),
  725. ),
  726. 'administrative_area' => array(
  727. 'label' => t('Administrative area (i.e. State / Province)'),
  728. ),
  729. 'sub_administrative_area' => array(
  730. 'label' => t('Sub administrative area'),
  731. ),
  732. 'locality' => array(
  733. 'label' => t('Locality (i.e. City)'),
  734. ),
  735. 'dependent_locality' => array(
  736. 'label' => t('Dependent locality'),
  737. ),
  738. 'postal_code' => array(
  739. 'label' => t('Postal code'),
  740. ),
  741. 'thoroughfare' => array(
  742. 'label' => t('Thoroughfare (i.e. Street address)'),
  743. ),
  744. 'premise' => array(
  745. 'label' => t('Premise (i.e. Apartment / Suite number)'),
  746. ),
  747. 'sub_premise' => array(
  748. 'label' => t('Sub Premise (i.e. Suite, Apartment, Floor, Unknown.'),
  749. ),
  750. );
  751. // Add the default values for each of the address field properties.
  752. foreach ($properties as $key => &$value) {
  753. $value += array(
  754. 'description' => !empty($name) ? t('!label of field %name', array('!label' => $value['label'], '%name' => $name)) : '',
  755. 'type' => 'text',
  756. 'getter callback' => 'entity_property_verbatim_get',
  757. 'setter callback' => 'entity_property_verbatim_set',
  758. );
  759. }
  760. return $properties;
  761. }
  762. /**
  763. * Returns the country list in a format suitable for use as an options list.
  764. */
  765. function _addressfield_country_options_list($field = NULL, $instance = NULL) {
  766. if (module_exists('countries')) {
  767. $countries = countries_get_countries('name', array('enabled' => COUNTRIES_ENABLED));
  768. }
  769. else {
  770. require_once DRUPAL_ROOT . '/includes/locale.inc';
  771. $countries = country_get_list();
  772. }
  773. if (isset($field)) {
  774. // If the instance is not specified, loop against all the instances of the field.
  775. if (!isset($instance)) {
  776. $instances = array();
  777. foreach ($field['bundles'] as $entity_type => $bundles) {
  778. foreach ($bundles as $bundle_name) {
  779. $instances[] = field_info_instance($entity_type, $field['field_name'], $bundle_name);
  780. }
  781. }
  782. }
  783. else {
  784. $instances = array($instance);
  785. }
  786. foreach ($instances as $instance) {
  787. if (!empty($instance['widget']['settings']['available_countries'])) {
  788. $countries = array_intersect_key($countries, $instance['widget']['settings']['available_countries']);
  789. break;
  790. }
  791. }
  792. }
  793. return $countries;
  794. }