tripal_core.chado_nodes.relationships.api.inc 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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. $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['relationship_table']."_id as relationship_id,
  293. rel.".$details['subject_field_name']." as subject_id,
  294. rel.".$details['object_field_name']." as object_id,
  295. base1.".$details['base_name_field']." as object_name,
  296. base2.".$details['base_name_field']." as subject_name,
  297. cvterm.name as type_name
  298. FROM {".$details['relationship_table']."} rel
  299. LEFT JOIN {".$details['base_table']."} base1 ON base1.".$details['base_foreign_key']." = rel.".$details['object_field_name']."
  300. LEFT JOIN {".$details['base_table']."} base2 ON base2.".$details['base_foreign_key']." = rel.".$details['subject_field_name']."
  301. LEFT JOIN {cvterm} cvterm ON cvterm.cvterm_id = rel.type_id
  302. WHERE rel.".$details['object_field_name']." = :base_key_value
  303. OR rel.".$details['subject_field_name']." = :base_key_value",
  304. array(':base_key_value' => $details['base_key_value'])
  305. );
  306. }
  307. /* The format of the $existing_rels' array is either:
  308. *
  309. * From the chado_relationships array:
  310. * $form_state['chado_relationships'] = array(
  311. * '[type_id]-[_relationship_id]' => array(
  312. * 'relationship_id' => [the _relationship._relationship_id value OR a temporary value if not yet saved to the database],
  313. * 'object_id' => [the _relationship.object_id value],
  314. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  315. * 'subject_id' => [the _relationship.subject_id value],
  316. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  317. * 'type_id' => [the _relationship.type_id value],
  318. * 'type_name' => [the cvterm.name value linked on type_id],
  319. * 'rank' => [the _relationship.rank value OR NULL if not yet saved to the database],
  320. * ),
  321. * );
  322. *
  323. * OR
  324. * Populated from the database:
  325. * $existing_rels = array(
  326. * 0 => array(
  327. * 'relationship_id' => [the _relationship._relationship_id value],
  328. * 'object_id' => [the _relationship.object_id value],
  329. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  330. * 'subject_id' => [the _relationship.subject_id value],
  331. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  332. * 'type_id' => [the _relationship.type_id value],
  333. * 'type_name' => [the cvterm.name value linked on type_id],
  334. * 'rank' => [the _relationship.rank value],
  335. * ),
  336. * );
  337. *
  338. * NOTE: The main difference is the key
  339. *
  340. * Loop on the array elements of the $existing_rels array and add
  341. * an element to the form for each one.
  342. */
  343. foreach ($existing_rels as $relationship) {
  344. if (array_key_exists($relationship->type_id, $type_options)) {
  345. $form['relationships']['relationship_table'][$relationship->type_id]['#type'] = 'markup';
  346. $form['relationships']['relationship_table'][$relationship->type_id]['#type'] = '';
  347. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['#type'] = 'markup';
  348. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['#value'] = '';
  349. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['relationship_id'] = array(
  350. '#type' => 'markup',
  351. '#markup' => $relationship->relationship_id
  352. );
  353. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['object_id'] = array(
  354. '#type' => 'hidden',
  355. '#value' => $relationship->object_id
  356. );
  357. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['subject_id'] = array(
  358. '#type' => 'hidden',
  359. '#value' => $relationship->subject_id
  360. );
  361. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['type_id'] = array(
  362. '#type' => 'hidden',
  363. '#value' => $relationship->type_id
  364. );
  365. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['object_name'] = array(
  366. '#type' => 'markup',
  367. '#markup' => $relationship->object_name
  368. );
  369. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['type_name'] = array(
  370. '#type' => 'markup',
  371. '#markup' => $relationship->type_name
  372. );
  373. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['subject_name'] = array(
  374. '#type' => 'markup',
  375. '#markup' => $relationship->subject_name
  376. );
  377. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['rank'] = array(
  378. '#type' => 'markup',
  379. '#markup' => (isset($relationship->rank)) ? $relationship->rank : NULL
  380. );
  381. $form['relationships']['relationship_table'][$relationship->type_id][$relationship->relationship_id]['rel_action'] = array(
  382. '#type' => 'submit',
  383. '#value' => t('Remove'),
  384. '#name' => "relationships_remove-".$relationship->type_id.'-'.$relationship->relationship_id,
  385. '#ajax' => array(
  386. 'callback' => 'chado_add_node_form_subtable_ajax_update',
  387. 'wrapper' => 'tripal-generic-edit-relationships-table',
  388. 'effect' => 'fade',
  389. 'method' => 'replace',
  390. 'prevent' => 'click'
  391. ),
  392. // When this button is clicked, the form will be validated and submitted.
  393. // Therefore, we set custom submit and validate functions to override the
  394. // default node form submit. In the validate function we validate only the
  395. // relationship fields and in the submit we remove the indicated relationship
  396. // from the chado_relationships array. In order to keep validate errors
  397. // from the node form validate and Drupal required errors for non-relationship fields
  398. // preventing the user from removing relationships we set the #limit_validation_errors below
  399. '#validate' => array('chado_add_node_form_subtables_remove_button_validate'),
  400. '#submit' => array('chado_add_node_form_subtables_remove_button_submit'),
  401. // Limit the validation of the form upon clicking this button to the relationship_table tree
  402. // No other fields will be validated (ie: no fields from the main form or any other api
  403. // added form).
  404. '#limit_validation_errors' => array(
  405. array('relationship_table') // Validate all fields within $form_state['values']['relationship_table']
  406. )
  407. );
  408. }
  409. }
  410. $form['relationships']['relationship_table']['new']['object_name'] = array(
  411. '#type' => 'textfield',
  412. '#autocomplete_path' => 'tripal_ajax/relationship_nodeform/' . $details['base_table'] . '/' . $details['base_name_field'].'/name_to_id'
  413. );
  414. $form['relationships']['relationship_table']['new']['object_is_current'] = array(
  415. '#type' => 'checkbox',
  416. '#title' => t('Current '.$details['nodetype']),
  417. );
  418. $form['relationships']['relationship_table']['new']['type_name'] = array(
  419. '#type' => 'select',
  420. '#options' => $type_options,
  421. );
  422. $form['relationships']['relationship_table']['new']['subject_name'] = array(
  423. '#type' => 'textfield',
  424. '#autocomplete_path' => 'tripal_ajax/relationship_nodeform/' . $details['base_table'] . '/' . $details['base_name_field'].'/name_to_id'
  425. );
  426. $form['relationships']['relationship_table']['new']['subject_is_current'] = array(
  427. '#type' => 'checkbox',
  428. '#title' => t('Current ' . $details['nodetype']),
  429. );
  430. $form['relationships']['relationship_table']['new']['rank'] = array(
  431. '#type' => 'markup',
  432. '#markup' => ''
  433. );
  434. $form['relationships']['relationship_table']['new']['rel_action'] = array(
  435. '#type' => 'submit',
  436. '#value' => t('Add'),
  437. '#name' => 'relationships-add',
  438. '#ajax' => array(
  439. 'callback' => 'chado_add_node_form_subtable_ajax_update',
  440. 'wrapper' => 'tripal-generic-edit-relationships-table',
  441. 'effect' => 'fade',
  442. 'method' => 'replace',
  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_subtables_add_button_validate'),
  452. '#submit' => array('chado_add_node_form_subtables_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') // Ensure relationship table results are not discarded.
  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('relationship_table][new][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('relationship_table][new][object_name', 'You need to select the object from the autocomplete drop-down');
  485. }
  486. }
  487. // NOTE: The only way to specify the current node is via checkbox. This is by
  488. // design since guessing if they meant the current node by name is a
  489. // chicken-egg problem due to the name field only being set to just the name
  490. // only happens once it has been determined which germplasm is the current
  491. // one. Furthermore, we can't use the primary key since this will not have
  492. // been set on insert.
  493. // At least one of the participants must be the current node.
  494. if (!($form_state['values']['relationship_table']['new']['subject_is_current'] OR $form_state['values']['relationship_table']['new']['object_is_current'])) {
  495. form_set_error('relationship_table][new][object_is_current', 'At least one member of the relationship must be
  496. the current '.$details['nodetype'].'. This is specified by checking the "Current '.$details['nodetype'].'"
  497. checkbox for either the subject or object.');
  498. }
  499. // Only one of the participants may be the current node.
  500. // We do not support circular relationships.
  501. if ($form_state['values']['relationship_table']['new']['subject_is_current']
  502. AND $form_state['values']['relationship_table']['new']['object_is_current']) {
  503. form_set_error('relationship_table][new][object_is_current', 'Only one member of the relationship may 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. // If it was determined current via checkbox, we need to ensure the name
  508. // provided actually matches the current node.
  509. if ($form_state['values']['relationship_table']['new']['subject_is_current']
  510. AND !empty($form_state['values']['relationship_table']['new']['subject_name'])
  511. AND $form_state['values']['relationship_table']['new']['subject_name'] != $form_state['values'][$details['form_element_name']]) {
  512. form_set_error('relationship_table][new][subject_name',
  513. 'The name you supplied for the current '.$details['nodetype'].' doesn\'t match the actual name
  514. of this '.$details['nodetype'].'. If you really meant the subject should be the current '.$details['nodetype'].',
  515. simply leave the textfield empty and re-add this relationship.');
  516. }
  517. if ($form_state['values']['relationship_table']['new']['object_is_current']
  518. AND !empty($form_state['values']['relationship_table']['new']['object_name'])
  519. AND $form_state['values']['relationship_table']['new']['object_name'] != $form_state['values'][$details['form_element_name']]) {
  520. form_set_error('relationship_table][new][object_name',
  521. 'The name you supplied for the current '.$details['nodetype'].' doesn\'t match the actual name
  522. of this '.$details['nodetype'].'. If you really meant the object should be the current '.$details['nodetype'].',
  523. simply leave the textfield empty and re-add this relationship.');
  524. }
  525. // The non-current uniquename must be exist in the base table (subject).
  526. if (!($form_state['values']['relationship_table']['new']['subject_is_current'])) {
  527. $result = chado_select_record(
  528. $details['base_table'],
  529. array($details['base_name_field']),
  530. array($details['base_foreign_key'] => $form_state['values']['relationship_table']['new']['subject_id'])
  531. );
  532. if (!isset($result[0])) {
  533. form_set_error('relationship_table][new][subject_name', 'The subject must be the unique name of an
  534. existing '.$details['nodetype'].' unless the "Current '.$details['nodetype'].'" checkbox is selected');
  535. }
  536. else {
  537. $form_state['values']['relationship_table']['new']['subject_name'] = $result[0]->{$details['base_name_field']};
  538. }
  539. }
  540. // The non-current uniquename must exist in the base table (object).
  541. if (!($form_state['values']['relationship_table']['new']['object_is_current'])) {
  542. $result = chado_select_record(
  543. $details['base_table'],
  544. array($details['base_name_field']),
  545. array($details['base_foreign_key'] => $form_state['values']['relationship_table']['new']['object_id'])
  546. );
  547. if (!isset($result[0])) {
  548. form_set_error('relationship_table][new][object_name', 'The object must be the unique name of an
  549. existing '.$details['nodetype'].' unless the "Current '.$details['nodetype'].'" checkbox is selected');
  550. }
  551. else {
  552. $form_state['values']['relationship_table']['new']['object_name'] = $result[0]->{$details['base_name_field']};
  553. }
  554. }
  555. // The type must be a valid cvterm.
  556. if ($form_state['values']['relationship_table']['new']['type_name']) {
  557. $form_state['values']['relationship_table']['new']['type_id'] = $form_state['values']['relationship_table']['new']['type_name'];
  558. $result = chado_select_record(
  559. 'cvterm',
  560. array('name'),
  561. array('cvterm_id' => $form_state['values']['relationship_table']['new']['type_id'])
  562. );
  563. if (!isset($result[0])) {
  564. form_set_error('relationship_table][new][type_id', 'The select type is not a valid controlled vocabulary term.');
  565. }
  566. else {
  567. $form_state['values']['relationship_table']['new']['type_name'] = $result[0]->name;
  568. }
  569. }
  570. else {
  571. form_set_error('relationship_table][new][type_id', 'Please select a type of relationship');
  572. }
  573. }
  574. /**
  575. * Called by the add button in chado_add_node_form_relationships
  576. *
  577. * Create an array of additional relationships in the form state. This array will then be
  578. * used to rebuild the form in subsequent builds
  579. *
  580. * @ingroup tripal_core
  581. */
  582. function chado_add_node_form_relationships_add_button_submit($form, &$form_state) {
  583. $details = unserialize($form_state['values']['relationship_table']['details']);
  584. // if the chado_relationships array is not set then this is the first time modifying the
  585. // relationship table. this means we need to include all the relationships from the db
  586. if (!isset($form_state['chado_relationships'])) {
  587. chado_add_node_form_relationships_create_relationship_formstate_array($form, $form_state);
  588. }
  589. $name = (isset($form_state['node']->{$details['base_table']}->uniquename)) ? $form_state['node']->{$details['base_table']}->uniquename : 'CURRENT';
  590. // get details for the new relationship
  591. if ($form_state['values']['relationship_table']['new']['subject_is_current']) {
  592. $relationship = array(
  593. 'type_id' => $form_state['values']['relationship_table']['new']['type_id'],
  594. 'type_name' => $form_state['values']['relationship_table']['new']['type_name'],
  595. 'object_id' => $form_state['values']['relationship_table']['new']['object_id'],
  596. 'object_name' => $form_state['values']['relationship_table']['new']['object_name'],
  597. 'subject_id' => $form_state['node']->{$details['base_table']}->{$details['base_foreign_key']},
  598. 'subject_name' => $name,
  599. 'rank' => NULL,
  600. 'relationship_id' => 'TEMP' . uniqid()
  601. );
  602. // we don't want the new element to pick up the values from the previous element so wipe them out
  603. unset($form_state['input']['relationship_table']['new']['object_id']);
  604. unset($form_state['input']['relationship_table']['new']['object_name']);
  605. }
  606. else {
  607. $relationship = array(
  608. 'type_id' => $form_state['values']['relationship_table']['new']['type_id'],
  609. 'type_name' => $form_state['values']['relationship_table']['new']['type_name'],
  610. 'object_id' => $form_state['node']->{$details['base_table']}->{$details['base_foreign_key']},
  611. 'object_name' => $name,
  612. 'subject_id' => $form_state['values']['relationship_table']['new']['subject_id'],
  613. 'subject_name' => $form_state['values']['relationship_table']['new']['subject_name'],
  614. 'rank' => NULL,
  615. 'relationship_id' => 'TEMP' . uniqid(),
  616. );
  617. // we don't want the new element to pick up the values from the previous element so wipe them out
  618. unset($form_state['input']['relationship_table']['new']['subject_id']);
  619. unset($form_state['input']['relationship_table']['new']['subject_name']);
  620. }
  621. $key = $relationship['type_id'] . '-' . $relationship['relationship_id'];
  622. $form_state['chado_relationships'][$key] = (object) $relationship;
  623. // we don't want the new element to pick up the values from the previous element so wipe them out
  624. unset($form_state['input']['relationship_table']['new']['type_id']);
  625. unset($form_state['input']['relationship_table']['new']['type_name']);
  626. }
  627. /**
  628. * Called by the many remove buttons in chado_add_node_form_relationships
  629. *
  630. * @ingroup tripal_core
  631. */
  632. function chado_add_node_form_relationships_remove_button_validate($form, &$form_state) {
  633. // No validation needed.
  634. }
  635. /**
  636. * Remove the correct relationship from the form
  637. * Called by the many remove buttons in chado_add_node_form_relationships
  638. *
  639. * @ingroup tripal_core
  640. */
  641. function chado_add_node_form_relationships_remove_button_submit(&$form, &$form_state) {
  642. // if the chado_relationships array is not set then this is the first time modifying the
  643. // relationship table. this means we need to include all the relationships from the db
  644. chado_add_node_form_relationships_create_relationship_formstate_array($form, $form_state);
  645. // remove the specified relationship from the form relationship table
  646. if(preg_match('/relationships_remove-([^-]+-[^-]+)/',$form_state['triggering_element']['#name'],$match)) {
  647. $key = $match[1];
  648. if (array_key_exists($key, $form_state['chado_relationships'])) {
  649. unset($form_state['chado_relationships'][$key]);
  650. }
  651. }
  652. }
  653. /**
  654. * Creates an array in form_state containing the existing relationships. This array is
  655. * then modified by the add/remove buttons and used as a source for rebuilding the form.
  656. *
  657. * $form_state['chado_relationships'] = array(
  658. * '[type_id]-[rank]' => array(
  659. * 'object_id' => [the _relationship.object_id value],
  660. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  661. * 'subject_id' => [the _relationship.subject_id value],
  662. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  663. * 'type_id' => [the _relationship.type_id value],
  664. * 'type_name' => [the cvterm.name value linked on type_id],
  665. * 'rank' => [the _relationship.rank value],
  666. * ),
  667. * );
  668. *
  669. * @ingroup tripal_core
  670. */
  671. function chado_add_node_form_relationships_create_relationship_formstate_array($form, &$form_state) {
  672. $form_state['chado_relationships'] = array();
  673. foreach (element_children($form['relationships']['relationship_table']) as $type_id) {
  674. if ($type_id != 'new') {
  675. foreach (element_children($form['relationships']['relationship_table'][$type_id]) as $relationship_id) {
  676. $element = $form['relationships']['relationship_table'][$type_id][$relationship_id];
  677. $rel = array(
  678. 'type_id' => $element['type_id']['#value'],
  679. 'object_id' => $element['object_id']['#value'],
  680. 'subject_id' => $element['subject_id']['#value'],
  681. 'type_name' => $element['type_name']['#markup'],
  682. 'object_name' => $element['object_name']['#markup'],
  683. 'subject_name' => $element['subject_name']['#markup'],
  684. 'rank' => $element['rank']['#markup'],
  685. 'relationship_id' => $relationship_id,
  686. );
  687. $key = $rel['type_id'] . '-' . $rel['relationship_id'];
  688. $form_state['chado_relationships'][$key] = (object) $rel;
  689. }
  690. }
  691. }
  692. }
  693. /**
  694. * Function to theme the add/remove relationships form into a table
  695. *
  696. * @ingroup tripal_chado_node_api
  697. */
  698. function theme_chado_add_node_form_relationships_table($variables) {
  699. $element = $variables['element'];
  700. $details = unserialize($element['details']['#value']);
  701. $header = array(
  702. 'subject_name' => t('Subject ' . $details['base_name_field']),
  703. 'type_name' => t('Type'),
  704. 'object_name' => t('Object ' . $details['base_name_field']),
  705. 'rel_action' => t('Action')
  706. );
  707. $rows = array();
  708. foreach (element_children($element) as $type_id) {
  709. if ($type_id == 'new') {
  710. $row = array();
  711. $row['data'] = array();
  712. foreach ($header as $fieldname => $title) {
  713. if ($fieldname == 'subject_name') {
  714. $row['data'][] = drupal_render($element[$type_id][$fieldname]) . drupal_render($element[$type_id]['subject_is_current']);
  715. }
  716. elseif ($fieldname == 'object_name') {
  717. $row['data'][] = drupal_render($element[$type_id][$fieldname]) . drupal_render($element[$type_id]['object_is_current']);
  718. }
  719. else {
  720. $row['data'][] = drupal_render($element[$type_id][$fieldname]);
  721. }
  722. }
  723. $rows[] = $row;
  724. }
  725. else {
  726. foreach (element_children($element[$type_id]) as $rank) {
  727. $row = array();
  728. $row['data'] = array();
  729. foreach ($header as $fieldname => $title) {
  730. $row['data'][] = drupal_render($element[$type_id][$rank][$fieldname]);
  731. }
  732. $rows[] = $row;
  733. }
  734. }
  735. }
  736. return theme('table', array(
  737. 'header' => $header,
  738. 'rows' => $rows,
  739. 'sticky' => FALSE
  740. ));
  741. }
  742. /**
  743. * This function is used in a hook_insert, hook_update for a node form
  744. * when the relationships form has been added to the form. It retrieves all of the relationships
  745. * and returns them in an array of the format:
  746. *
  747. * $relationships[<type_id>][<rank>] = array(
  748. * 'subject_id' => <subject_id>,
  749. * 'object_id' => <object_id>,
  750. * );
  751. *
  752. * This array can then be used for inserting or updating relationships manually
  753. *
  754. * @param $node
  755. *
  756. * @return
  757. * A relationship array
  758. *
  759. * @ingroup tripal_chado_node_api
  760. */
  761. function chado_retrieve_node_form_relationships($node) {
  762. $rels = array();
  763. if (isset($node->relationship_table)) {
  764. foreach ($node->relationship_table as $type_id => $elements) {
  765. if ($type_id != 'new' AND $type_id != 'details') {
  766. foreach ($elements as $rank => $relationships) {
  767. $rels[$type_id][$rank]['subject_id'] = $relationships['subject_id'];
  768. $rels[$type_id][$rank]['object_id'] = $relationships['object_id'];
  769. }
  770. }
  771. }
  772. }
  773. return $rels;
  774. }
  775. /**
  776. * This function is used in hook_insert or hook_update and handles inserting of
  777. * relationships between the current nodetype and other memebers of the same nodetype
  778. *
  779. * @param $node
  780. * The node passed into hook_insert & hook_update
  781. * @param $details
  782. * - relationship_table: the name of the _relationship linking table (ie: feature_relationship)
  783. * - foreignkey_value: the value of the foreign key (ie: 445, if there exists a feature where feature_id=445)
  784. * @param $retrieved_relationships
  785. * An array of relationships from chado_retrieve_node_form_relationships($node). This
  786. * can be used if you need special handling for some of the relationships.
  787. *
  788. * @ingroup tripal_chado_node_api
  789. */
  790. function chado_update_node_form_relationships($node, $details, $retrieved_relationships = FALSE) {
  791. $relationship_table = $details['relationship_table'];
  792. $current_id = $details['foreignkey_value'];
  793. if (isset($node->relationship_table) AND ($current_id > 0)) {
  794. // determine whether there is a rank in this relationship table
  795. $form_details = unserialize($node->relationship_table['details']);
  796. $has_rank = $form_details['table_has_rank'];
  797. // First remove existing relationships links
  798. chado_delete_record(
  799. $relationship_table,
  800. array($form_details['subject_field_name'] => $current_id)
  801. );
  802. chado_delete_record(
  803. $relationship_table,
  804. array($form_details['object_field_name'] => $current_id)
  805. );
  806. // Add back in relationships as needed
  807. if ($retrieved_relationships) {
  808. $relationships = $retrieved_relationships;
  809. }
  810. else {
  811. $relationships = chado_retrieve_node_form_relationships($node);
  812. }
  813. foreach ($relationships as $type_id => $ranks) {
  814. foreach ($ranks as $rank => $element) {
  815. $values = array(
  816. $form_details['subject_field_name'] => $element['subject_id'],
  817. 'type_id' => $type_id,
  818. $form_details['object_field_name'] => $element['object_id']
  819. );
  820. // Set the current id if not already
  821. // this is usually only necessary in an insert
  822. if (empty($values[$form_details['subject_field_name']])) {
  823. $values[$form_details['subject_field_name']] = $current_id;
  824. }
  825. if (empty($values[$form_details['object_field_name']])) {
  826. $values[$form_details['object_field_name']] = $current_id;
  827. }
  828. if ($has_rank) {
  829. // Ensure that the rank is Set & Current
  830. $rank_select = chado_get_table_max_rank(
  831. $relationship_table,
  832. array(
  833. $form_details['subject_field_name'] => $values['subject_id'],
  834. 'type_id' => $values['type_id'],
  835. $form_details['object_field_name'] => $values['object_id'],
  836. )
  837. );
  838. $values['rank'] = $rank_select + 1;
  839. }
  840. // add relationship
  841. $success_link = chado_insert_record(
  842. $relationship_table,
  843. $values
  844. );
  845. }
  846. }
  847. }
  848. }
  849. /**
  850. * Handles autocomplete for subject & object id
  851. *
  852. * @param $string
  853. * The part of the string already typed in the textfield
  854. *
  855. * @ingroup tripal_core
  856. */
  857. function chado_add_node_form_relationships_name_to_id_callback($base_table, $name_field, $string) {
  858. $matches = array();
  859. $base_key = $base_table.'_id';
  860. $query = db_select('chado.'.$base_table, 'b')
  861. ->fields('b', array($base_key, $name_field))
  862. ->condition($name_field, '%' . db_like($string) . '%', 'LIKE');
  863. $result = $query->execute();
  864. // save the query to matches
  865. foreach ($result as $row) {
  866. if (strlen($row->{$name_field}) > 50) {
  867. $key = '('.$row->{$base_key}.') ' . substr($row->{$name_field}, 0, 50) . '...';
  868. }
  869. else {
  870. $key = '('.$row->{$base_key}.') ' . $row->{$name_field};
  871. }
  872. $matches[$key] = check_plain($row->{$name_field});
  873. }
  874. // return for JS
  875. drupal_json_output($matches);
  876. }