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. if (!empty($form_state['input'])) {
  482. $input_address = drupal_array_get_nested_value($form_state['input'], $parents);
  483. }
  484. if (!empty($input_address)) {
  485. $address = $input_address;
  486. }
  487. elseif (!empty($items[$delta]['country'])) {
  488. // Else use the saved value for the field.
  489. $address = $items[$delta];
  490. }
  491. // Determine the list of available countries, and if the currently selected
  492. // country is not in it, unset it so it can be reset to the default country.
  493. $countries = _addressfield_country_options_list($field, $instance);
  494. if (!empty($address['country']) && !isset($countries[$address['country']])) {
  495. unset($address['country']);
  496. }
  497. // Merge in default values.
  498. $address += addressfield_default_values($field, $instance, $address);
  499. // Add the form elements for the standard widget, which includes a country
  500. // select list at the top that reloads the available address elements when the
  501. // country is changed.
  502. if ($instance['widget']['type'] == 'addressfield_standard') {
  503. // Wrap everything in a fieldset. This is not the best looking element,
  504. // but it's the only wrapper available in Drupal we can properly use
  505. // in that context, and it is overridable if necessary.
  506. $element['#type'] = 'fieldset';
  507. if (!empty($instance['description'])) {
  508. // Checkout panes convert the fieldset into a container, causing
  509. // #description to not be rendered. Hence, a real element is added and
  510. // the old #description is removed.
  511. $element['#description'] = '';
  512. $element['element_description'] = array(
  513. '#markup' => $instance['description'],
  514. '#prefix' => '<div class="fieldset-description">',
  515. '#suffix' => '</div>',
  516. '#weight' => -999,
  517. );
  518. }
  519. // Generate the address form.
  520. $context = array(
  521. 'mode' => 'form',
  522. 'field' => $field,
  523. 'instance' => $instance,
  524. 'langcode' => $langcode,
  525. 'delta' => $delta,
  526. );
  527. $element += addressfield_generate($address, $settings['format_handlers'], $context);
  528. // Remove any already saved default value.
  529. // See addressfield_form_field_ui_field_edit_form_alter() for the reasoning.
  530. if ($form_state['build_info']['form_id'] == 'field_ui_field_edit_form') {
  531. $element['#address'] = array('country' => '');
  532. }
  533. }
  534. return $element;
  535. }
  536. /**
  537. * Element validate callback: rebuilds the form on country change.
  538. */
  539. function addressfield_standard_country_validate($element, &$form_state) {
  540. if ($element['#default_value'] != $element['#value']) {
  541. $parents = $element['#parents'];
  542. array_pop($parents);
  543. $address = drupal_array_get_nested_value($form_state['values'], $parents);
  544. // Clear the country-specific field values.
  545. $country_specific_data = array(
  546. 'dependent_locality' => '',
  547. 'locality' => '',
  548. 'administrative_area' => '',
  549. 'postal_code' => '',
  550. );
  551. $address = array_diff_key($address, $country_specific_data);
  552. drupal_array_set_nested_value($form_state['values'], $parents, $address);
  553. drupal_array_set_nested_value($form_state['input'], $parents, $address);
  554. $form_state['rebuild'] = TRUE;
  555. }
  556. }
  557. /**
  558. * Ajax callback in response to a change of country in an address field.
  559. *
  560. * The only thing we have to do is to find the proper element to render.
  561. */
  562. function addressfield_standard_widget_refresh($form, $form_state) {
  563. // The target element is one element below the triggering country selector.
  564. $array_parents = $form_state['triggering_element']['#array_parents'];
  565. array_pop($array_parents);
  566. // Iterate over the form parents to find the element.
  567. $element = $form;
  568. foreach ($array_parents as $name) {
  569. $element = &$element[$name];
  570. if (!empty($element['#addressfield'])) {
  571. break;
  572. }
  573. }
  574. // Return the address block, but remove the '_weight' element inserted
  575. // by the field API.
  576. unset($element['_weight']);
  577. // Replace the address field widget with the updated widget and focus on the
  578. // new country select list.
  579. $commands[] = ajax_command_replace(NULL, render($element));
  580. $commands[] = ajax_command_invoke('#' . $element['country']['#id'], 'focus');
  581. // Add the status messages inside the new addressfield's wrapper element,
  582. // just like core does.
  583. $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
  584. // Allow other modules to add arbitrary AJAX commands on the refresh.
  585. drupal_alter('addressfield_standard_widget_refresh', $commands, $form, $form_state);
  586. return array('#type' => 'ajax', '#commands' => $commands);
  587. }
  588. /**
  589. * Implements hook_field_formatter_info().
  590. */
  591. function addressfield_field_formatter_info() {
  592. return array(
  593. 'addressfield_default' => array(
  594. 'label' => t('Default'),
  595. 'field types' => array('addressfield'),
  596. 'settings' => array(
  597. 'use_widget_handlers' => 1,
  598. 'format_handlers' => array('address'),
  599. ),
  600. ),
  601. );
  602. }
  603. /**
  604. * Implements hook_field_formatter_settings_form().
  605. */
  606. function addressfield_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  607. $display = $instance['display'][$view_mode];
  608. $settings = $display['settings'];
  609. $element['use_widget_handlers'] = array(
  610. '#type' => 'checkbox',
  611. '#title' => t('Use the same configuration as the widget.'),
  612. '#default_value' => !empty($settings['use_widget_handlers']),
  613. );
  614. $element['format_handlers'] = array(
  615. '#type' => 'checkboxes',
  616. '#title' => t('Format handlers'),
  617. '#options' => addressfield_format_plugins_options(),
  618. '#default_value' => $settings['format_handlers'],
  619. '#process' => array('form_process_checkboxes', '_addressfield_field_formatter_settings_form_process_add_state'),
  620. '#element_validate' => array('_addressfield_field_formatter_settings_form_validate')
  621. );
  622. return $element;
  623. }
  624. /**
  625. * Helper function: set the proper #states to the use widget handlers checkbox.
  626. */
  627. function _addressfield_field_formatter_settings_form_process_add_state($element, $form_state) {
  628. // Build a #parents based on the current checkbox.
  629. $target_parents = array_slice($element['#parents'], 0, -1);
  630. $target_parents[] = 'use_widget_handlers';
  631. $target_parents = array_shift($target_parents) . ($target_parents ? '[' . implode('][', $target_parents) . ']' : '');
  632. $element['#states']['visible'] = array(
  633. ':input[name="' . $target_parents . '"]' => array('checked' => FALSE),
  634. );
  635. return $element;
  636. }
  637. /**
  638. * Helper function: filter the results of the checkboxes form element.
  639. */
  640. function _addressfield_field_formatter_settings_form_validate($element, &$element_state) {
  641. form_set_value($element, array_filter($element['#value']), $element_state);
  642. }
  643. /**
  644. * Implements hook_field_formatter_settings_summary().
  645. */
  646. function addressfield_field_formatter_settings_summary($field, $instance, $view_mode) {
  647. $display = $instance['display'][$view_mode];
  648. $settings = $display['settings'];
  649. if ($settings['use_widget_handlers']) {
  650. return t('Use widget configuration');
  651. }
  652. else {
  653. $summary = array();
  654. $plugins = addressfield_format_plugins();
  655. foreach ($settings['format_handlers'] as $handler) {
  656. $summary[] = $plugins[$handler]['title'];
  657. }
  658. return $summary ? implode(', ', $summary) : t('No handler');
  659. }
  660. }
  661. /**
  662. * Implements hook_field_formatter_view().
  663. */
  664. function addressfield_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  665. $settings = $display['settings'];
  666. $element = array();
  667. switch ($display['type']) {
  668. case 'addressfield_default':
  669. if (!empty($settings['use_widget_handlers'])) {
  670. $handlers = $instance['widget']['settings']['format_handlers'];
  671. }
  672. else {
  673. $handlers = $settings['format_handlers'];
  674. }
  675. foreach ($items as $delta => $address) {
  676. // Generate the address format.
  677. $context = array(
  678. 'mode' => 'render',
  679. 'field' => $field,
  680. 'instance' => $instance,
  681. 'langcode' => $langcode,
  682. 'delta' => $delta,
  683. );
  684. $element[$delta] = addressfield_generate($address, $handlers, $context);
  685. }
  686. break;
  687. }
  688. return $element;
  689. }
  690. /**
  691. * Callback to alter the property info of address fields.
  692. *
  693. * @see addressfield_field_info().
  694. */
  695. function addressfield_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  696. $name = $field['field_name'];
  697. $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];
  698. $property['type'] = ($field['cardinality'] != 1) ? 'list<addressfield>' : 'addressfield';
  699. $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  700. $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  701. $property['auto creation'] = 'addressfield_auto_creation';
  702. $property['property info'] = addressfield_data_property_info();
  703. unset($property['query callback']);
  704. }
  705. /**
  706. * Auto creation callback for an addressfield value array.
  707. *
  708. * @see addressfield_property_info_callback()
  709. */
  710. function addressfield_auto_creation($property_name, $context) {
  711. return addressfield_default_values($context['field'], $context['instance']);
  712. }
  713. /**
  714. * Defines info for the properties of the address field data structure.
  715. */
  716. function addressfield_data_property_info($name = NULL) {
  717. // Build an array of basic property information for the address field.
  718. $properties = array(
  719. 'country' => array(
  720. 'label' => t('Country'),
  721. 'options list' => '_addressfield_country_options_list',
  722. ),
  723. 'name_line' => array(
  724. 'label' => t('Full name'),
  725. ),
  726. 'first_name' => array(
  727. 'label' => t('First name'),
  728. ),
  729. 'last_name' => array(
  730. 'label' => t('Last name'),
  731. ),
  732. 'organisation_name' => array(
  733. 'label' => t('Company'),
  734. ),
  735. 'administrative_area' => array(
  736. 'label' => t('Administrative area (i.e. State / Province)'),
  737. ),
  738. 'sub_administrative_area' => array(
  739. 'label' => t('Sub administrative area'),
  740. ),
  741. 'locality' => array(
  742. 'label' => t('Locality (i.e. City)'),
  743. ),
  744. 'dependent_locality' => array(
  745. 'label' => t('Dependent locality'),
  746. ),
  747. 'postal_code' => array(
  748. 'label' => t('Postal code'),
  749. ),
  750. 'thoroughfare' => array(
  751. 'label' => t('Thoroughfare (i.e. Street address)'),
  752. ),
  753. 'premise' => array(
  754. 'label' => t('Premise (i.e. Apartment / Suite number)'),
  755. ),
  756. 'sub_premise' => array(
  757. 'label' => t('Sub Premise (i.e. Suite, Apartment, Floor, Unknown.'),
  758. ),
  759. );
  760. // Add the default values for each of the address field properties.
  761. foreach ($properties as $key => &$value) {
  762. $value += array(
  763. 'description' => !empty($name) ? t('!label of field %name', array('!label' => $value['label'], '%name' => $name)) : '',
  764. 'type' => 'text',
  765. 'getter callback' => 'entity_property_verbatim_get',
  766. 'setter callback' => 'entity_property_verbatim_set',
  767. );
  768. }
  769. return $properties;
  770. }
  771. /**
  772. * Returns the country list in a format suitable for use as an options list.
  773. */
  774. function _addressfield_country_options_list($field = NULL, $instance = NULL) {
  775. if (module_exists('countries')) {
  776. $countries = countries_get_countries('name', array('enabled' => COUNTRIES_ENABLED));
  777. }
  778. else {
  779. require_once DRUPAL_ROOT . '/includes/locale.inc';
  780. $countries = country_get_list();
  781. }
  782. if (isset($field)) {
  783. // If the instance is not specified, loop against all the instances of the field.
  784. if (!isset($instance)) {
  785. $instances = array();
  786. foreach ($field['bundles'] as $entity_type => $bundles) {
  787. foreach ($bundles as $bundle_name) {
  788. $instances[] = field_info_instance($entity_type, $field['field_name'], $bundle_name);
  789. }
  790. }
  791. }
  792. else {
  793. $instances = array($instance);
  794. }
  795. foreach ($instances as $instance) {
  796. if (!empty($instance['widget']['settings']['available_countries'])) {
  797. $countries = array_intersect_key($countries, $instance['widget']['settings']['available_countries']);
  798. break;
  799. }
  800. }
  801. }
  802. return $countries;
  803. }