tripal_core.chado_nodes.relationships.api.inc 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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 property 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('tcprops_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('tcprops_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('tcprops_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('tcprops_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. $form_state['rebuild'] = TRUE;
  159. // Set Defaults for optional fields
  160. $details['fieldset_title'] = (isset($details['fieldset_title'])) ? $details['fieldset_title'] : 'Relationships';
  161. $details['additional_instructions'] = (isset($details['additional_instructions'])) ? $details['additional_instructions'] : '';
  162. $details['nodetype_plural'] = (isset($details['nodetype_plural'])) ? $details['nodetype_plural'] : $details['nodetype'] . 's';
  163. $details['base_name_field'] = (isset($details['base_name_field'])) ? $details['base_name_field'] : 'uniquename';
  164. $details['subject_field_name'] = (isset($details['subject_field_name'])) ? $details['subject_field_name'] : 'subject_id';
  165. $details['object_field_name'] = (isset($details['object_field_name'])) ? $details['object_field_name'] : 'object_id';
  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 Property 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 Property';
  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. $prop_types = chado_query($sql, array(':cv_name' => $details['cv_name']));
  188. while ($prop = $prop_types->fetchObject()) {
  189. $type_options[$prop->cvterm_id] = $prop->name;
  190. $details['cv_id'] = $prop->cv_id;
  191. }
  192. }
  193. elseif (isset($details['cv_id'])) {
  194. $type_options = array();
  195. $type_options[] = 'Select a Property';
  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. $prop_types = chado_query($sql, array(':cv_id' => $details['cv_id']));
  206. while ($prop = $prop_types->fetchObject()) {
  207. $type_options[$prop->cvterm_id] = $prop->name;
  208. $details['cv_name'] = $prop->cv_name;
  209. }
  210. }
  211. }
  212. // Tell tripal administrators how to add terms to the property types drop down.
  213. if (empty($type_options)) {
  214. $tripal_message = tripal_set_message(
  215. t('There are currently no property types! To add additional properties 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 properties 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. $form['relationships'] = array(
  241. '#type' => 'fieldset',
  242. '#title' => t($details['fieldset_title']),
  243. '#prefix' => "<div id='relationships-fieldset'>",
  244. '#suffix' => '</div>',
  245. '#weight' => 10
  246. );
  247. $form['relationships']['descrip'] = array(
  248. '#type' => 'item',
  249. '#markup' => t('You may add relationships between this %nodetype and other
  250. %nodetype_plural by entering the details below. You may add
  251. as many relationships as desired by clicking the add button on the right. To
  252. remove a relationship, click the remove button. ' . $details['additional_instructions'],
  253. array('%nodetype' => $details['nodetype'], '%nodetype_plural' => $details['nodetype_plural'])),
  254. );
  255. $form['relationships']['admin_message'] = array(
  256. '#type' => 'markup',
  257. '#markup' => $tripal_message
  258. );
  259. // this form element is a tree, so that we don't puke all of the values into then node variable
  260. // it is set as a tree, and keeps them in the $form_state['values']['relationship_table'] heading.
  261. $form['relationships']['relationship_table'] = array(
  262. '#type' => 'markup',
  263. '#tree' => TRUE,
  264. '#prefix' => '<div id="tripal-generic-edit-relationships-table">',
  265. '#suffix' => '</div>',
  266. '#theme' => 'chado_node_relationships_form_table'
  267. );
  268. // Add defaults into form_state to be used elsewhere
  269. $form['relationships']['relationship_table']['details'] = array(
  270. '#type' => 'hidden',
  271. '#value' => serialize($details)
  272. );
  273. // Add relationships already attached to the node
  274. //---------------------------------------------
  275. /* Relationships can come to us in two ways:
  276. *
  277. * 1) In the form state in the $form_state['chado_relationships']. Data is in this field
  278. * when an AJAX call updates the form state or a validation error.
  279. *
  280. * 2) Directly from the database if the record already has _relationships associated. This
  281. * data is only used the first time the form is loaded. On AJAX calls or validation
  282. * errors the fields on the form are populated from the $form_state['chado_relationships']
  283. * entry.
  284. */
  285. if (isset($form_state['chado_relationships'])) {
  286. $existing_rels = $form_state['chado_relationships'];
  287. }
  288. else {
  289. $existing_rels = chado_query(
  290. "SELECT
  291. rel.*,
  292. rel.".$details['subject_field_name']." as subject_id,
  293. rel.".$details['object_field_name']." as object_id,
  294. base1.".$details['base_name_field']." as object_name,
  295. base2.".$details['base_name_field']." as subject_name,
  296. cvterm.name as type_name
  297. FROM {".$details['relationship_table']."} rel
  298. LEFT JOIN {".$details['base_table']."} base1 ON base1.".$details['base_foreign_key']." = rel.".$details['object_field_name']."
  299. LEFT JOIN {".$details['base_table']."} base2 ON base2.".$details['base_foreign_key']." = rel.".$details['subject_field_name']."
  300. LEFT JOIN {cvterm} cvterm ON cvterm.cvterm_id = rel.type_id
  301. WHERE rel.".$details['object_field_name']." = :base_key_value
  302. OR rel.".$details['subject_field_name']." = :base_key_value",
  303. array(':base_key_value' => $details['base_key_value'])
  304. );
  305. }
  306. /* The format of the $existing_rels' array is either:
  307. *
  308. * From the chado_relationships array:
  309. * $form_state['chado_relationships'] = array(
  310. * '[type_id]-[rank]' => array(
  311. * 'object_id' => [the _relationship.object_id value],
  312. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  313. * 'subject_id' => [the _relationship.subject_id value],
  314. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  315. * 'type_id' => [the _relationship.type_id value],
  316. * 'type_name' => [the cvterm.name value linked on type_id],
  317. * 'rank' => [the _relationship.rank value],
  318. * ),
  319. * );
  320. *
  321. * OR
  322. * Populated from the database:
  323. * $existing_rels = array(
  324. * 0 => array(
  325. * 'relationship_id' => [the _relationship.relationship_id value],
  326. * 'object_id' => [the _relationship.object_id value],
  327. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  328. * 'subject_id' => [the _relationship.subject_id value],
  329. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  330. * 'type_id' => [the _relationship.type_id value],
  331. * 'type_name' => [the cvterm.name value linked on type_id],
  332. * 'rank' => [the _relationship.rank value],
  333. * ),
  334. * );
  335. *
  336. * NOTE: The main difference is the key
  337. *
  338. * Loop on the array elements of the $existing_rels array and add
  339. * an element to the form for each one.
  340. */
  341. foreach ($existing_rels as $relationship) {
  342. if (array_key_exists($relationship->type_id, $type_options)) {
  343. // We're using a unique id as a rank placeholder to ensure all relationships are shown
  344. // We can't use the actual rank b/c there can be two relationships with the same type
  345. // and rank as long as the subject_id and object_id are switched. For example, you can
  346. // have Fred is_paternal_parent_of Max and Max is_paternal_parent_of Lui (both rank=0)
  347. $rank = uniqid();
  348. $form['relationships']['relationship_table'][$relationship->type_id]['#type'] = 'markup';
  349. $form['relationships']['relationship_table'][$relationship->type_id]['#type'] = '';
  350. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['#type'] = 'markup';
  351. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['#value'] = '';
  352. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['object_id'] = array(
  353. '#type' => 'hidden',
  354. '#value' => $relationship->object_id
  355. );
  356. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['subject_id'] = array(
  357. '#type' => 'hidden',
  358. '#value' => $relationship->subject_id
  359. );
  360. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['type_id'] = array(
  361. '#type' => 'hidden',
  362. '#value' => $relationship->type_id
  363. );
  364. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['object_name'] = array(
  365. '#type' => 'markup',
  366. '#markup' => $relationship->object_name
  367. );
  368. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['type_name'] = array(
  369. '#type' => 'markup',
  370. '#markup' => $relationship->type_name
  371. );
  372. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['subject_name'] = array(
  373. '#type' => 'markup',
  374. '#markup' => $relationship->subject_name
  375. );
  376. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['rank'] = array(
  377. '#type' => 'markup',
  378. '#markup' => $rank
  379. );
  380. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['rel_action'] = array(
  381. '#type' => 'submit',
  382. '#value' => t('Remove'),
  383. '#name' => "rel_remove-".$relationship->type_id.'-'.$rank,
  384. '#ajax' => array(
  385. 'callback' => 'chado_add_node_form_relationships_ajax_update',
  386. 'wrapper' => 'tripal-generic-edit-relationships-table',
  387. 'effect' => 'fade',
  388. 'method' => 'replace',
  389. 'prevent' => 'click'
  390. ),
  391. // When this button is clicked, the form will be validated and submitted.
  392. // Therefore, we set custom submit and validate functions to override the
  393. // default node form submit. In the validate function we validate only the
  394. // relationship fields and in the submit we remove the indicated relationship
  395. // from the chado_relationships array. In order to keep validate errors
  396. // from the node form validate and Drupal required errors for non-relationship fields
  397. // preventing the user from removing relationships we set the #limit_validation_errors below
  398. '#validate' => array('chado_add_node_form_relationships_form_remove_button_validate'),
  399. '#submit' => array('chado_add_node_form_relationships_remove_button_submit'),
  400. // Limit the validation of the form upon clicking this button to the relationship_table tree
  401. // No other fields will be validated (ie: no fields from the main form or any other api
  402. // added form).
  403. '#limit_validation_errors' => array(
  404. array('relationship_table') // Validate all fields within $form_state['values']['relationship_table']
  405. )
  406. );
  407. }
  408. }
  409. $form['relationships']['relationship_table']['new']['object_name'] = array(
  410. '#type' => 'textfield',
  411. '#autocomplete_path' => 'tripal_ajax/relationship_nodeform/' . $details['base_table'] . '/' . $details['base_name_field'].'/name_to_id'
  412. );
  413. $form['relationships']['relationship_table']['new']['object_is_current'] = array(
  414. '#type' => 'checkbox',
  415. '#title' => t('Current '.$details['nodetype']),
  416. );
  417. $form['relationships']['relationship_table']['new']['type_name'] = array(
  418. '#type' => 'select',
  419. '#options' => $type_options,
  420. );
  421. $form['relationships']['relationship_table']['new']['subject_name'] = array(
  422. '#type' => 'textfield',
  423. '#autocomplete_path' => 'tripal_ajax/relationship_nodeform/' . $details['base_table'] . '/' . $details['base_name_field'].'/name_to_id'
  424. );
  425. $form['relationships']['relationship_table']['new']['subject_is_current'] = array(
  426. '#type' => 'checkbox',
  427. '#title' => t('Current ' . $details['nodetype']),
  428. );
  429. $form['relationships']['relationship_table']['new']['rank'] = array(
  430. '#type' => 'markup',
  431. '#markup' => ''
  432. );
  433. $form['relationships']['relationship_table']['new']['rel_action'] = array(
  434. '#type' => 'submit',
  435. '#value' => t('Add'),
  436. '#name' => 'rel_add',
  437. '#ajax' => array(
  438. 'callback' => 'chado_add_node_form_relationships_ajax_update',
  439. 'wrapper' => 'tripal-generic-edit-relationships-table',
  440. 'effect' => 'fade',
  441. 'method' => 'replace',
  442. 'prevent' => 'click'
  443. ),
  444. // When this button is clicked, the form will be validated and submitted.
  445. // Therefore, we set custom submit and validate functions to override the
  446. // default node form submit. In the validate function we validate only the
  447. // relationship fields and in the submit we add them to the chado_relationships
  448. // array. In order to keep validate errors from the node form validate and Drupal
  449. // required errors for non-relationship fields preventing the user from adding relationships we
  450. // set the #limit_validation_errors below
  451. '#validate' => array('chado_add_node_form_relationships_add_button_validate'),
  452. '#submit' => array('chado_add_node_form_relationships_add_button_submit'),
  453. // Limit the validation of the form upon clicking this button to the relationship_table tree
  454. // No other fields will be validated (ie: no fields from the main form or any other api
  455. // added form).
  456. '#limit_validation_errors' => array(
  457. array('relationship_table') // Validate all fields within $form_state['values']['relationship_table']
  458. )
  459. );
  460. }
  461. /**
  462. * Validate the user input for creating a new relationship
  463. * Called by the add button in chado_add_node_form_relationships
  464. *
  465. * @ingroup tripal_core
  466. */
  467. function chado_add_node_form_relationships_add_button_validate($form, &$form_state) {
  468. $details = unserialize($form_state['values']['relationship_table']['details']);
  469. // First deal with autocomplete fields
  470. // extract the base_id assuming '(###) NAME FIELD'
  471. if (!empty($form_state['values']['relationship_table']['new']['subject_name'])) {
  472. if (preg_match('/\((\d+)\) .*/', $form_state['values']['relationship_table']['new']['subject_name'], $matches)) {
  473. $form_state['values']['relationship_table']['new']['subject_id'] = $matches[1];
  474. }
  475. else {
  476. form_set_error('subject_name', 'You need to select the subject from the autocomplete drop-down');
  477. }
  478. }
  479. if (!empty($form_state['values']['relationship_table']['new']['object_name'])) {
  480. if (preg_match('/\((\d+)\) .*/', $form_state['values']['relationship_table']['new']['object_name'], $matches)) {
  481. $form_state['values']['relationship_table']['new']['object_id'] = $matches[1];
  482. }
  483. else {
  484. form_set_error('object_name', 'You need to select the subject from the autocomplete drop-down');
  485. }
  486. }
  487. // At least one of the participants must be the current node
  488. if (!($form_state['values']['relationship_table']['new']['subject_is_current'] OR $form_state['values']['relationship_table']['new']['object_is_current'])) {
  489. // If the checkbox isn't set then check to see if either has the same uniquename as the node
  490. if ($form_state['values']['relationship_table']['new']['subject_name'] == $form_state['values']['uniquename']) {
  491. $form_state['values']['relationship_table']['new']['subject_is_current'] = 1;
  492. form_set_error('subject_is_current', 'To set the current '.$details['nodetype'].', select the
  493. checkbox. You entered the unique name of the current '.$details['nodetype'].' as the subject,
  494. is this what you meant to do?');
  495. }
  496. elseif ($form_state['values']['relationship_table']['new']['subject_name'] == $form_state['values']['uniquename']) {
  497. $form_state['values']['relationship_table']['new']['object_is_current'] = 1;
  498. form_set_error('subject_is_current', 'To set the current '.$details['nodetype'].', select the
  499. checkbox. You entered the unique name of the current '.$details['nodetype'].' as the subject,
  500. is this what you meant to do?');
  501. }
  502. else {
  503. form_set_error('object_is_current', 'At least one member of the relationship must be
  504. the current '.$details['nodetype'].'. This is specified by checking the "Current '.$details['nodetype'].'"
  505. checkbox for either the subject or object.');
  506. }
  507. }
  508. // The non-current uniquename must be exist in the base table (subject)
  509. if (!($form_state['values']['relationship_table']['new']['subject_is_current'])) {
  510. $result = chado_select_record(
  511. $details['base_table'],
  512. array($details['base_name_field']),
  513. array($details['base_foreign_key'] => $form_state['values']['relationship_table']['new']['subject_id'])
  514. );
  515. if (!isset($result[0])) {
  516. form_set_error('subject_name', 'The subject must be the unique name of an
  517. existing '.$details['nodetype'].' unless the "Current '.$details['nodetype'].'" checkbox is selected');
  518. }
  519. else {
  520. $form_state['values']['relationship_table']['new']['subject_name'] = $result[0]->{$details['base_name_field']};
  521. }
  522. }
  523. // The non-current uniquename must exist in the base table (object)
  524. if (!($form_state['values']['relationship_table']['new']['object_is_current'])) {
  525. $result = chado_select_record(
  526. $details['base_table'],
  527. array($details['base_name_field']),
  528. array($details['base_foreign_key'] => $form_state['values']['relationship_table']['new']['object_id'])
  529. );
  530. if (!isset($result[0])) {
  531. form_set_error('object_name', 'The object must be the unique name of an
  532. existing '.$details['nodetype'].' unless the "Current '.$details['nodetype'].'" checkbox is selected');
  533. }
  534. else {
  535. $form_state['values']['relationship_table']['new']['object_name'] = $result[0]->{$details['base_name_field']};
  536. }
  537. }
  538. // The type must be a valid cvterm
  539. if ($form_state['values']['relationship_table']['new']['type_name']) {
  540. $form_state['values']['relationship_table']['new']['type_id'] = $form_state['values']['relationship_table']['new']['type_name'];
  541. $result = chado_select_record(
  542. 'cvterm',
  543. array('name'),
  544. array('cvterm_id' => $form_state['values']['relationship_table']['new']['type_id'])
  545. );
  546. if (!isset($result[0])) {
  547. form_set_error('type_id', 'The select type is not a valid controlled vocabulary term.');
  548. }
  549. else {
  550. $form_state['values']['relationship_table']['new']['type_name'] = $result[0]->name;
  551. }
  552. }
  553. else {
  554. form_set_error('type_id', 'Please select a type of relationship');
  555. }
  556. }
  557. /**
  558. * Called by the add button in chado_add_node_form_relationships
  559. *
  560. * Create an array of additional relationships in the form state. This array will then be
  561. * used to rebuild the form in subsequent builds
  562. *
  563. * @ingroup tripal_core
  564. */
  565. function chado_add_node_form_relationships_add_button_submit(&$form, &$form_state) {
  566. $details = unserialize($form_state['values']['relationship_table']['details']);
  567. // if the chado_relationships array is not set then this is the first time modifying the
  568. // relationship table. this means we need to include all the relationships from the db
  569. if (!isset($form_state['chado_relationships'])) {
  570. chado_add_node_form_relationships_create_relationship_formstate_array($form, $form_state);
  571. }
  572. $name = (isset($form_state['node']->{$details['base_table']}->uniquename)) ? $form_state['node']->{$details['base_table']}->uniquename : 'CURRENT';
  573. // get details for the new relationship
  574. if ($form_state['values']['relationship_table']['new']['subject_is_current']) {
  575. $relationship = array(
  576. 'type_id' => $form_state['values']['relationship_table']['new']['type_id'],
  577. 'type_name' => $form_state['values']['relationship_table']['new']['type_name'],
  578. 'object_id' => $form_state['values']['relationship_table']['new']['object_id'],
  579. 'object_name' => $form_state['values']['relationship_table']['new']['object_name'],
  580. 'subject_id' => $form_state['node']->{$details['base_table']}->{$details['base_foreign_key']},
  581. 'subject_name' => $name,
  582. 'rank' => uniqid(),
  583. );
  584. // we don't want the new element to pick up the values from the previous element so wipe them out
  585. unset($form_state['input']['relationship_table']['new']['object_id']);
  586. unset($form_state['input']['relationship_table']['new']['object_name']);
  587. }
  588. else {
  589. $relationship = array(
  590. 'type_id' => $form_state['values']['relationship_table']['new']['type_id'],
  591. 'type_name' => $form_state['values']['relationship_table']['new']['type_name'],
  592. 'object_id' => $form_state['node']->{$details['base_table']}->{$details['base_foreign_key']},
  593. 'object_name' => $name,
  594. 'subject_id' => $form_state['values']['relationship_table']['new']['subject_id'],
  595. 'subject_name' => $form_state['values']['relationship_table']['new']['subject_name'],
  596. 'rank' => uniqid(),
  597. );
  598. // we don't want the new element to pick up the values from the previous element so wipe them out
  599. unset($form_state['input']['relationship_table']['new']['subject_id']);
  600. unset($form_state['input']['relationship_table']['new']['subject_name']);
  601. }
  602. $key = $relationship['type_id'] . '-' . $relationship['rank'];
  603. $form_state['chado_relationships'][$key] = (object) $relationship;
  604. // we don't want the new element to pick up the values from the previous element so wipe them out
  605. unset($form_state['input']['relationship_table']['new']['type_id']);
  606. unset($form_state['input']['relationship_table']['new']['type_name']);
  607. $form_state['rebuild'] = TRUE;
  608. }
  609. /**
  610. * There is no user input for the remove buttons so there is no need to validate
  611. * However, both a submit & validate need to be specified so this is just a placeholder
  612. *
  613. * Called by the many remove buttons in chado_add_node_form_relationships
  614. *
  615. * @ingroup tripal_core
  616. */
  617. function chado_add_node_form_relationships_form_remove_button_validate($form, $form_state) {
  618. // No Validation needed for remove
  619. }
  620. /**
  621. * Remove the correct relationship from the form
  622. * Called by the many remove buttons in chado_add_node_form_relationships
  623. *
  624. * @ingroup tripal_core
  625. */
  626. function chado_add_node_form_relationships_remove_button_submit(&$form, &$form_state) {
  627. // if the chado_relationships array is not set then this is the first time modifying the
  628. // relationship table. this means we need to include all the relationships from the db
  629. if (!isset($form_state['chado_relationships'])) {
  630. chado_add_node_form_relationships_create_relationship_formstate_array($form, $form_state);
  631. }
  632. // remove the specified relationship from the form relationship table
  633. if(preg_match('/rel_remove-([^-]+-[^-]+)/',$form_state['triggering_element']['#name'],$match)) {
  634. $key = $match[1];
  635. if (array_key_exists($key, $form_state['chado_relationships'])) {
  636. unset($form_state['chado_relationships'][$key]);
  637. }
  638. }
  639. $form_state['rebuild'] = TRUE;
  640. }
  641. /**
  642. * Ajax function which returns the section of the form to be re-rendered
  643. *
  644. * @ingroup tripal_core
  645. */
  646. function chado_add_node_form_relationships_ajax_update($form, $form_state) {
  647. return $form['relationships']['relationship_table'];
  648. }
  649. /**
  650. * Creates an array in form_state containing the existing relationships. This array is
  651. * then modified by the add/remove buttons and used as a source for rebuilding the form.
  652. *
  653. * $form_state['chado_relationships'] = array(
  654. * '[type_id]-[rank]' => array(
  655. * 'object_id' => [the _relationship.object_id value],
  656. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  657. * 'subject_id' => [the _relationship.subject_id value],
  658. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  659. * 'type_id' => [the _relationship.type_id value],
  660. * 'type_name' => [the cvterm.name value linked on type_id],
  661. * 'rank' => [the _relationship.rank value],
  662. * ),
  663. * );
  664. *
  665. * @ingroup tripal_core
  666. */
  667. function chado_add_node_form_relationships_create_relationship_formstate_array($form, &$form_state) {
  668. $form_state['chado_relationships'] = array();
  669. foreach (element_children($form['relationships']['relationship_table']) as $type_id) {
  670. if ($type_id != 'new') {
  671. foreach (element_children($form['relationships']['relationship_table'][$type_id]) as $rank) {
  672. $element = $form['relationships']['relationship_table'][$type_id][$rank];
  673. $rel = array(
  674. 'type_id' => $element['type_id']['#value'],
  675. 'object_id' => $element['object_id']['#value'],
  676. 'subject_id' => $element['subject_id']['#value'],
  677. 'type_name' => $element['type_name']['#markup'],
  678. 'object_name' => $element['object_name']['#markup'],
  679. 'subject_name' => $element['subject_name']['#markup'],
  680. 'rank' => $element['rank']['#markup']
  681. );
  682. $key = $rel['type_id'] . '-' . $rel['rank'];
  683. $form_state['chado_relationships'][$key] = (object) $rel;
  684. }
  685. }
  686. }
  687. }
  688. /**
  689. * Function to theme the add/remove relationships form into a table
  690. *
  691. * @ingroup tripal_chado_node_api
  692. */
  693. function theme_chado_add_node_form_relationships_table($variables) {
  694. $element = $variables['element'];
  695. $details = unserialize($element['details']['#value']);
  696. $header = array(
  697. 'subject_name' => t('Subject ' . $details['base_name_field']),
  698. 'type_name' => t('Type'),
  699. 'object_name' => t('Object ' . $details['base_name_field']),
  700. 'rel_action' => t('Action')
  701. );
  702. $rows = array();
  703. foreach (element_children($element) as $type_id) {
  704. if ($type_id == 'new') {
  705. $row = array();
  706. $row['data'] = array();
  707. foreach ($header as $fieldname => $title) {
  708. if ($fieldname == 'subject_name') {
  709. $row['data'][] = drupal_render($element[$type_id][$fieldname]) . drupal_render($element[$type_id]['subject_is_current']);
  710. }
  711. elseif ($fieldname == 'object_name') {
  712. $row['data'][] = drupal_render($element[$type_id][$fieldname]) . drupal_render($element[$type_id]['object_is_current']);
  713. }
  714. else {
  715. $row['data'][] = drupal_render($element[$type_id][$fieldname]);
  716. }
  717. }
  718. $rows[] = $row;
  719. }
  720. else {
  721. foreach (element_children($element[$type_id]) as $rank) {
  722. $row = array();
  723. $row['data'] = array();
  724. foreach ($header as $fieldname => $title) {
  725. $row['data'][] = drupal_render($element[$type_id][$rank][$fieldname]);
  726. }
  727. $rows[] = $row;
  728. }
  729. }
  730. }
  731. return theme('table', array(
  732. 'header' => $header,
  733. 'rows' => $rows
  734. ));
  735. }
  736. /**
  737. * This function is used in a hook_insert, hook_update for a node form
  738. * when the relationships form has been added to the form. It retrieves all of the relationships
  739. * and returns them in an array of the format:
  740. *
  741. * $relationships[<type_id>][<rank>] = array(
  742. * 'subject_id' => <subject_id>,
  743. * 'object_id' => <object_id>,
  744. * );
  745. *
  746. * This array can then be used for inserting or updating relationships manually
  747. *
  748. * @param $node
  749. *
  750. * @return
  751. * A relationship array
  752. *
  753. * @ingroup tripal_chado_node_api
  754. */
  755. function chado_retrieve_node_form_relationships($node) {
  756. $rels = array();
  757. if (isset($node->relationship_table)) {
  758. foreach ($node->relationship_table as $type_id => $elements) {
  759. if ($type_id != 'new' AND $type_id != 'details') {
  760. foreach ($elements as $rank => $relationships) {
  761. $rels[$type_id][$rank]['subject_id'] = $relationships['subject_id'];
  762. $rels[$type_id][$rank]['object_id'] = $relationships['object_id'];
  763. }
  764. }
  765. }
  766. }
  767. return $rels;
  768. }
  769. /**
  770. * This function is used in hook_insert or hook_update and handles inserting of
  771. * relationships between the current nodetype and other memebers of the same nodetype
  772. *
  773. * @param $node
  774. * The node passed into hook_insert & hook_update
  775. * @param $details
  776. * - relationship_table: the name of the _relationship linking table (ie: feature_relationship)
  777. * - foreignkey_value: the value of the foreign key (ie: 445, if there exists a feature where feature_id=445)
  778. * @param $retrieved_relationships
  779. * An array of relationships from chado_retrieve_node_form_relationships($node). This
  780. * can be used if you need special handling for some of the relationships.
  781. *
  782. * @ingroup tripal_chado_node_api
  783. */
  784. function chado_update_node_form_relationships($node, $details, $retrieved_relationships = FALSE) {
  785. $relationship_table = $details['relationship_table'];
  786. $current_id = $details['foreignkey_value'];
  787. if (isset($node->relationship_table) AND ($current_id > 0)) {
  788. // determine whether there is a rank in this relationship table
  789. $form_details = unserialize($node->relationship_table['details']);
  790. $has_rank = $form_details['table_has_rank'];
  791. // First remove existing relationships links
  792. chado_delete_record(
  793. $relationship_table,
  794. array($form_details['subject_field_name'] => $current_id)
  795. );
  796. chado_delete_record(
  797. $relationship_table,
  798. array($form_details['object_field_name'] => $current_id)
  799. );
  800. // Add back in relationships as needed
  801. if ($retrieved_relationships) {
  802. $relationships = $retrieved_relationships;
  803. }
  804. else {
  805. $relationships = chado_retrieve_node_form_relationships($node);
  806. }
  807. foreach ($relationships as $type_id => $ranks) {
  808. foreach ($ranks as $rank => $element) {
  809. $values = array(
  810. $form_details['subject_field_name'] => $element['subject_id'],
  811. 'type_id' => $type_id,
  812. $form_details['object_field_name'] => $element['object_id']
  813. );
  814. // Set the current id if not already
  815. // this is usually only necessary in an insert
  816. if (empty($values[$form_details['subject_field_name']])) {
  817. $values[$form_details['subject_field_name']] = $current_id;
  818. }
  819. if (empty($values[$form_details['object_field_name']])) {
  820. $values[$form_details['object_field_name']] = $current_id;
  821. }
  822. if ($has_rank) {
  823. // Ensure that the rank is Set & Current
  824. $rank_select = chado_get_table_max_rank(
  825. $relationship_table,
  826. array(
  827. $form_details['subject_field_name'] => $values['subject_id'],
  828. 'type_id' => $values['type_id'],
  829. $form_details['object_field_name'] => $values['object_id'],
  830. )
  831. );
  832. $values['rank'] = $rank_select + 1;
  833. }
  834. // add relationship
  835. $success_link = chado_insert_record(
  836. $relationship_table,
  837. $values
  838. );
  839. }
  840. }
  841. }
  842. }
  843. /**
  844. * Handles autocomplete for subject & object id
  845. *
  846. * @param $string
  847. * The part of the string already typed in the textfield
  848. *
  849. * @ingroup tripal_core
  850. */
  851. function chado_add_node_form_relationships_name_to_id_callback($base_table, $name_field, $string) {
  852. $matches = array();
  853. $base_key = $base_table.'_id';
  854. $result = db_select('chado.'.$base_table, 'b')
  855. ->fields('b', array($base_key, $name_field))
  856. ->condition($name_field, '%' . db_like($string) . '%', 'LIKE')
  857. ->execute();
  858. // save the query to matches
  859. foreach ($result as $row) {
  860. $key = '('.$row->{$base_key}.') '.substr($row->{$name_field},0,50) . '...';
  861. $matches[$key] = check_plain($row->{$name_field});
  862. }
  863. // return for JS
  864. drupal_json_output($matches);
  865. }