addressfield.module 31 KB

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