addressfield.module 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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 attribute because the W3C validator complains.
  270. // It's only used on forms anyway.
  271. unset($element['#attributes']['autocomplete']);
  272. if (strlen($element['#children']) > 0) {
  273. $output = '<' . $element['#tag'] . drupal_attributes($element['#attributes']) . '>';
  274. $output .= $element['#children'];
  275. $output .= '</' . $element['#tag'] . ">";
  276. return $output;
  277. }
  278. else {
  279. return '';
  280. }
  281. }
  282. /**
  283. * Implementation of hook_element_info().
  284. */
  285. function addressfield_element_info() {
  286. $types['addressfield_container'] = array(
  287. '#theme_wrappers' => array('addressfield_container'),
  288. '#process' => array('addressfield_widget_process'),
  289. '#attributes' => array(),
  290. '#tag' => 'div',
  291. );
  292. return $types;
  293. }
  294. /**
  295. * Form API process function: set the #parents of the children of this element so they appear at the same level as the parent.
  296. */
  297. function addressfield_widget_process($element) {
  298. foreach (element_children($element) as $key) {
  299. $element[$key]['#parents'] = $element['#parents'];
  300. $element[$key]['#parents'][count($element[$key]['#parents']) - 1] = $key;
  301. }
  302. return $element;
  303. }
  304. /**
  305. * Implements hook_field_info()
  306. */
  307. function addressfield_field_info() {
  308. $fields = array();
  309. $fields['addressfield'] = array(
  310. 'label' => t('Postal address'),
  311. 'description' => t('A field type used for storing postal addresses according the xNAL standard.'),
  312. 'settings' => array(),
  313. 'instance_settings' => array(),
  314. 'default_widget' => 'addressfield_standard',
  315. 'default_formatter' => 'addressfield_default',
  316. 'property_type' => 'addressfield',
  317. 'property_callbacks' => array('addressfield_property_info_callback'),
  318. );
  319. return $fields;
  320. }
  321. /**
  322. * Returns an array of default values for the addressfield form elements.
  323. *
  324. * @param $field
  325. * The field array.
  326. * @param $instance
  327. * The instance array.
  328. * @param $address
  329. * The current address values, if known. Allows for per-country defaults.
  330. *
  331. * @return
  332. * An array of default values.
  333. */
  334. function addressfield_default_values($field, $instance, array $address = array()) {
  335. $available_countries = _addressfield_country_options_list($field, $instance);
  336. $default_country = $instance['widget']['settings']['default_country'];
  337. // Resolve the special site_default option.
  338. if ($default_country == 'site_default') {
  339. $default_country = variable_get('site_default_country', '');
  340. }
  341. // Fallback to the first country in the list if the default country is not
  342. // available, or is empty even though the field is required.
  343. $not_available = $default_country && !isset($available_countries[$default_country]);
  344. $empty_but_required = empty($default_country) && !empty($instance['required']);
  345. if ($not_available || $empty_but_required) {
  346. $default_country = key($available_countries);
  347. }
  348. $default_values = array(
  349. 'country' => $default_country,
  350. 'name_line' => '',
  351. 'first_name' => '',
  352. 'last_name' => '',
  353. 'organisation_name' => '',
  354. 'administrative_area' => '',
  355. 'sub_administrative_area' => '',
  356. 'locality' => '',
  357. 'dependent_locality' => '',
  358. 'postal_code' => '',
  359. 'thoroughfare' => '',
  360. 'premise' => '',
  361. 'sub_premise' => '',
  362. 'data' => '',
  363. );
  364. // Allow other modules to alter the default values.
  365. $context = array(
  366. 'field' => $field,
  367. 'instance' => $instance,
  368. 'address' => $address,
  369. );
  370. drupal_alter('addressfield_default_values', $default_values, $context);
  371. return $default_values;
  372. }
  373. /**
  374. * Implements hook_field_is_empty().
  375. */
  376. function addressfield_field_is_empty($item, $field) {
  377. // Every address field must have at least a country value or it is considered
  378. // empty, even if it has name information.
  379. return empty($item['country']);
  380. }
  381. /**
  382. * Implements hook_field_presave().
  383. */
  384. function addressfield_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  385. foreach ($items as $delta => &$item) {
  386. // If the first name and last name are set but the name line isn't...
  387. if (isset($item['first_name']) && isset($item['last_name']) && !isset($item['name_line'])) {
  388. // Combine the first and last name to be the name line.
  389. $items[$delta]['name_line'] = $items[$delta]['first_name'] . ' ' . $items[$delta]['last_name'];
  390. }
  391. elseif (isset($item['name_line'])) {
  392. // Otherwise if the name line is set, separate it out into a best guess at
  393. // the first and last name.
  394. $names = explode(' ', $item['name_line']);
  395. $item['first_name'] = array_shift($names);
  396. $item['last_name'] = implode(' ', $names);
  397. }
  398. // Trim whitespace from all of the address components and convert any double
  399. // spaces to single spaces.
  400. foreach ($item as $key => &$value) {
  401. if (!in_array($key, array('data')) && is_string($value)) {
  402. $value = trim(str_replace(' ', ' ', $value));
  403. }
  404. }
  405. }
  406. }
  407. /**
  408. * Implements hook_field_widget_info()
  409. */
  410. function addressfield_field_widget_info() {
  411. $widgets = array();
  412. $widgets['addressfield_standard'] = array(
  413. 'label' => t('Dynamic address form'),
  414. 'field types' => array('addressfield'),
  415. 'settings' => array(
  416. 'available_countries' => array(),
  417. // Can't use variable_get('site_default_country') here because it would
  418. // set the value in stone. Instead, the site_default option allows the
  419. // default country to always reflect the current site setting.
  420. 'default_country' => 'site_default',
  421. 'format_handlers' => array('address'),
  422. ),
  423. );
  424. return $widgets;
  425. }
  426. /**
  427. * Implements hook_field_widget_settings_form()
  428. */
  429. function addressfield_field_widget_settings_form($field, $instance) {
  430. $widget = $instance['widget'];
  431. $defaults = field_info_widget_settings($widget['type']);
  432. $settings = array_merge($defaults, $widget['settings']);
  433. $form = array();
  434. if ($widget['type'] == 'addressfield_standard') {
  435. $form['available_countries'] = array(
  436. '#type' => 'select',
  437. '#multiple' => TRUE,
  438. '#title' => t('Available countries'),
  439. '#description' => t('If no countries are selected, all countries will be available.'),
  440. '#options' => _addressfield_country_options_list(),
  441. '#default_value' => $settings['available_countries'],
  442. );
  443. $form['default_country'] = array(
  444. '#type' => 'select',
  445. '#title' => t('Default country'),
  446. '#options' => array('site_default' => t('- Site default -')) + _addressfield_country_options_list(),
  447. '#default_value' => $settings['default_country'],
  448. '#empty_value' => '',
  449. );
  450. $form['format_handlers'] = array(
  451. '#type' => 'checkboxes',
  452. '#title' => t('Format handlers'),
  453. '#options' => addressfield_format_plugins_options(),
  454. '#default_value' => $settings['format_handlers'],
  455. );
  456. }
  457. return $form;
  458. }
  459. /**
  460. * Implements hook_form_BASE_FORM_ID_alter().
  461. *
  462. * Removes the default values form from the field settings page.
  463. * Allows the module to implement its own, more predictable default value
  464. * handling, getting around #1253820 and other bugs.
  465. */
  466. function addressfield_form_field_ui_field_edit_form_alter(&$form, $form_state) {
  467. if ($form['#field']['type'] == 'addressfield') {
  468. $form['instance']['default_value_widget']['#access'] = FALSE;
  469. }
  470. }
  471. /**
  472. * Implements hook_field_widget_form()
  473. */
  474. function addressfield_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  475. $settings = $instance['widget']['settings'];
  476. $address = array();
  477. // If the form has been rebuilt via AJAX, use the form state values.
  478. // $form_state['values'] is empty because of #limit_validation_errors, so
  479. // $form_state['input'] needs to be used instead.
  480. $parents = array_merge($element['#field_parents'], array($element['#field_name'], $langcode, $delta));
  481. $input_address = drupal_array_get_nested_value($form_state['input'], $parents);
  482. if (!empty($input_address)) {
  483. $address = $input_address;
  484. }
  485. elseif (!empty($items[$delta]['country'])) {
  486. // Else use the saved value for the field.
  487. $address = $items[$delta];
  488. }
  489. // Determine the list of available countries, and if the currently selected
  490. // country is not in it, unset it so it can be reset to the default country.
  491. $countries = _addressfield_country_options_list($field, $instance);
  492. if (!empty($address['country']) && !isset($countries[$address['country']])) {
  493. unset($address['country']);
  494. }
  495. // Merge in default values.
  496. $address += addressfield_default_values($field, $instance, $address);
  497. // Add the form elements for the standard widget, which includes a country
  498. // select list at the top that reloads the available address elements when the
  499. // country is changed.
  500. if ($instance['widget']['type'] == 'addressfield_standard') {
  501. // Wrap everything in a fieldset. This is not the best looking element,
  502. // but it's the only wrapper available in Drupal we can properly use
  503. // in that context, and it is overridable if necessary.
  504. $element['#type'] = 'fieldset';
  505. if (!empty($instance['description'])) {
  506. // Checkout panes convert the fieldset into a container, causing
  507. // #description to not be rendered. Hence, a real element is added and
  508. // the old #description is removed.
  509. $element['#description'] = '';
  510. $element['element_description'] = array(
  511. '#markup' => $instance['description'],
  512. '#prefix' => '<div class="fieldset-description">',
  513. '#suffix' => '</div>',
  514. '#weight' => -999,
  515. );
  516. }
  517. // Generate the address form.
  518. $context = array(
  519. 'mode' => 'form',
  520. 'field' => $field,
  521. 'instance' => $instance,
  522. 'langcode' => $langcode,
  523. 'delta' => $delta,
  524. );
  525. $element += addressfield_generate($address, $settings['format_handlers'], $context);
  526. // Remove any already saved default value.
  527. // See addressfield_form_field_ui_field_edit_form_alter() for the reasoning.
  528. if ($form_state['build_info']['form_id'] == 'field_ui_field_edit_form') {
  529. $element['#address'] = array('country' => '');
  530. }
  531. }
  532. return $element;
  533. }
  534. /**
  535. * Element validate callback: rebuilds the form on country change.
  536. */
  537. function addressfield_standard_country_validate($element, &$form_state) {
  538. if ($element['#default_value'] != $element['#value']) {
  539. $parents = $element['#parents'];
  540. array_pop($parents);
  541. $address = drupal_array_get_nested_value($form_state['values'], $parents);
  542. // Clear the country-specific field values.
  543. $country_specific_data = array(
  544. 'dependent_locality' => '',
  545. 'locality' => '',
  546. 'administrative_area' => '',
  547. 'postal_code' => '',
  548. );
  549. $address = array_diff_key($address, $country_specific_data);
  550. drupal_array_set_nested_value($form_state['values'], $parents, $address);
  551. drupal_array_set_nested_value($form_state['input'], $parents, $address);
  552. $form_state['rebuild'] = TRUE;
  553. }
  554. }
  555. /**
  556. * Ajax callback in response to a change of country in an address field.
  557. *
  558. * The only thing we have to do is to find the proper element to render.
  559. */
  560. function addressfield_standard_widget_refresh($form, $form_state) {
  561. // The target element is one element below the triggering country selector.
  562. $array_parents = $form_state['triggering_element']['#array_parents'];
  563. array_pop($array_parents);
  564. // Iterate over the form parents to find the element.
  565. $element = $form;
  566. foreach ($array_parents as $name) {
  567. $element = &$element[$name];
  568. if (!empty($element['#addressfield'])) {
  569. break;
  570. }
  571. }
  572. // Return the address block, but remove the '_weight' element inserted
  573. // by the field API.
  574. unset($element['_weight']);
  575. // Replace the address field widget with the updated widget and focus on the
  576. // new country select list.
  577. $commands[] = ajax_command_replace(NULL, render($element));
  578. $commands[] = ajax_command_invoke('#' . $element['country']['#id'], 'focus');
  579. // Add the status messages inside the new addressfield's wrapper element,
  580. // just like core does.
  581. $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
  582. // Allow other modules to add arbitrary AJAX commands on the refresh.
  583. drupal_alter('addressfield_standard_widget_refresh', $commands, $form, $form_state);
  584. return array('#type' => 'ajax', '#commands' => $commands);
  585. }
  586. /**
  587. * Implements hook_field_formatter_info().
  588. */
  589. function addressfield_field_formatter_info() {
  590. return array(
  591. 'addressfield_default' => array(
  592. 'label' => t('Default'),
  593. 'field types' => array('addressfield'),
  594. 'settings' => array(
  595. 'use_widget_handlers' => 1,
  596. 'format_handlers' => array('address'),
  597. ),
  598. ),
  599. );
  600. }
  601. /**
  602. * Implements hook_field_formatter_settings_form().
  603. */
  604. function addressfield_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  605. $display = $instance['display'][$view_mode];
  606. $settings = $display['settings'];
  607. $element['use_widget_handlers'] = array(
  608. '#type' => 'checkbox',
  609. '#title' => t('Use the same configuration as the widget.'),
  610. '#default_value' => !empty($settings['use_widget_handlers']),
  611. );
  612. $element['format_handlers'] = array(
  613. '#type' => 'checkboxes',
  614. '#title' => t('Format handlers'),
  615. '#options' => addressfield_format_plugins_options(),
  616. '#default_value' => $settings['format_handlers'],
  617. '#process' => array('form_process_checkboxes', '_addressfield_field_formatter_settings_form_process_add_state'),
  618. '#element_validate' => array('_addressfield_field_formatter_settings_form_validate')
  619. );
  620. return $element;
  621. }
  622. /**
  623. * Helper function: set the proper #states to the use widget handlers checkbox.
  624. */
  625. function _addressfield_field_formatter_settings_form_process_add_state($element, $form_state) {
  626. // Build a #parents based on the current checkbox.
  627. $target_parents = array_slice($element['#parents'], 0, -1);
  628. $target_parents[] = 'use_widget_handlers';
  629. $target_parents = array_shift($target_parents) . ($target_parents ? '[' . implode('][', $target_parents) . ']' : '');
  630. $element['#states']['visible'] = array(
  631. ':input[name="' . $target_parents . '"]' => array('checked' => FALSE),
  632. );
  633. return $element;
  634. }
  635. /**
  636. * Helper function: filter the results of the checkboxes form element.
  637. */
  638. function _addressfield_field_formatter_settings_form_validate($element, &$element_state) {
  639. form_set_value($element, array_filter($element['#value']), $element_state);
  640. }
  641. /**
  642. * Implements hook_field_formatter_settings_summary().
  643. */
  644. function addressfield_field_formatter_settings_summary($field, $instance, $view_mode) {
  645. $display = $instance['display'][$view_mode];
  646. $settings = $display['settings'];
  647. $summary = '';
  648. if ($settings['use_widget_handlers']) {
  649. return t('Use widget configuration');
  650. }
  651. else {
  652. $summary = array();
  653. $plugins = addressfield_format_plugins();
  654. foreach ($settings['format_handlers'] as $handler) {
  655. $summary[] = $plugins[$handler]['title'];
  656. }
  657. return $summary ? implode(', ', $summary) : t('No handler');
  658. }
  659. }
  660. /**
  661. * Implements hook_field_formatter_view().
  662. */
  663. function addressfield_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  664. $settings = $display['settings'];
  665. $element = array();
  666. switch ($display['type']) {
  667. case 'addressfield_default':
  668. if (!empty($settings['use_widget_handlers'])) {
  669. $handlers = $instance['widget']['settings']['format_handlers'];
  670. }
  671. else {
  672. $handlers = $settings['format_handlers'];
  673. }
  674. foreach ($items as $delta => $address) {
  675. // Generate the address format.
  676. $context = array(
  677. 'mode' => 'render',
  678. 'field' => $field,
  679. 'instance' => $instance,
  680. 'langcode' => $langcode,
  681. 'delta' => $delta,
  682. );
  683. $element[$delta] = addressfield_generate($address, $handlers, $context);
  684. }
  685. break;
  686. }
  687. return $element;
  688. }
  689. /**
  690. * Callback to alter the property info of address fields.
  691. *
  692. * @see addressfield_field_info().
  693. */
  694. function addressfield_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  695. $name = $field['field_name'];
  696. $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];
  697. $property['type'] = ($field['cardinality'] != 1) ? 'list<addressfield>' : 'addressfield';
  698. $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  699. $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  700. $property['auto creation'] = 'addressfield_auto_creation';
  701. $property['property info'] = addressfield_data_property_info();
  702. unset($property['query callback']);
  703. }
  704. /**
  705. * Auto creation callback for an addressfield value array.
  706. *
  707. * @see addressfield_property_info_callback()
  708. */
  709. function addressfield_auto_creation($property_name, $context) {
  710. return addressfield_default_values($context['field'], $context['instance']);
  711. }
  712. /**
  713. * Defines info for the properties of the address field data structure.
  714. */
  715. function addressfield_data_property_info($name = NULL) {
  716. // Build an array of basic property information for the address field.
  717. $properties = array(
  718. 'country' => array(
  719. 'label' => t('Country'),
  720. 'options list' => '_addressfield_country_options_list',
  721. ),
  722. 'name_line' => array(
  723. 'label' => t('Full name'),
  724. ),
  725. 'first_name' => array(
  726. 'label' => t('First name'),
  727. ),
  728. 'last_name' => array(
  729. 'label' => t('Last name'),
  730. ),
  731. 'organisation_name' => array(
  732. 'label' => t('Company'),
  733. ),
  734. 'administrative_area' => array(
  735. 'label' => t('Administrative area (i.e. State / Province)'),
  736. ),
  737. 'sub_administrative_area' => array(
  738. 'label' => t('Sub administrative area'),
  739. ),
  740. 'locality' => array(
  741. 'label' => t('Locality (i.e. City)'),
  742. ),
  743. 'dependent_locality' => array(
  744. 'label' => t('Dependent locality'),
  745. ),
  746. 'postal_code' => array(
  747. 'label' => t('Postal code'),
  748. ),
  749. 'thoroughfare' => array(
  750. 'label' => t('Thoroughfare (i.e. Street address)'),
  751. ),
  752. 'premise' => array(
  753. 'label' => t('Premise (i.e. Apartment / Suite number)'),
  754. ),
  755. 'sub_premise' => array(
  756. 'label' => t('Sub Premise (i.e. Suite, Apartment, Floor, Unknown.'),
  757. ),
  758. );
  759. // Add the default values for each of the address field properties.
  760. foreach ($properties as $key => &$value) {
  761. $value += array(
  762. 'description' => !empty($name) ? t('!label of field %name', array('!label' => $value['label'], '%name' => $name)) : '',
  763. 'type' => 'text',
  764. 'getter callback' => 'entity_property_verbatim_get',
  765. 'setter callback' => 'entity_property_verbatim_set',
  766. );
  767. }
  768. return $properties;
  769. }
  770. /**
  771. * Returns the country list in a format suitable for use as an options list.
  772. */
  773. function _addressfield_country_options_list($field = NULL, $instance = NULL) {
  774. if (module_exists('countries')) {
  775. $countries = countries_get_countries('name', array('enabled' => COUNTRIES_ENABLED));
  776. }
  777. else {
  778. require_once DRUPAL_ROOT . '/includes/locale.inc';
  779. $countries = country_get_list();
  780. }
  781. if (isset($field)) {
  782. // If the instance is not specified, loop against all the instances of the field.
  783. if (!isset($instance)) {
  784. $instances = array();
  785. foreach ($field['bundles'] as $entity_type => $bundles) {
  786. foreach ($bundles as $bundle_name) {
  787. $instances[] = field_info_instance($entity_type, $field['field_name'], $bundle_name);
  788. }
  789. }
  790. }
  791. else {
  792. $instances = array($instance);
  793. }
  794. foreach ($instances as $instance) {
  795. if (!empty($instance['widget']['settings']['available_countries'])) {
  796. $countries = array_intersect_key($countries, $instance['widget']['settings']['available_countries']);
  797. break;
  798. }
  799. }
  800. }
  801. return $countries;
  802. }