tripal_core.chado_nodes.relationships.api.inc 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. <?php
  2. /**
  3. * @file
  4. * API to manage the chado _relationship table for various Tripal Node Types
  5. *
  6. * How To Use:
  7. * @code
  8. function chado_example_form($form, &$form_state) {
  9. // Default values for form elements can come in the following ways:
  10. //
  11. // 1) as elements of the $node object. This occurs when editing an existing node
  12. // 2) in the $form_state['values'] array which occurs on a failed validation or
  13. // ajax callbacks when the ajax call originates from non-submit fields other
  14. // than button
  15. // 3) in the $form_state['input'] array which occurs on ajax callbacks from submit
  16. // form elements (e.g. buttons) and the form is being rebuilt but has not yet
  17. // been validated
  18. //
  19. // The reference elements added by this function do use AJAX calls from buttons,
  20. // therefore, it is important to check for form values in the $form_state['values']
  21. // for case #2 above, and in the $form_state['input'] for case #3.
  22. // See the chado analysis node form for an example.
  23. // Next, add in all the form array definition particular to your node type
  24. // To add in the relationship form elements, you first need to prepare the arguments
  25. // for the function call.
  26. $details = array(
  27. 'relationship_table' => 'example_relationship', // the name of the table linking additional dbxrefs to this node
  28. 'base_table' => 'example', // the name of the chado table this node links to
  29. 'base_foreign_key' => 'example_id', // key to link to the chado content created by this node
  30. 'base_key_value' => $example_id, // the value of the above key
  31. 'fieldset_title' => 'Relationships', // the non-translated title for this fieldset
  32. 'additional_instructions' => '' // a non-stranslated string providing additional instructions
  33. );
  34. // Finally, and add the additional form elements to the form
  35. chado_add_node_form_relationships($form, $form_state, $details);
  36. return $form;
  37. }
  38. function chado_example_insert($node) {
  39. // if there is an example_id in the $node object then this must be a sync so
  40. // we can skip adding the chado_example as it is already there, although
  41. // we do need to proceed with the rest of the insert
  42. if (!property_exists($node, 'example_id')) {
  43. // Add record to chado example table
  44. // Add to any other tables needed
  45. // Add all relationships
  46. // Existing _relationship links with the current example as either the subject_id
  47. // or object_id will be cleared and then re-added
  48. chado_update_node_form_relationships(
  49. $node,
  50. 'example_relationship',
  51. $node->example_id
  52. );
  53. }
  54. // Add record to chado_example linking example_id to new node
  55. }
  56. function chado_example_update($node) {
  57. // Update record in chado example table
  58. // Update any other tables needed
  59. // Update all additional database references
  60. // Existing _relationship links with the current example as either the subject_id
  61. // or object_id will be cleared and then re-added
  62. chado_update_node_form_relationships(
  63. $node,
  64. 'example_relationship',
  65. $node->example_id
  66. );
  67. // Don't need to update chado_example linking table since niether example_id or nid can be changed in update
  68. }
  69. * @endcode
  70. *
  71. * @ingroup tripal_chado_node_api
  72. */
  73. /**
  74. * Provides a form for adding to BASE_relationship and relationship tables
  75. *
  76. * @param $form
  77. * The Drupal form array into which the relationship elements will be added
  78. * @param $form_state
  79. * The corresponding form_state array for the form
  80. * @param $details
  81. * An array defining details needed by this form. Required Keys are:
  82. * - relationship_table: the name of the relationship table (ie: feature_relationship)
  83. * - base_table: the name of the base table (ie: feature)
  84. * - base_foreign_key: the name of the foreign key in the relationship table field linking this table to the non-relationship table (ie: feature_id)
  85. * - base_key_value: the value of the base_foreign_key for the current form (ie: 999 if the feature_id=999)
  86. * - nodetype: the non-translated singular title of this node type
  87. * One of the following:
  88. * - cv_id: the id of the ontology to supply terms for the type dropdown
  89. * - cv_name: the name of the ontology to supply terms for the type dropdown
  90. * Optional keys include:
  91. * - fieldset_title: the non-translated title for this fieldset
  92. * - additional_instructions: a non-translated string providing additional instructions
  93. * - nodetype_plural: the non-translated plural title of this node type
  94. * - select_options: must be an array where the [key] is a valid cvterm_id and
  95. * the [value] is the human-readable name of the option. This is generated from the cv_name/id by default
  96. * - base_name_field: the field in your base table you want to be used as the name of the record
  97. * - subject_field_name: the name of the subject field in your relationship table (default: subject_id)
  98. * - object_field_name: the name of the object field in your relationship table (default: object_id)
  99. *
  100. * @ingroup tripal_chado_node_api
  101. */
  102. function chado_add_node_form_relationships(&$form, &$form_state, $details) {
  103. // make sure the relationship table exists before proceeding.
  104. if (!chado_table_exists($details['relationship_table'])) {
  105. drupal_set_message("Cannot add relationship elements to the form. The relationship table, '" .
  106. $details['relationship_table'] . "', does not exists", "error");
  107. tripal_report_error('tcrel_form', TRIPAL_ERROR, "Cannot add relationship elements to the form.
  108. The relationship table, '%name', cannot be found.", array('%name' => $details['relationship_table']));
  109. return;
  110. }
  111. // make sure the specified cv exists
  112. if (isset($details['cv_name'])) {
  113. // make sure the cv_name is real
  114. $result = chado_select_record('cv',array('cv_id'),array('name' => $details['cv_name']));
  115. if (count($result) == 0) {
  116. drupal_set_message("Cannot add relationship elements to the form. The CV name, '" .
  117. $details['cv_name'] . "', does not exists", "error");
  118. tripal_report_error('tcrel_form', TRIPAL_ERROR, "Cannot add relationship elements to the form.
  119. The CV named, '%name', cannot be found.", array('%name' => $details['cv_name']));
  120. return;
  121. }
  122. // add the cv_id option to the details array
  123. $details['cv_id'] = $result[0]->cv_id;
  124. }
  125. elseif (isset($details['cv_id'])) {
  126. // make sure the cv_id is real
  127. $result = chado_select_record('cv', array('name'), array('cv_id' => $details['cv_id']));
  128. if (count($result) == 0) {
  129. drupal_set_message("Cannot add relationship elements to the form. The CV ID, '" .
  130. $details['cv_id'] . "', does not exist", "error");
  131. tripal_report_error('tcrel_form', TRIPAL_ERROR, "Cannot add relationship elements
  132. to the form. The CV ID, '%id', cannot be found.", array('%id' => $details['cv_id']));
  133. return;
  134. }
  135. // add the cv_name option to the details array
  136. $details['cv_name'] = $result[0]->name;
  137. }
  138. else {
  139. // If we didn't get given a cv identifier, then try retrieving the default one
  140. // using the new cv defaults api
  141. $default_cv = tripal_get_default_cv($details['relationship_table'], 'type_id');
  142. if (!empty($default_cv)) {
  143. $details['cv_id'] = $default_cv->cv_id;
  144. $details['cv_name'] = $default_cv->name;
  145. }
  146. else {
  147. $default_form_link = l('vocabulary defaults configuration page',
  148. 'admin/tripal/chado/tripal_cv/defaults',
  149. array('attributes' => array('target' => '_blank')));
  150. $table = ucwords(str_replace('_',' ',$details['base_table']));
  151. $message = "There is not a default vocabulary set for $table Releationship Types. Please set one using the $default_form_link.";
  152. tripal_set_message($message, TRIPAL_WARNING);
  153. tripal_report_error('tcrel_form', TRIPAL_ERROR, "Please provide either a
  154. 'cv_name' or 'cv_id' as an option for adding relationship to the form", array());
  155. return;
  156. }
  157. }
  158. // Set Defaults for optional fields
  159. $details['fieldset_title'] = (isset($details['fieldset_title'])) ? $details['fieldset_title'] : 'Relationships';
  160. $details['additional_instructions'] = (isset($details['additional_instructions'])) ? $details['additional_instructions'] : '';
  161. $details['nodetype_plural'] = (isset($details['nodetype_plural'])) ? $details['nodetype_plural'] : $details['nodetype'] . 's';
  162. $details['base_name_field'] = (isset($details['base_name_field'])) ? $details['base_name_field'] : 'uniquename';
  163. $details['subject_field_name'] = (isset($details['subject_field_name'])) ? $details['subject_field_name'] : 'subject_id';
  164. $details['object_field_name'] = (isset($details['object_field_name'])) ? $details['object_field_name'] : 'object_id';
  165. $details['form_element_name'] = (isset($details['form_element_name'])) ? $details['form_element_name'] : $details['base_name_field'];
  166. // Some relationship tables don't have a rank
  167. // thus we need to first check this table has a rank before trying to set it
  168. $table_schema = chado_get_schema($details['relationship_table']);
  169. $details['table_has_rank'] = (isset($table_schema['fields']['rank'])) ? TRUE : FALSE;
  170. // Get Relationship Types for the Select List
  171. if (isset($details['select_options'])) {
  172. $type_options = $details['select_options'];
  173. }
  174. else {
  175. if (isset($details['cv_name'])) {
  176. $type_options = array();
  177. $type_options[] = 'Select a Type';
  178. $sql = "
  179. SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition, CV.cv_id as cv_id
  180. FROM {cvterm} CVT
  181. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  182. WHERE
  183. CV.name = :cv_name AND
  184. NOT CVT.is_obsolete = 1
  185. ORDER BY CVT.name ASC
  186. ";
  187. $cvterms = chado_query($sql, array(':cv_name' => $details['cv_name']));
  188. while ($term = $cvterms->fetchObject()) {
  189. $type_options[$term->cvterm_id] = $term->name;
  190. $details['cv_id'] = $term->cv_id;
  191. }
  192. }
  193. elseif (isset($details['cv_id'])) {
  194. $type_options = array();
  195. $type_options[] = 'Select a Type';
  196. $sql = "
  197. SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition, CV.name AS cv_name
  198. FROM {cvterm} CVT
  199. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  200. WHERE
  201. CV.cv_id = :cv_id AND
  202. NOT CVT.is_obsolete = 1
  203. ORDER BY CVT.name ASC
  204. ";
  205. $cvterms = chado_query($sql, array(':cv_id' => $details['cv_id']));
  206. while ($term = $cvterms->fetchObject()) {
  207. $type_options[$term->cvterm_id] = $term->name;
  208. $details['cv_name'] = $term->cv_name;
  209. }
  210. }
  211. }
  212. // Tell tripal administrators how to add terms to the relationship types drop down.
  213. if (empty($type_options)) {
  214. $tripal_message = tripal_set_message(
  215. t('There are currently no relationship types! To add additional relationship types to the drop
  216. down list, you need to <a href="@cvtermlink">add a controlled vocabulary term</a>
  217. to the %cv_name controlled vocabulary.',
  218. array(
  219. '%cv_name' => $details['cv_name'],
  220. '@cvtermlink' => url('admin/tripal/chado/tripal_cv/cv/'.$details['cv_id'].'/cvterm/add')
  221. )
  222. ),
  223. TRIPAL_WARNING,
  224. array('return_html' => TRUE)
  225. );
  226. }
  227. else {
  228. $tripal_message = tripal_set_message(
  229. t('To add additional relationship types to the drop down list, you need to <a href="@cvtermlink">add
  230. a controlled vocabulary term</a> to the %cv_name controlled vocabulary.',
  231. array(
  232. '%cv_name' => $details['cv_name'],
  233. '@cvtermlink' => url('admin/tripal/chado/tripal_cv/cv/' . $details['cv_id'] . '/cvterm/add')
  234. )
  235. ),
  236. TRIPAL_INFO,
  237. array('return_html' => TRUE)
  238. );
  239. }
  240. // Group all of the chado node api fieldsets into vertical tabs.
  241. $form['chado_node_api'] = array(
  242. '#type' => 'vertical_tabs',
  243. '#attached' => array(
  244. 'css' => array(
  245. 'chado-node-api' => drupal_get_path('module', 'tripal_core') . '/theme/css/chado_node_api.css',
  246. ),
  247. ),
  248. );
  249. $form['relationships'] = array(
  250. '#type' => 'fieldset',
  251. '#title' => t($details['fieldset_title']),
  252. '#collapsible' => TRUE,
  253. '#collapsed' => TRUE,
  254. '#group' => 'chado_node_api',
  255. '#weight' => 10,
  256. '#attributes' => array('class' => array('chado-node-api','relationships')),
  257. '#attached' => array(
  258. 'js' => array(
  259. 'chado-node-api-vertical-tabs' => drupal_get_path('module', 'tripal_core') . '/theme/js/chadoNodeApi_updateVerticalTabSummary.js',
  260. ),
  261. ),
  262. );
  263. $instructions = 'Relationships should be read like a sentence ([subject] [type]
  264. [object]) in order to determine their direction and thus their meaning. When
  265. adding a relationship, it is easiest to first select the type of relationship you would
  266. like to enter and then select whether the current %nodetype is the subject
  267. or object (based on which "sentence" makes sense). Finally enter the other
  268. %nodetype in the remaining text box (making sure to select from the
  269. autocomplete drop-down) before clicking "Add". To remove incorrect relationships, click the
  270. "Remove" button. Note: you cannot edit previously added relationships
  271. but instead need to remove and re-add them.';
  272. $form['relationships']['descrip'] = array(
  273. '#type' => 'item',
  274. '#markup' => t('<p><strong>Relate the current %nodetype with others that already exist.</strong></p><p>'. $instructions . $details['additional_instructions'] . '</p>', array('%nodetype' => $details['nodetype'])),
  275. );
  276. // this form element is a tree, so that we don't puke all of the values into then node variable
  277. // it is set as a tree, and keeps them in the $form_state['values']['relationship_table'] heading.
  278. $form['relationships']['relationship_table'] = array(
  279. '#type' => 'markup',
  280. '#tree' => TRUE,
  281. '#prefix' => '<div id="tripal-generic-edit-relationships-table">',
  282. '#suffix' => '</div>',
  283. '#theme' => 'chado_node_relationships_form_table'
  284. );
  285. // Add defaults into form_state to be used elsewhere
  286. $form['relationships']['relationship_table']['details'] = array(
  287. '#type' => 'hidden',
  288. '#value' => serialize($details)
  289. );
  290. // Add relationships already attached to the node
  291. //---------------------------------------------
  292. /* Relationships can come to us in two ways:
  293. *
  294. * 1) In the form state in the $form_state['chado_relationships']. Data is in this field
  295. * when an AJAX call updates the form state or a validation error.
  296. *
  297. * 2) Directly from the database if the record already has _relationships associated. This
  298. * data is only used the first time the form is loaded. On AJAX calls or validation
  299. * errors the fields on the form are populated from the $form_state['chado_relationships']
  300. * entry.
  301. */
  302. if (isset($form_state['chado_relationships'])) {
  303. $existing_rels = $form_state['chado_relationships'];
  304. }
  305. else {
  306. $existing_rels = chado_query(
  307. "SELECT
  308. rel.*,
  309. rel.".$details['relationship_table']."_id as relationship_id,
  310. rel.".$details['subject_field_name']." as subject_id,
  311. rel.".$details['object_field_name']." as object_id,
  312. base1.".$details['base_name_field']." as object_name,
  313. base2.".$details['base_name_field']." as subject_name,
  314. cvterm.name as type_name
  315. FROM {".$details['relationship_table']."} rel
  316. LEFT JOIN {".$details['base_table']."} base1 ON base1.".$details['base_foreign_key']." = rel.".$details['object_field_name']."
  317. LEFT JOIN {".$details['base_table']."} base2 ON base2.".$details['base_foreign_key']." = rel.".$details['subject_field_name']."
  318. LEFT JOIN {cvterm} cvterm ON cvterm.cvterm_id = rel.type_id
  319. WHERE rel.".$details['object_field_name']." = :base_key_value
  320. OR rel.".$details['subject_field_name']." = :base_key_value",
  321. array(':base_key_value' => $details['base_key_value'])
  322. );
  323. }
  324. /* The format of the $existing_rels' array is either:
  325. *
  326. * From the chado_relationships array:
  327. * $form_state['chado_relationships'] = array(
  328. * '[type_id]-[_relationship_id]' => array(
  329. * 'relationship_id' => [the _relationship._relationship_id value OR a temporary value if not yet saved to the database],
  330. * 'object_id' => [the _relationship.object_id value],
  331. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  332. * 'subject_id' => [the _relationship.subject_id value],
  333. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  334. * 'type_id' => [the _relationship.type_id value],
  335. * 'type_name' => [the cvterm.name value linked on type_id],
  336. * 'rank' => [the _relationship.rank value OR NULL if not yet saved to the database],
  337. * ),
  338. * );
  339. *
  340. * OR
  341. * Populated from the database:
  342. * $existing_rels = array(
  343. * 0 => array(
  344. * 'relationship_id' => [the _relationship._relationship_id value],
  345. * 'object_id' => [the _relationship.object_id value],
  346. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  347. * 'subject_id' => [the _relationship.subject_id value],
  348. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  349. * 'type_id' => [the _relationship.type_id value],
  350. * 'type_name' => [the cvterm.name value linked on type_id],
  351. * 'rank' => [the _relationship.rank value],
  352. * ),
  353. * );
  354. *
  355. * NOTE: The main difference is the key
  356. *
  357. * Loop on the array elements of the $existing_rels array and add
  358. * an element to the form for each one.
  359. */
  360. $num_relationships = 0;
  361. foreach ($existing_rels as $relationship) {
  362. if (array_key_exists($relationship->type_id, $type_options)) {
  363. $num_relationships++;
  364. $form['relationships']['relationship_table'][$relationship->type_id]['#type'] = 'markup';
  365. $form['relationships']['relationship_table'][$relationship->type_id]['#type'] = '';
  366. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['#type'] = 'markup';
  367. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['#value'] = '';
  368. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['#attributes'] = array(
  369. 'class' => array('relationship', 'saved')
  370. );
  371. // Determine whether this relationship is unsaved or not.
  372. // We can tell this by looking at the relationship_id: if it's not
  373. // saved yet we will have entered a TEMP###.
  374. if (preg_match('/^TEMP/', $relationship->relationship_id)) {
  375. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['#attributes'] = array(
  376. 'class' => array('relationship', 'unsaved')
  377. );
  378. }
  379. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['relationship_id'] = array(
  380. '#type' => 'markup',
  381. '#markup' => $relationship->relationship_id
  382. );
  383. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['object_id'] = array(
  384. '#type' => 'hidden',
  385. '#value' => $relationship->object_id
  386. );
  387. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['subject_id'] = array(
  388. '#type' => 'hidden',
  389. '#value' => $relationship->subject_id
  390. );
  391. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['type_id'] = array(
  392. '#type' => 'hidden',
  393. '#value' => $relationship->type_id
  394. );
  395. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['object_name'] = array(
  396. '#type' => 'markup',
  397. '#markup' => $relationship->object_name
  398. );
  399. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['type_name'] = array(
  400. '#type' => 'markup',
  401. '#markup' => $relationship->type_name
  402. );
  403. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['subject_name'] = array(
  404. '#type' => 'markup',
  405. '#markup' => $relationship->subject_name
  406. );
  407. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['rank'] = array(
  408. '#type' => 'markup',
  409. '#markup' => (isset($relationship->rank)) ? $relationship->rank : NULL
  410. );
  411. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['rel_action'] = array(
  412. '#type' => 'submit',
  413. '#value' => t('Remove'),
  414. '#name' => "relationships_remove-".$relationship->type_id.'-'.$relationship->relationship_id,
  415. '#ajax' => array(
  416. 'callback' => 'chado_add_node_form_subtable_ajax_update',
  417. 'wrapper' => 'tripal-generic-edit-relationships-table',
  418. 'effect' => 'fade',
  419. 'method' => 'replace',
  420. 'prevent' => 'click'
  421. ),
  422. // When this button is clicked, the form will be validated and submitted.
  423. // Therefore, we set custom submit and validate functions to override the
  424. // default node form submit. In the validate function we validate only the
  425. // relationship fields and in the submit we remove the indicated relationship
  426. // from the chado_relationships array. In order to keep validate errors
  427. // from the node form validate and Drupal required errors for non-relationship fields
  428. // preventing the user from removing relationships we set the #limit_validation_errors below
  429. '#validate' => array('chado_add_node_form_subtables_remove_button_validate'),
  430. '#submit' => array('chado_add_node_form_subtables_remove_button_submit'),
  431. // Limit the validation of the form upon clicking this button to the relationship_table tree
  432. // No other fields will be validated (ie: no fields from the main form or any other api
  433. // added form).
  434. '#limit_validation_errors' => array(
  435. array('relationship_table') // Validate all fields within $form_state['values']['relationship_table']
  436. )
  437. );
  438. }
  439. }
  440. // Quickly add a hidden field stating how many relationships are currently added.
  441. $form['relationships']['num_relationships'] = array(
  442. '#type' => 'hidden',
  443. '#value' => $num_relationships,
  444. '#attributes' => array('class' => 'num-relationships')
  445. );
  446. // Form elements for adding a new relationship
  447. //---------------------------------------------
  448. $form['relationships']['relationship_table']['new']['object_name'] = array(
  449. '#type' => 'textfield',
  450. '#autocomplete_path' => 'tripal_ajax/relationship_nodeform/' . $details['base_table'] . '/' . $details['base_name_field'].'/name_to_id'
  451. );
  452. $form['relationships']['relationship_table']['new']['object_is_current'] = array(
  453. '#type' => 'checkbox',
  454. '#title' => t('Current '.$details['nodetype']),
  455. );
  456. $form['relationships']['relationship_table']['new']['type_name'] = array(
  457. '#type' => 'select',
  458. '#options' => $type_options,
  459. );
  460. $form['relationships']['relationship_table']['new']['subject_name'] = array(
  461. '#type' => 'textfield',
  462. '#autocomplete_path' => 'tripal_ajax/relationship_nodeform/' . $details['base_table'] . '/' . $details['base_name_field'].'/name_to_id'
  463. );
  464. $form['relationships']['relationship_table']['new']['subject_is_current'] = array(
  465. '#type' => 'checkbox',
  466. '#title' => t('Current ' . $details['nodetype']),
  467. );
  468. $form['relationships']['relationship_table']['new']['rank'] = array(
  469. '#type' => 'markup',
  470. '#markup' => ''
  471. );
  472. $form['relationships']['relationship_table']['new']['rel_action'] = array(
  473. '#type' => 'submit',
  474. '#value' => t('Add'),
  475. '#name' => 'relationships-add',
  476. '#ajax' => array(
  477. 'callback' => 'chado_add_node_form_subtable_ajax_update',
  478. 'wrapper' => 'tripal-generic-edit-relationships-table',
  479. 'effect' => 'fade',
  480. 'method' => 'replace',
  481. ),
  482. // When this button is clicked, the form will be validated and submitted.
  483. // Therefore, we set custom submit and validate functions to override the
  484. // default node form submit. In the validate function we validate only the
  485. // relationship fields and in the submit we add them to the chado_relationships
  486. // array. In order to keep validate errors from the node form validate and Drupal
  487. // required errors for non-relationship fields preventing the user from adding relationships we
  488. // set the #limit_validation_errors below
  489. '#validate' => array('chado_add_node_form_subtables_add_button_validate'),
  490. '#submit' => array('chado_add_node_form_subtables_add_button_submit'),
  491. // Limit the validation of the form upon clicking this button to the relationship_table tree
  492. // No other fields will be validated (ie: no fields from the main form or any other api
  493. // added form).
  494. '#limit_validation_errors' => array(
  495. array('relationship_table') // Ensure relationship table results are not discarded.
  496. )
  497. );
  498. $form['relationships']['admin_message'] = array(
  499. '#type' => 'markup',
  500. '#markup' => $tripal_message
  501. );
  502. }
  503. /**
  504. * Validate the user input for creating a new relationship.
  505. * Called by the add button in chado_add_node_form_relationships.
  506. *
  507. * @ingroup tripal_core
  508. */
  509. function chado_add_node_form_relationships_add_button_validate($form, &$form_state) {
  510. $details = unserialize($form_state['values']['relationship_table']['details']);
  511. // First deal with autocomplete fields.
  512. // Extract the base_id assuming '(###) NAME FIELD'.
  513. if (!empty($form_state['values']['relationship_table']['new']['subject_name'])) {
  514. if (preg_match('/\((\d+)\) .*/', $form_state['values']['relationship_table']['new']['subject_name'], $matches)) {
  515. $form_state['values']['relationship_table']['new']['subject_id'] = $matches[1];
  516. }
  517. else {
  518. form_set_error('relationship_table][new][subject_name', 'You need to select the subject from the autocomplete drop-down');
  519. }
  520. }
  521. if (!empty($form_state['values']['relationship_table']['new']['object_name'])) {
  522. if (preg_match('/\((\d+)\) .*/', $form_state['values']['relationship_table']['new']['object_name'], $matches)) {
  523. $form_state['values']['relationship_table']['new']['object_id'] = $matches[1];
  524. }
  525. else {
  526. form_set_error('relationship_table][new][object_name', 'You need to select the object from the autocomplete drop-down');
  527. }
  528. }
  529. // NOTE: The only way to specify the current node is via checkbox. This is by
  530. // design since guessing if they meant the current node by name is a
  531. // chicken-egg problem due to the name field only being set to just the name
  532. // only happens once it has been determined which germplasm is the current
  533. // one. Furthermore, we can't use the primary key since this will not have
  534. // been set on insert.
  535. // At least one of the participants must be the current node.
  536. if (!($form_state['values']['relationship_table']['new']['subject_is_current'] OR $form_state['values']['relationship_table']['new']['object_is_current'])) {
  537. form_set_error('relationship_table][new][object_is_current', 'At least one member of the relationship must be
  538. the current '.$details['nodetype'].'. This is specified by checking the "Current '.$details['nodetype'].'"
  539. checkbox for either the subject or object.');
  540. }
  541. // Only one of the participants may be the current node.
  542. // We do not support circular relationships.
  543. if ($form_state['values']['relationship_table']['new']['subject_is_current']
  544. AND $form_state['values']['relationship_table']['new']['object_is_current']) {
  545. form_set_error('relationship_table][new][object_is_current', 'Only one member of the relationship may be
  546. the current '.$details['nodetype'].'. This is specified by checking the "Current '.$details['nodetype'].'"
  547. checkbox for either the subject or object.');
  548. }
  549. // If it was determined current via checkbox, we need to ensure the name
  550. // provided actually matches the current node.
  551. if ($form_state['values']['relationship_table']['new']['subject_is_current']
  552. AND !empty($form_state['values']['relationship_table']['new']['subject_name'])
  553. AND $form_state['values']['relationship_table']['new']['subject_name'] != $form_state['values'][$details['form_element_name']]) {
  554. form_set_error('relationship_table][new][subject_name',
  555. 'The name you supplied for the current '.$details['nodetype'].' doesn\'t match the actual name
  556. of this '.$details['nodetype'].'. If you really meant the subject should be the current '.$details['nodetype'].',
  557. simply leave the textfield empty and re-add this relationship.');
  558. }
  559. if ($form_state['values']['relationship_table']['new']['object_is_current']
  560. AND !empty($form_state['values']['relationship_table']['new']['object_name'])
  561. AND $form_state['values']['relationship_table']['new']['object_name'] != $form_state['values'][$details['form_element_name']]) {
  562. form_set_error('relationship_table][new][object_name',
  563. 'The name you supplied for the current '.$details['nodetype'].' doesn\'t match the actual name
  564. of this '.$details['nodetype'].'. If you really meant the object should be the current '.$details['nodetype'].',
  565. simply leave the textfield empty and re-add this relationship.');
  566. }
  567. // The non-current uniquename must be exist in the base table (subject).
  568. if (!($form_state['values']['relationship_table']['new']['subject_is_current'])) {
  569. $result = chado_select_record(
  570. $details['base_table'],
  571. array($details['base_name_field']),
  572. array($details['base_foreign_key'] => $form_state['values']['relationship_table']['new']['subject_id'])
  573. );
  574. if (!isset($result[0])) {
  575. form_set_error('relationship_table][new][subject_name', 'The subject must be the unique name of an
  576. existing '.$details['nodetype'].' unless the "Current '.$details['nodetype'].'" checkbox is selected');
  577. }
  578. else {
  579. $form_state['values']['relationship_table']['new']['subject_name'] = $result[0]->{$details['base_name_field']};
  580. }
  581. }
  582. // The non-current uniquename must exist in the base table (object).
  583. if (!($form_state['values']['relationship_table']['new']['object_is_current'])) {
  584. $result = chado_select_record(
  585. $details['base_table'],
  586. array($details['base_name_field']),
  587. array($details['base_foreign_key'] => $form_state['values']['relationship_table']['new']['object_id'])
  588. );
  589. if (!isset($result[0])) {
  590. form_set_error('relationship_table][new][object_name', 'The object must be the unique name of an
  591. existing '.$details['nodetype'].' unless the "Current '.$details['nodetype'].'" checkbox is selected');
  592. }
  593. else {
  594. $form_state['values']['relationship_table']['new']['object_name'] = $result[0]->{$details['base_name_field']};
  595. }
  596. }
  597. // The type must be a valid cvterm.
  598. if ($form_state['values']['relationship_table']['new']['type_name']) {
  599. $form_state['values']['relationship_table']['new']['type_id'] = $form_state['values']['relationship_table']['new']['type_name'];
  600. $result = chado_select_record(
  601. 'cvterm',
  602. array('name'),
  603. array('cvterm_id' => $form_state['values']['relationship_table']['new']['type_id'])
  604. );
  605. if (!isset($result[0])) {
  606. form_set_error('relationship_table][new][type_id', 'The select type is not a valid controlled vocabulary term.');
  607. }
  608. else {
  609. $form_state['values']['relationship_table']['new']['type_name'] = $result[0]->name;
  610. }
  611. }
  612. else {
  613. form_set_error('relationship_table][new][type_id', 'Please select a type of relationship');
  614. }
  615. }
  616. /**
  617. * Called by the add button in chado_add_node_form_relationships
  618. *
  619. * Create an array of additional relationships in the form state. This array will then be
  620. * used to rebuild the form in subsequent builds
  621. *
  622. * @ingroup tripal_core
  623. */
  624. function chado_add_node_form_relationships_add_button_submit($form, &$form_state) {
  625. $details = unserialize($form_state['values']['relationship_table']['details']);
  626. // if the chado_relationships array is not set then this is the first time modifying the
  627. // relationship table. this means we need to include all the relationships from the db
  628. if (!isset($form_state['chado_relationships'])) {
  629. chado_add_node_form_relationships_create_relationship_formstate_array($form, $form_state);
  630. }
  631. $name = (isset($form_state['node']->{$details['base_table']}->uniquename)) ? $form_state['node']->{$details['base_table']}->uniquename : 'CURRENT';
  632. // get details for the new relationship
  633. if ($form_state['values']['relationship_table']['new']['subject_is_current']) {
  634. $relationship = array(
  635. 'type_id' => $form_state['values']['relationship_table']['new']['type_id'],
  636. 'type_name' => $form_state['values']['relationship_table']['new']['type_name'],
  637. 'object_id' => $form_state['values']['relationship_table']['new']['object_id'],
  638. 'object_name' => $form_state['values']['relationship_table']['new']['object_name'],
  639. 'subject_id' => $form_state['node']->{$details['base_table']}->{$details['base_foreign_key']},
  640. 'subject_name' => $name,
  641. 'rank' => NULL,
  642. 'relationship_id' => 'TEMP' . uniqid()
  643. );
  644. // we don't want the new element to pick up the values from the previous element so wipe them out
  645. unset($form_state['input']['relationship_table']['new']['object_id']);
  646. unset($form_state['input']['relationship_table']['new']['object_name']);
  647. }
  648. else {
  649. $relationship = array(
  650. 'type_id' => $form_state['values']['relationship_table']['new']['type_id'],
  651. 'type_name' => $form_state['values']['relationship_table']['new']['type_name'],
  652. 'object_id' => $form_state['node']->{$details['base_table']}->{$details['base_foreign_key']},
  653. 'object_name' => $name,
  654. 'subject_id' => $form_state['values']['relationship_table']['new']['subject_id'],
  655. 'subject_name' => $form_state['values']['relationship_table']['new']['subject_name'],
  656. 'rank' => NULL,
  657. 'relationship_id' => 'TEMP' . uniqid(),
  658. );
  659. // we don't want the new element to pick up the values from the previous element so wipe them out
  660. unset($form_state['input']['relationship_table']['new']['subject_id']);
  661. unset($form_state['input']['relationship_table']['new']['subject_name']);
  662. }
  663. $key = $relationship['type_id'] . '-' . $relationship['relationship_id'];
  664. $form_state['chado_relationships'][$key] = (object) $relationship;
  665. // we don't want the new element to pick up the values from the previous element so wipe them out
  666. unset($form_state['input']['relationship_table']['new']['type_id']);
  667. unset($form_state['input']['relationship_table']['new']['type_name']);
  668. }
  669. /**
  670. * Called by the many remove buttons in chado_add_node_form_relationships
  671. *
  672. * @ingroup tripal_core
  673. */
  674. function chado_add_node_form_relationships_remove_button_validate($form, &$form_state) {
  675. // No validation needed.
  676. }
  677. /**
  678. * Remove the correct relationship from the form
  679. * Called by the many remove buttons in chado_add_node_form_relationships
  680. *
  681. * @ingroup tripal_core
  682. */
  683. function chado_add_node_form_relationships_remove_button_submit(&$form, &$form_state) {
  684. // if the chado_relationships array is not set then this is the first time modifying the
  685. // relationship table. this means we need to include all the relationships from the db
  686. chado_add_node_form_relationships_create_relationship_formstate_array($form, $form_state);
  687. // remove the specified relationship from the form relationship table
  688. if(preg_match('/relationships_remove-([^-]+-[^-]+)/',$form_state['triggering_element']['#name'],$match)) {
  689. $key = $match[1];
  690. if (array_key_exists($key, $form_state['chado_relationships'])) {
  691. unset($form_state['chado_relationships'][$key]);
  692. }
  693. }
  694. }
  695. /**
  696. * Creates an array in form_state containing the existing relationships. This array is
  697. * then modified by the add/remove buttons and used as a source for rebuilding the form.
  698. *
  699. * $form_state['chado_relationships'] = array(
  700. * '[type_id]-[rank]' => array(
  701. * 'object_id' => [the _relationship.object_id value],
  702. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  703. * 'subject_id' => [the _relationship.subject_id value],
  704. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  705. * 'type_id' => [the _relationship.type_id value],
  706. * 'type_name' => [the cvterm.name value linked on type_id],
  707. * 'rank' => [the _relationship.rank value],
  708. * ),
  709. * );
  710. *
  711. * @ingroup tripal_core
  712. */
  713. function chado_add_node_form_relationships_create_relationship_formstate_array($form, &$form_state) {
  714. $form_state['chado_relationships'] = array();
  715. foreach (element_children($form['relationships']['relationship_table']) as $type_id) {
  716. if ($type_id != 'new') {
  717. foreach (element_children($form['relationships']['relationship_table'][$type_id]) as $relationship_id) {
  718. $element = $form['relationships']['relationship_table'][$type_id][$relationship_id];
  719. $rel = array(
  720. 'type_id' => $element['type_id']['#value'],
  721. 'object_id' => $element['object_id']['#value'],
  722. 'subject_id' => $element['subject_id']['#value'],
  723. 'type_name' => $element['type_name']['#markup'],
  724. 'object_name' => $element['object_name']['#markup'],
  725. 'subject_name' => $element['subject_name']['#markup'],
  726. 'rank' => $element['rank']['#markup'],
  727. 'relationship_id' => $relationship_id,
  728. );
  729. $key = $rel['type_id'] . '-' . $rel['relationship_id'];
  730. $form_state['chado_relationships'][$key] = (object) $rel;
  731. }
  732. }
  733. }
  734. }
  735. /**
  736. * Function to theme the add/remove relationships form into a table
  737. *
  738. * @ingroup tripal_chado_node_api
  739. */
  740. function theme_chado_add_node_form_relationships_table($variables) {
  741. $element = $variables['element'];
  742. $details = unserialize($element['details']['#value']);
  743. $header = array(
  744. 'subject_name' => t('Subject ' . $details['base_name_field']),
  745. 'type_name' => t('Type'),
  746. 'object_name' => t('Object ' . $details['base_name_field']),
  747. 'rel_action' => t('Action')
  748. );
  749. $rows = array();
  750. foreach (element_children($element) as $type_id) {
  751. if ($type_id == 'new') {
  752. $row = array();
  753. $row['data'] = array();
  754. foreach ($header as $fieldname => $title) {
  755. if ($fieldname == 'subject_name') {
  756. $row['data'][] = drupal_render($element[$type_id][$fieldname]) . drupal_render($element[$type_id]['subject_is_current']);
  757. }
  758. elseif ($fieldname == 'object_name') {
  759. $row['data'][] = drupal_render($element[$type_id][$fieldname]) . drupal_render($element[$type_id]['object_is_current']);
  760. }
  761. else {
  762. $row['data'][] = drupal_render($element[$type_id][$fieldname]);
  763. }
  764. }
  765. $rows[] = $row;
  766. }
  767. else {
  768. foreach (element_children($element[$type_id]) as $rank) {
  769. $row = array();
  770. $row['data'] = array();
  771. $row['class'] = $element[$type_id][$rank]['#attributes']['class'];
  772. foreach ($header as $fieldname => $title) {
  773. $row['data'][] = drupal_render($element[$type_id][$rank][$fieldname]);
  774. }
  775. $rows[] = $row;
  776. }
  777. }
  778. }
  779. return theme('table', array(
  780. 'header' => $header,
  781. 'rows' => $rows,
  782. 'sticky' => FALSE
  783. ));
  784. }
  785. /**
  786. * This function is used in a hook_insert, hook_update for a node form
  787. * when the relationships form has been added to the form. It retrieves all of the relationships
  788. * and returns them in an array of the format:
  789. *
  790. * $relationships[<type_id>][<rank>] = array(
  791. * 'subject_id' => <subject_id>,
  792. * 'object_id' => <object_id>,
  793. * );
  794. *
  795. * This array can then be used for inserting or updating relationships manually
  796. *
  797. * @param $node
  798. *
  799. * @return
  800. * A relationship array
  801. *
  802. * @ingroup tripal_chado_node_api
  803. */
  804. function chado_retrieve_node_form_relationships($node) {
  805. $rels = array();
  806. if (isset($node->relationship_table)) {
  807. foreach ($node->relationship_table as $type_id => $elements) {
  808. if ($type_id != 'new' AND $type_id != 'details') {
  809. foreach ($elements as $rank => $relationships) {
  810. $rels[$type_id][$rank]['subject_id'] = $relationships['subject_id'];
  811. $rels[$type_id][$rank]['object_id'] = $relationships['object_id'];
  812. }
  813. }
  814. }
  815. }
  816. return $rels;
  817. }
  818. /**
  819. * This function is used in hook_insert or hook_update and handles inserting of
  820. * relationships between the current nodetype and other memebers of the same nodetype
  821. *
  822. * @param $node
  823. * The node passed into hook_insert & hook_update
  824. * @param $details
  825. * - relationship_table: the name of the _relationship linking table (ie: feature_relationship)
  826. * - foreignkey_value: the value of the foreign key (ie: 445, if there exists a feature where feature_id=445)
  827. * @param $retrieved_relationships
  828. * An array of relationships from chado_retrieve_node_form_relationships($node). This
  829. * can be used if you need special handling for some of the relationships.
  830. *
  831. * @ingroup tripal_chado_node_api
  832. */
  833. function chado_update_node_form_relationships($node, $details, $retrieved_relationships = FALSE) {
  834. $relationship_table = $details['relationship_table'];
  835. $current_id = $details['foreignkey_value'];
  836. if (isset($node->relationship_table) AND ($current_id > 0)) {
  837. // determine whether there is a rank in this relationship table
  838. $form_details = unserialize($node->relationship_table['details']);
  839. $has_rank = $form_details['table_has_rank'];
  840. // First remove existing relationships links
  841. chado_delete_record(
  842. $relationship_table,
  843. array($form_details['subject_field_name'] => $current_id)
  844. );
  845. chado_delete_record(
  846. $relationship_table,
  847. array($form_details['object_field_name'] => $current_id)
  848. );
  849. // Add back in relationships as needed
  850. if ($retrieved_relationships) {
  851. $relationships = $retrieved_relationships;
  852. }
  853. else {
  854. $relationships = chado_retrieve_node_form_relationships($node);
  855. }
  856. foreach ($relationships as $type_id => $ranks) {
  857. foreach ($ranks as $rank => $element) {
  858. $values = array(
  859. $form_details['subject_field_name'] => $element['subject_id'],
  860. 'type_id' => $type_id,
  861. $form_details['object_field_name'] => $element['object_id']
  862. );
  863. // Set the current id if not already
  864. // this is usually only necessary in an insert
  865. if (empty($values[$form_details['subject_field_name']])) {
  866. $values[$form_details['subject_field_name']] = $current_id;
  867. }
  868. if (empty($values[$form_details['object_field_name']])) {
  869. $values[$form_details['object_field_name']] = $current_id;
  870. }
  871. if ($has_rank) {
  872. // Ensure that the rank is Set & Current
  873. $rank_select = chado_get_table_max_rank(
  874. $relationship_table,
  875. array(
  876. $form_details['subject_field_name'] => $values['subject_id'],
  877. 'type_id' => $values['type_id'],
  878. $form_details['object_field_name'] => $values['object_id'],
  879. )
  880. );
  881. $values['rank'] = $rank_select + 1;
  882. }
  883. // add relationship
  884. $success_link = chado_insert_record(
  885. $relationship_table,
  886. $values
  887. );
  888. }
  889. }
  890. }
  891. }
  892. /**
  893. * Handles autocomplete for subject & object id
  894. *
  895. * @param $string
  896. * The part of the string already typed in the textfield
  897. *
  898. * @ingroup tripal_core
  899. */
  900. function chado_add_node_form_relationships_name_to_id_callback($base_table, $name_field, $string) {
  901. $matches = array();
  902. $base_key = $base_table.'_id';
  903. $query = db_select('chado.'.$base_table, 'b')
  904. ->fields('b', array($base_key, $name_field))
  905. ->condition($name_field, '%' . db_like($string) . '%', 'LIKE');
  906. $result = $query->execute();
  907. // save the query to matches
  908. foreach ($result as $row) {
  909. if (strlen($row->{$name_field}) > 50) {
  910. $key = '('.$row->{$base_key}.') ' . substr($row->{$name_field}, 0, 50) . '...';
  911. }
  912. else {
  913. $key = '('.$row->{$base_key}.') ' . $row->{$name_field};
  914. }
  915. $matches[$key] = check_plain($row->{$name_field});
  916. }
  917. // return for JS
  918. drupal_json_output($matches);
  919. }