nodereference_url.module 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. <?php
  2. /**
  3. * @file
  4. * Adds a "URL" widget to the Node Reference field.
  5. */
  6. /**
  7. * Implements hook_theme().
  8. */
  9. function nodereference_url_theme() {
  10. return array(
  11. 'nodereference_url' => array(
  12. 'render element' => 'element',
  13. ),
  14. );
  15. }
  16. /**
  17. * Implements hook_form_alter().
  18. */
  19. function nodereference_url_form_alter(&$form, &$form_state, $form_id) {
  20. if ($form_id == 'field_ui_field_edit_form' && isset($form['#instance']) && $form['#instance']['widget']['type'] == 'nodereference_url') {
  21. // Hide settings that don't apply to this widget.
  22. $form['field']['cardinality']['#type'] = 'value';
  23. $form['instance']['description']['#title'] = t('Fallback widget help text');
  24. $form['instance']['description']['#weight'] = -1;
  25. }
  26. }
  27. /**
  28. * Implements hook_widget_info().
  29. */
  30. function nodereference_url_field_widget_info() {
  31. return array(
  32. 'nodereference_url' => array(
  33. 'label' => t('Reference from URL'),
  34. 'description' => t('Node Reference calculated from URL'),
  35. 'field types' => array('node_reference'),
  36. 'settings' => array(
  37. 'fallback' => 'select',
  38. 'node_link' => array(),
  39. 'edit_fallback' => 0,
  40. 'autocomplete_match' => 'contains',
  41. ),
  42. ),
  43. );
  44. }
  45. /**
  46. * Implements hook_node_view().
  47. */
  48. function nodereference_url_node_view($node, $view_mode, $langcode) {
  49. $links = nodereference_url_build_all_links($node, $view_mode);
  50. $node->content['links']['nodereference_url'] = array(
  51. '#theme' => 'links__node__nodereference',
  52. '#links' => $links,
  53. '#attributes' => array('class' => array('links', 'inline')),
  54. );
  55. }
  56. /**
  57. * Build an array of links for nodereference_url widgets that point to this node.
  58. *
  59. * @param $node
  60. * A fully loaded node object.
  61. * @param $teaser
  62. *
  63. * @return
  64. * An array of links for use with theme_links().
  65. */
  66. function nodereference_url_build_all_links($node, $view_mode) {
  67. $links = array();
  68. $fields = field_info_instances('node');
  69. $instances = array();
  70. foreach ($fields as $target_type => $field) {
  71. foreach ($field as $field_name => $instance) {
  72. if ($instance['widget']['type'] == 'nodereference_url') {
  73. $instances[$target_type][$field_name] = $instance;
  74. }
  75. }
  76. }
  77. foreach ($instances as $target_type => $instances_group) {
  78. $alt_format = count($instances_group) > 1;
  79. foreach ($instances_group as $field_name => $instance) {
  80. $link_settings = $instance['widget']['settings']['node_link'];
  81. if (isset($link_settings[$view_mode])) {
  82. if ($link = nodereference_url_build_link($node, $instance, $view_mode, $alt_format)) {
  83. $links[$target_type .'_'. $field_name] = $link;
  84. }
  85. }
  86. }
  87. }
  88. return $links;
  89. }
  90. /**
  91. * Build an individual link.
  92. *
  93. * Checks to ensure that the current node can be referenced by the field, ensures
  94. * the current user has permission to create the field's node type, and builds
  95. * the link based on the field's settings.
  96. *
  97. * @param $node
  98. * A fully loaded node object.
  99. * @param $instance
  100. * A field instance.
  101. * @param $teaser
  102. * Optional. The current display mode of the node. Defaults to 'full'.
  103. * @param $alt_format
  104. * Optional. Use the alternative (safer but more verbose) format for
  105. * generating the link. Defaults to FALSE.
  106. *
  107. * @return
  108. * An array containing properties to build a single link.
  109. */
  110. function nodereference_url_build_link($node, $instance, $view_mode = 'full', $alt_format = FALSE) {
  111. $link = array();
  112. // Load the $field, which contains field-level configuration (such as the
  113. // Views and content type settings).
  114. $field = field_info_field($instance['field_name']);
  115. // Check if this widget is using a views listing.
  116. if (module_exists('views') && !empty($field['settings']['view']['view_name'])) {
  117. // TODO: Remove legacy function after final release of References module.
  118. if (function_exists('node_reference_potential_references')) {
  119. $referenceable = (bool) node_reference_potential_references($field, array('ids' => array($node->nid), 'limit' => 1));
  120. }
  121. else {
  122. $referenceable = (bool) _node_reference_potential_references($field, '', NULL, array($node->nid), 1);
  123. }
  124. }
  125. // Otherwise restrict by node type.
  126. else {
  127. $referenceable = !empty($field['settings']['referenceable_types'][$node->type]);
  128. }
  129. if ($referenceable && node_access('create', $instance['bundle'])) {
  130. $link_settings = $instance['widget']['settings']['node_link'];
  131. if (!empty($link_settings[$view_mode])) {
  132. $link['title'] = t($link_settings['title']);
  133. $link['query'] = array();
  134. // Get the first "preferred" path for creating Node Reference links.
  135. $link_urls = variable_get('nodereference_url_paths', array('node/add/%type/%nid'));
  136. // Basic wildcard replacement: %type and %nid.
  137. $link_url = $link_urls[0];
  138. $link_url = str_replace('%type', str_replace('_', '-', $instance['bundle']), $link_url);
  139. if ($alt_format) {
  140. // The alternative format is used when there are multiple fields on the
  141. // node edit form, so we can't just add an parameter at the end for NID.
  142. $link_url = preg_replace('!/%nid$!', '', $link_url);
  143. $field_name = str_replace('field_', '', $instance['field_name']);
  144. $link['query'][$field_name] = $node->nid;
  145. }
  146. else {
  147. $link_url = str_replace('%nid', $node->nid, $link_url);
  148. }
  149. $link['href'] = $link_url;
  150. if (!empty($link_settings['hover_title'])) {
  151. $link['attributes']['title'] = t($link_settings['hover_title']);
  152. }
  153. if (!empty($link_settings['destination'])) {
  154. if ($link_settings['destination'] == 'source') {
  155. $link['query']['destination'] = isset($_REQUEST['destination']) ? $_REQUEST['destination'] : $_GET['q'];
  156. }
  157. elseif ($link_settings['destination'] == 'node') {
  158. $link['query']['destination'] = drupal_get_path_alias('node/'. $node->nid);
  159. }
  160. }
  161. if (module_exists('og_context')) {
  162. // First try to get context based on the current page URL.
  163. $group_entity = og_get_context_by_url();
  164. // Otherwise try getting the context based on the node being referenced.
  165. if (!$group_entity) {
  166. $group_entity = og_context();
  167. }
  168. if ($group_entity) {
  169. $link['query']['gids'] = array($group_entity->gid);
  170. }
  171. }
  172. }
  173. }
  174. return $link;
  175. }
  176. /**
  177. * Helper function for themers to easily create a link.
  178. *
  179. * This function should be used in custom themes, rather than making manual
  180. * links because it first checks a user's access before showing the link. If
  181. * the user does not have access to create the node then an empty string will
  182. * be returned.
  183. *
  184. * @param $node
  185. * The node object that will be referenced.
  186. * @param $field_name
  187. * The name of the Node Reference field.
  188. * @param $type_name
  189. * The name of node type that contains the Node Reference field.
  190. * @param $attributes
  191. * Optional. An array of additional attributes to add to the link.
  192. */
  193. function nodereference_url_create_link($node, $field_name, $type_name, $attributes = array()) {
  194. $output = '';
  195. $instance = field_info_instance('node', $field_name, $type_name);
  196. $instance['widget']['settings']['node_link']['full'] = TRUE;
  197. if ($link = nodereference_url_build_link($node, $instance)) {
  198. $options = array();
  199. $link_attributes = isset($link['attributes']) ? (array) $link['attributes'] : array();
  200. $options['attributes'] = $attributes + $link_attributes;
  201. if ($link['query']) {
  202. $options['query'] = $link['query'];
  203. }
  204. $output = l($link['title'], $link['href'], $options);
  205. }
  206. return $output;
  207. }
  208. /**
  209. * Implements of hook_elements_info().
  210. *
  211. * Any FAPI callbacks needed for individual widgets can be declared here,
  212. * and the element will be passed to those callbacks for processing.
  213. *
  214. * Drupal will automatically theme the element using a theme with
  215. * the same name as the hook_elements key.
  216. *
  217. * Autocomplete_path is not used by text_widget but other widgets can use it
  218. * (see nodereference and userreference).
  219. */
  220. function nodereference_url_element_info() {
  221. return array(
  222. 'nodereference_url' => array(
  223. '#input' => TRUE,
  224. '#columns' => array('nid'),
  225. '#delta' => 0,
  226. '#process' => array('_nodereference_url_process'),
  227. '#theme' => 'nodereference_url',
  228. '#theme_wrappers' => array('form_element'),
  229. ),
  230. );
  231. }
  232. /**
  233. * Implements hook_field_widget_settings_form().
  234. */
  235. function nodereference_url_field_widget_settings_form($field, $instance) {
  236. $widget = $instance['widget'];
  237. $defaults = field_info_widget_settings($widget['type']);
  238. $settings = array_merge($defaults, $widget['settings']);
  239. $form = array();
  240. if ($widget['type'] == 'nodereference_url') {
  241. $form['fallback'] = array(
  242. '#type' => 'radios',
  243. '#title' => t('Fallback behavior'),
  244. '#options' => array(
  245. 'autocomplete' => t('Use autocomplete widget'),
  246. 'select' => t('Use select list widget'),
  247. 'page_not_found' => t('Display page not found error'),
  248. 'leave_blank' => t('Leave the field blank'),
  249. ),
  250. '#default_value' => isset($settings['fallback']) ? $settings['fallback'] : 'autocomplete',
  251. '#description' => t('If no content is referenced in the URL, determine how the form should be handled.'),
  252. '#required' => TRUE,
  253. '#element_validate' => array('nodereference_url_fallback_validate'),
  254. '#weight' => -11,
  255. );
  256. $form['autocomplete_match'] = array(
  257. '#type' => 'select',
  258. '#title' => t('Autocomplete matching'),
  259. '#default_value' => $settings['autocomplete_match'],
  260. '#options' => array(
  261. 'starts_with' => t('Starts with'),
  262. 'contains' => t('Contains'),
  263. ),
  264. '#description' => t('Select the method used to collect autocomplete suggestions. <br /> Note that <em>Contains</em> can cause performance issues on sites with thousands of nodes.'),
  265. '#states' => array(
  266. 'visible' => array(
  267. ':input[name="instance[widget][settings][fallback]"]' => array('value' => 'autocomplete'),
  268. ),
  269. ),
  270. '#weight' => -10,
  271. );
  272. $form['edit_fallback'] = array(
  273. '#type' => 'checkbox',
  274. '#title' => t('Use fallback behavior when editing content'),
  275. '#default_value' => isset($settings['edit_fallback']) ? $settings['edit_fallback'] : FALSE,
  276. '#weight' => -9,
  277. );
  278. $form['node_link'] = array(
  279. '#tree' => TRUE,
  280. '#type' => 'fieldset',
  281. '#title' => t('Referenceable node links'),
  282. '#element_validate' => array('nodereference_url_node_link_validate'),
  283. '#description' => t('These settings will automatically make a link on nodes that can be referenced. Clicking the link will take the user to the new node form and prepopulate the value of this node reference field.'),
  284. );
  285. $form['node_link']['teaser'] = array(
  286. '#type' => 'checkbox',
  287. '#title' => t('Create link on the teaser view'),
  288. '#default_value' => isset($settings['node_link']['teaser']) ? $settings['node_link']['teaser'] : FALSE,
  289. );
  290. $form['node_link']['full'] = array(
  291. '#type' => 'checkbox',
  292. '#title' => t('Create link on the full view'),
  293. '#default_value' => isset($settings['node_link']['full']) ? $settings['node_link']['full'] : TRUE,
  294. );
  295. $form['node_link']['title'] = array(
  296. '#type' => 'textfield',
  297. '#title' => t('Link title'),
  298. '#default_value' => isset($settings['node_link']['title']) ? $settings['node_link']['title'] : '',
  299. '#description' => t('The title is the visible text for the link. This is required if you enable the content links.'),
  300. );
  301. $form['node_link']['hover_title'] = array(
  302. '#type' => 'textfield',
  303. '#title' => t('Link hover title'),
  304. '#default_value' => isset($settings['node_link']['hover_title']) ? $settings['node_link']['hover_title'] : '',
  305. '#description' => t('Text shown while hovering over the link.'),
  306. );
  307. $form['node_link']['destination'] = array(
  308. '#type' => 'select',
  309. '#title' => t('Return path'),
  310. '#default_value' => isset($settings['node_link']['destination']) ? $settings['node_link']['destination'] : 'default',
  311. '#options' => array(
  312. 'default' => t('The new node (no redirect)'),
  313. 'node' => t('The referenced node'),
  314. 'source' => t('The previous page'),
  315. ),
  316. '#description' => t('After creating the new node through the link, determine where the user should be redirected.'),
  317. );
  318. }
  319. return $form;
  320. }
  321. /**
  322. * Implements hook_field_widget_error().
  323. */
  324. function nodereference_url_field_widget_error($element, $error, $form, &$form_state) {
  325. form_error($element['nid'], $error['message']);
  326. }
  327. /**
  328. * Element validation function to ensure invalid options are not selected.
  329. */
  330. function nodereference_url_fallback_validate($element, &$form_state) {
  331. if ($form_state['values']['instance']['required'] && $form_state['values']['instance']['widget']['settings']['fallback'] == 'leave_blank') {
  332. form_error($element, t('The fallback behavior cannot be left blank if this field is also required.'));
  333. }
  334. }
  335. /**
  336. * Element validation function that makes title required when creating a link.
  337. */
  338. function nodereference_url_node_link_validate($element, &$form_state, $form) {
  339. $link_settings = $form_state['values']['instance']['widget']['settings']['node_link'];
  340. if (($link_settings['teaser'] || $link_settings['full']) && empty($link_settings['title'])) {
  341. form_error($element['title'], t('A link title must be specified if creating links on referenceable content.'));
  342. }
  343. }
  344. /**
  345. * Implements hook_field_widget_form().
  346. */
  347. function nodereference_url_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  348. $field_name = $field['field_name'];
  349. $field_name_url = preg_replace('/^field_/', '', $field_name);
  350. $referenced_nid = NULL;
  351. $fallback = $instance['widget']['settings']['fallback'];
  352. // Check for an existing NID.
  353. if (isset($items[$delta]['nid']) && is_numeric($items[$delta]['nid'])) {
  354. $referenced_nid = $items[$delta]['nid'];
  355. }
  356. // Check in the input array (used during AJAX requests).
  357. elseif (!empty($form_state['input'][$field_name][$langcode][$delta]['nid'])) {
  358. $referenced_nid = $form_state['input'][$field_name][$langcode][$delta]['nid'];
  359. }
  360. // Check for a reference in the query string.
  361. elseif (isset($_GET[$field_name_url]) && is_numeric($_GET[$field_name_url])) {
  362. $referenced_nid = $_GET[$field_name_url];
  363. }
  364. // Pull from the URL.
  365. else {
  366. $referenced_nid = nodereference_url_get_nid($field_name);
  367. }
  368. // Check that the NID is a valid reference.
  369. if (!empty($referenced_nid)) {
  370. // TODO: Remove legacy function after final release of References module.
  371. if (function_exists('node_reference_potential_references')) {
  372. $reference = node_reference_potential_references($field, array('ids' => array($referenced_nid), 'limit' => 1));
  373. }
  374. else {
  375. $reference = _node_reference_potential_references($field, '', 'equals', array($referenced_nid), 1);
  376. }
  377. if (empty($reference)) {
  378. $referenced_nid = NULL;
  379. }
  380. }
  381. // If no NID is available or editing this field, use the fallback behavior.
  382. if (empty($referenced_nid) || (!empty($instance['widget']['settings']['edit_fallback']) && (empty($form['#node_edit_form']) || !empty($form['#node']->{$field_name}[$langcode])))) {
  383. // If not on a node/add page (such as editing a node that does not yet have
  384. // a reference), switch to using an autocomplete widget.
  385. if (in_array($fallback, array('page_not_found', 'leave_blank')) && nodereference_url_get_nid($field_name) === FALSE) {
  386. $fallback = 'autocomplete';
  387. }
  388. // Page not found error.
  389. // Check for the form_build_id to prevent throwing a page not found on
  390. // manual builds. See http://drupal.org/node/397606.
  391. if ($fallback == 'page_not_found') {
  392. drupal_set_message(t('To create a new @type, a referenced piece of content must be specified in the link you followed.', array('@type' => $field['bundles']['node'][0])), 'error');
  393. drupal_not_found();
  394. exit();
  395. }
  396. // Fallback to select list.
  397. elseif ($fallback == 'select') {
  398. $element += array(
  399. '#type' => 'select',
  400. '#default_value' => isset($items[$delta]['nid']) ? $items[$delta]['nid'] : NULL,
  401. '#options' => array('' => t('- None -')) + node_reference_options_list($field),
  402. );
  403. }
  404. // Fallback to autocomplete.
  405. elseif ($fallback == 'autocomplete') {
  406. $element += array(
  407. '#type' => 'textfield',
  408. '#default_value' => isset($items[$delta]['nid']) ? $items[$delta]['nid'] : NULL,
  409. '#autocomplete_path' => 'node_reference/autocomplete/' . $instance['entity_type'] . '/' . $instance['bundle'] . '/' . $field['field_name'],
  410. '#value_callback' => 'node_reference_autocomplete_value',
  411. '#element_validate' => array('node_reference_autocomplete_validate'),
  412. );
  413. }
  414. }
  415. if (isset($referenced_nid) && (empty($element['#type']))) {
  416. $element += array(
  417. '#title' => $instance['label'],
  418. '#type' => 'nodereference_url',
  419. '#field_name' => $field_name,
  420. '#default_value' => $referenced_nid,
  421. );
  422. }
  423. return array('nid' => $element);
  424. }
  425. /**
  426. * Process an individual element.
  427. *
  428. * Build the form element. When creating a form using FAPI #process,
  429. * note that $element['#value'] is already set.
  430. */
  431. function _nodereference_url_process($element, $form_state, $form) {
  432. if (isset($element['#value']) && is_numeric($element['#value']) && ($node = node_load($element['#value']))) {
  433. $element['#display_title'] = check_plain($node->title);
  434. }
  435. else {
  436. $element['#display_title'] = t('Referenced content not found.');
  437. }
  438. $element['nid'] = array(
  439. '#type' => 'hidden',
  440. '#value' => isset($element['#value']) ? $element['#value'] : $element['#value'],
  441. '#parents' => $element['#parents'],
  442. );
  443. return $element;
  444. }
  445. /**
  446. * Check the current URL and pull the referenced node from it.
  447. */
  448. function nodereference_url_get_nid($field_name) {
  449. $add_urls = variable_get('nodereference_url_paths', array('node/add/%type/%nid'));
  450. $field_name_url = preg_replace('/^field_/', '', $field_name);
  451. $referenced_nid = NULL;
  452. foreach ($add_urls as $url) {
  453. $args = explode('/', $url);
  454. foreach ($args as $part => $arg) {
  455. // Set the target NID if matching on this part of the URL.
  456. if ($arg == '%nid') {
  457. $referenced_nid = arg($part);
  458. }
  459. // Set the target NID based on the field name, allowing for multiple
  460. // references in the same URL.
  461. elseif ($arg == '%' . $field_name_url) {
  462. $referenced_nid = arg($part);
  463. }
  464. // Skip any other wildcards in the URL.
  465. elseif (strpos($arg, '%') === 0) {
  466. continue;
  467. }
  468. // Arguments must line up exactly if they're not a wildcard.
  469. elseif (arg($part) != $arg) {
  470. $referenced_nid = FALSE;
  471. break;
  472. }
  473. }
  474. if ($referenced_nid) {
  475. break;
  476. }
  477. }
  478. return $referenced_nid;
  479. }
  480. /**
  481. * FAPI theme for an individual elements.
  482. *
  483. * This theme function controls the display of the widget when an existing item
  484. * is being referenced.
  485. *
  486. * $element['#display_title'] contains the title of the item being referenced.
  487. * $element['#field_name'] contains the field name.
  488. * $element['#delta] is the position of this element in the group.
  489. */
  490. function theme_nodereference_url($variables) {
  491. $element = $variables['element'];
  492. $output = $element['#display_title'];
  493. $output .= drupal_render_children($element);
  494. return $output;
  495. }