tripal_core.chado_nodes.relationships.api.inc 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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 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. $form_state['rebuild'] = TRUE;
  104. // Set Defaults for optional fields
  105. $details['fieldset_title'] = (isset($details['fieldset_title'])) ? $details['fieldset_title'] : 'Relationships';
  106. $details['additional_instructions'] = (isset($details['additional_instructions'])) ? $details['additional_instructions'] : '';
  107. $details['nodetype_plural'] = (isset($details['nodetype_plural'])) ? $details['nodetype_plural'] : $details['nodetype'] . 's';
  108. $details['base_name_field'] = (isset($details['base_name_field'])) ? $details['base_name_field'] : 'uniquename';
  109. $details['subject_field_name'] = (isset($details['subject_field_name'])) ? $details['subject_field_name'] : 'subject_id';
  110. $details['object_field_name'] = (isset($details['object_field_name'])) ? $details['object_field_name'] : 'object_id';
  111. // Some relationship tables don't have a rank
  112. // thus we need to first check this table has a rank before trying to set it
  113. $table_schema = chado_get_schema($details['relationship_table']);
  114. $details['table_has_rank'] = (isset($table_schema['fields']['rank'])) ? TRUE : FALSE;
  115. // Get Property Types for the Select List
  116. if (isset($details['select_options'])) {
  117. $type_options = $details['select_options'];
  118. }
  119. else {
  120. if (isset($details['cv_name'])) {
  121. $type_options = array();
  122. $type_options[] = 'Select a Property';
  123. $sql = "
  124. SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition
  125. FROM {cvterm} CVT
  126. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  127. WHERE
  128. CV.name = :cv_name AND
  129. NOT CVT.is_obsolete = 1
  130. ORDER BY CVT.name ASC
  131. ";
  132. $prop_types = chado_query($sql, array(':cv_name' => $details['cv_name']));
  133. while ($prop = $prop_types->fetchObject()) {
  134. $type_options[$prop->cvterm_id] = $prop->name;
  135. }
  136. } elseif (isset($details['cv_id'])) {
  137. $type_options = array();
  138. $type_options[] = 'Select a Property';
  139. $sql = "
  140. SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition
  141. FROM {cvterm} CVT
  142. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  143. WHERE
  144. CV.cv_id = :cv_id AND
  145. NOT CVT.is_obsolete = 1
  146. ORDER BY CVT.name ASC
  147. ";
  148. $prop_types = chado_query($sql, array(':cv_id' => $details['cv_id']));
  149. while ($prop = $prop_types->fetchObject()) {
  150. $type_options[$prop->cvterm_id] = $prop->name;
  151. }
  152. }
  153. }
  154. $form['relationships'] = array(
  155. '#type' => 'fieldset',
  156. '#title' => t($details['fieldset_title']),
  157. '#description' => t('You may add relationships between this %nodetype and other
  158. %nodetype_plural by entering the details below. You may add
  159. as many relationships as desired by clicking the add button on the right. To
  160. remove a relationship, click the remove button. ' . $details['additional_instructions'],
  161. array('%nodetype' => $details['nodetype'], '%nodetype_plural' => $details['nodetype_plural'])),
  162. '#prefix' => "<div id='relationships-fieldset'>",
  163. '#suffix' => '</div>',
  164. '#weight' => 10
  165. );
  166. // this form element is a tree, so that we don't puke all of the values into then node variable
  167. // it is set as a tree, and keeps them in the $form_state['values']['relationship_table'] heading.
  168. $form['relationships']['relationship_table'] = array(
  169. '#type' => 'markup',
  170. '#tree' => TRUE,
  171. '#prefix' => '<div id="tripal-generic-edit-relationships-table">',
  172. '#suffix' => '</div>',
  173. '#theme' => 'chado_node_relationships_form_table'
  174. );
  175. // Add defaults into form_state to be used elsewhere
  176. $form['relationships']['relationship_table']['details'] = array(
  177. '#type' => 'hidden',
  178. '#value' => serialize($details)
  179. );
  180. // Add relationships already attached to the node
  181. //---------------------------------------------
  182. /* Relationships can come to us in two ways:
  183. *
  184. * 1) In the form state in the $form_state['chado_relationships']. Data is in this field
  185. * when an AJAX call updates the form state or a validation error.
  186. *
  187. * 2) Directly from the database if the record already has _relationships associated. This
  188. * data is only used the first time the form is loaded. On AJAX calls or validation
  189. * errors the fields on the form are populated from the $form_state['chado_relationships']
  190. * entry.
  191. */
  192. if (isset($form_state['chado_relationships'])) {
  193. $existing_rels = $form_state['chado_relationships'];
  194. }
  195. else {
  196. $existing_rels = chado_query(
  197. "SELECT
  198. rel.*,
  199. rel.".$details['subject_field_name']." as subject_id,
  200. rel.".$details['object_field_name']." as object_id,
  201. base1.".$details['base_name_field']." as object_name,
  202. base2.".$details['base_name_field']." as subject_name,
  203. cvterm.name as type_name
  204. FROM {".$details['relationship_table']."} rel
  205. LEFT JOIN {".$details['base_table']."} base1 ON base1.".$details['base_foreign_key']." = rel.".$details['object_field_name']."
  206. LEFT JOIN {".$details['base_table']."} base2 ON base2.".$details['base_foreign_key']." = rel.".$details['subject_field_name']."
  207. LEFT JOIN {cvterm} cvterm ON cvterm.cvterm_id = rel.type_id
  208. WHERE rel.".$details['object_field_name']." = :base_key_value
  209. OR rel.".$details['subject_field_name']." = :base_key_value",
  210. array(':base_key_value' => $details['base_key_value'])
  211. );
  212. }
  213. /* The format of the $existing_rels' array is either:
  214. *
  215. * From the chado_relationships array:
  216. * $form_state['chado_relationships'] = array(
  217. * '[type_id]-[rank]' => array(
  218. * 'object_id' => [the _relationship.object_id value],
  219. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  220. * 'subject_id' => [the _relationship.subject_id value],
  221. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  222. * 'type_id' => [the _relationship.type_id value],
  223. * 'type_name' => [the cvterm.name value linked on type_id],
  224. * 'rank' => [the _relationship.rank value],
  225. * ),
  226. * );
  227. *
  228. * OR
  229. * Populated from the database:
  230. * $existing_rels = array(
  231. * 0 => array(
  232. * 'relationship_id' => [the _relationship.relationship_id value],
  233. * 'object_id' => [the _relationship.object_id value],
  234. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  235. * 'subject_id' => [the _relationship.subject_id value],
  236. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  237. * 'type_id' => [the _relationship.type_id value],
  238. * 'type_name' => [the cvterm.name value linked on type_id],
  239. * 'rank' => [the _relationship.rank value],
  240. * ),
  241. * );
  242. *
  243. * NOTE: The main difference is the key
  244. *
  245. * Loop on the array elements of the $existing_rels array and add
  246. * an element to the form for each one.
  247. */
  248. foreach ($existing_rels as $relationship) {
  249. if (array_key_exists($relationship->type_id, $type_options)) {
  250. $rank = (isset($relationship->rank)) ? $relationship->rank : 0;
  251. $form['relationships']['relationship_table'][$relationship->type_id]['#type'] = 'markup';
  252. $form['relationships']['relationship_table'][$relationship->type_id]['#type'] = '';
  253. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['#type'] = 'markup';
  254. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['#value'] = '';
  255. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['object_id'] = array(
  256. '#type' => 'hidden',
  257. '#value' => $relationship->object_id
  258. );
  259. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['subject_id'] = array(
  260. '#type' => 'hidden',
  261. '#value' => $relationship->subject_id
  262. );
  263. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['type_id'] = array(
  264. '#type' => 'hidden',
  265. '#value' => $relationship->type_id
  266. );
  267. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['object_name'] = array(
  268. '#type' => 'markup',
  269. '#markup' => $relationship->object_name
  270. );
  271. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['type_name'] = array(
  272. '#type' => 'markup',
  273. '#markup' => $relationship->type_name
  274. );
  275. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['subject_name'] = array(
  276. '#type' => 'markup',
  277. '#markup' => $relationship->subject_name
  278. );
  279. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['rank'] = array(
  280. '#type' => 'markup',
  281. '#markup' => $rank
  282. );
  283. $form['relationships']['relationship_table'][$relationship->type_id][$rank]['rel_action'] = array(
  284. '#type' => 'submit',
  285. '#value' => t('Remove'),
  286. '#name' => "rel_remove-".$relationship->type_id.'-'.$rank,
  287. '#ajax' => array(
  288. 'callback' => 'chado_add_node_form_relationships_ajax_update',
  289. 'wrapper' => 'tripal-generic-edit-relationships-table',
  290. 'effect' => 'fade',
  291. 'method' => 'replace',
  292. 'prevent' => 'click'
  293. ),
  294. // When this button is clicked, the form will be validated and submitted.
  295. // Therefore, we set custom submit and validate functions to override the
  296. // default node form submit. In the validate function we validate only the
  297. // relationship fields and in the submit we remove the indicated relationship
  298. // from the chado_relationships array. In order to keep validate errors
  299. // from the node form validate and Drupal required errors for non-relationship fields
  300. // preventing the user from removing relationships we set the #limit_validation_errors below
  301. '#validate' => array('chado_add_node_form_relationships_form_remove_button_validate'),
  302. '#submit' => array('chado_add_node_form_relationships_remove_button_submit'),
  303. // Limit the validation of the form upon clicking this button to the relationship_table tree
  304. // No other fields will be validated (ie: no fields from the main form or any other api
  305. // added form).
  306. '#limit_validation_errors' => array(
  307. array('relationship_table') // Validate all fields within $form_state['values']['relationship_table']
  308. )
  309. );
  310. }
  311. }
  312. $form['relationships']['relationship_table']['new']['object_name'] = array(
  313. '#type' => 'textfield',
  314. '#autocomplete_path' => 'tripal_ajax/relationship_nodeform/'.$details['base_table'].'/'.$details['base_name_field'].'/name_to_id'
  315. );
  316. $form['relationships']['relationship_table']['new']['object_is_current'] = array(
  317. '#type' => 'checkbox',
  318. '#title' => t('Current '.$details['nodetype']),
  319. );
  320. $form['relationships']['relationship_table']['new']['type_name'] = array(
  321. '#type' => 'select',
  322. '#options' => $type_options,
  323. );
  324. $form['relationships']['relationship_table']['new']['subject_name'] = array(
  325. '#type' => 'textfield',
  326. '#autocomplete_path' => 'tripal_ajax/relationship_nodeform/'.$details['base_table'].'/'.$details['base_name_field'].'/name_to_id'
  327. );
  328. $form['relationships']['relationship_table']['new']['subject_is_current'] = array(
  329. '#type' => 'checkbox',
  330. '#title' => t('Current '.$details['nodetype']),
  331. );
  332. $form['relationships']['relationship_table']['new']['rank'] = array(
  333. '#type' => 'markup',
  334. '#markup' => ''
  335. );
  336. $form['relationships']['relationship_table']['new']['rel_action'] = array(
  337. '#type' => 'submit',
  338. '#value' => t('Add'),
  339. '#name' => 'rel_add',
  340. '#ajax' => array(
  341. 'callback' => 'chado_add_node_form_relationships_ajax_update',
  342. 'wrapper' => 'tripal-generic-edit-relationships-table',
  343. 'effect' => 'fade',
  344. 'method' => 'replace',
  345. 'prevent' => 'click'
  346. ),
  347. // When this button is clicked, the form will be validated and submitted.
  348. // Therefore, we set custom submit and validate functions to override the
  349. // default node form submit. In the validate function we validate only the
  350. // relationship fields and in the submit we add them to the chado_relationships
  351. // array. In order to keep validate errors from the node form validate and Drupal
  352. // required errors for non-relationship fields preventing the user from adding relationships we
  353. // set the #limit_validation_errors below
  354. '#validate' => array('chado_add_node_form_relationships_add_button_validate'),
  355. '#submit' => array('chado_add_node_form_relationships_add_button_submit'),
  356. // Limit the validation of the form upon clicking this button to the relationship_table tree
  357. // No other fields will be validated (ie: no fields from the main form or any other api
  358. // added form).
  359. '#limit_validation_errors' => array(
  360. array('relationship_table') // Validate all fields within $form_state['values']['relationship_table']
  361. )
  362. );
  363. }
  364. /**
  365. * Validate the user input for creating a new relationship
  366. * Called by the add button in chado_add_node_form_relationships
  367. *
  368. * @ingroup tripal_core
  369. */
  370. function chado_add_node_form_relationships_add_button_validate($form, &$form_state) {
  371. $details = unserialize($form_state['values']['relationship_table']['details']);
  372. // First deal with autocomplete fields
  373. // extract the base_id assuming '(###) NAME FIELD'
  374. if (!empty($form_state['values']['relationship_table']['new']['subject_name'])) {
  375. if (preg_match('/\((\d+)\) .*/', $form_state['values']['relationship_table']['new']['subject_name'], $matches)) {
  376. $form_state['values']['relationship_table']['new']['subject_id'] = $matches[1];
  377. }
  378. else {
  379. form_set_error('subject_name', 'You need to select the subject from the autocomplete drop-down');
  380. }
  381. }
  382. if (!empty($form_state['values']['relationship_table']['new']['object_name'])) {
  383. if (preg_match('/\((\d+)\) .*/', $form_state['values']['relationship_table']['new']['object_name'], $matches)) {
  384. $form_state['values']['relationship_table']['new']['object_id'] = $matches[1];
  385. }
  386. else {
  387. form_set_error('object_name', 'You need to select the subject from the autocomplete drop-down');
  388. }
  389. }
  390. // At least one of the participants must be the current node
  391. if (!($form_state['values']['relationship_table']['new']['subject_is_current'] OR $form_state['values']['relationship_table']['new']['object_is_current'])) {
  392. // If the checkbox isn't set then check to see if either has the same uniquename as the node
  393. if ($form_state['values']['relationship_table']['new']['subject_name'] == $form_state['values']['uniquename']) {
  394. $form_state['values']['relationship_table']['new']['subject_is_current'] = 1;
  395. form_set_error('subject_is_current', 'To set the current '.$details['nodetype'].', select the
  396. checkbox. You entered the unique name of the current '.$details['nodetype'].' as the subject,
  397. is this what you meant to do?');
  398. }
  399. elseif ($form_state['values']['relationship_table']['new']['subject_name'] == $form_state['values']['uniquename']) {
  400. $form_state['values']['relationship_table']['new']['object_is_current'] = 1;
  401. form_set_error('subject_is_current', 'To set the current '.$details['nodetype'].', select the
  402. checkbox. You entered the unique name of the current '.$details['nodetype'].' as the subject,
  403. is this what you meant to do?');
  404. }
  405. else {
  406. form_set_error('object_is_current', 'At least one member of the relationship must be
  407. the current '.$details['nodetype'].'. This is specified by checking the "Current '.$details['nodetype'].'"
  408. checkbox for either the subject or object.');
  409. }
  410. }
  411. // The non-current uniquename must be exist in the base table (subject)
  412. if (!($form_state['values']['relationship_table']['new']['subject_is_current'])) {
  413. $result = chado_select_record(
  414. $details['base_table'],
  415. array($details['base_name_field']),
  416. array($details['base_foreign_key'] => $form_state['values']['relationship_table']['new']['subject_id'])
  417. );
  418. if (!isset($result[0])) {
  419. form_set_error('subject_name', 'The subject must be the unique name of an
  420. existing '.$details['nodetype'].' unless the "Current '.$details['nodetype'].'" checkbox is selected');
  421. }
  422. else {
  423. $form_state['values']['relationship_table']['new']['subject_name'] = $result[0]->{$details['base_name_field']};
  424. }
  425. }
  426. // The non-current uniquename must exist in the base table (object)
  427. if (!($form_state['values']['relationship_table']['new']['object_is_current'])) {
  428. $result = chado_select_record(
  429. $details['base_table'],
  430. array($details['base_name_field']),
  431. array($details['base_foreign_key'] => $form_state['values']['relationship_table']['new']['object_id'])
  432. );
  433. if (!isset($result[0])) {
  434. form_set_error('object_name', 'The object must be the unique name of an
  435. existing '.$details['nodetype'].' unless the "Current '.$details['nodetype'].'" checkbox is selected');
  436. }
  437. else {
  438. $form_state['values']['relationship_table']['new']['object_name'] = $result[0]->{$details['base_name_field']};
  439. }
  440. }
  441. // The type must be a valid cvterm
  442. if ($form_state['values']['relationship_table']['new']['type_name']) {
  443. $form_state['values']['relationship_table']['new']['type_id'] = $form_state['values']['relationship_table']['new']['type_name'];
  444. $result = chado_select_record(
  445. 'cvterm',
  446. array('name'),
  447. array('cvterm_id' => $form_state['values']['relationship_table']['new']['type_id'])
  448. );
  449. if (!isset($result[0])) {
  450. form_set_error('type_id', 'The select type is not a valid controlled vocabulary term.');
  451. }
  452. else {
  453. $form_state['values']['relationship_table']['new']['type_name'] = $result[0]->name;
  454. }
  455. }
  456. else {
  457. form_set_error('type_id', 'Please select a type of relationship');
  458. }
  459. }
  460. /**
  461. * Called by the add button in chado_add_node_form_relationships
  462. *
  463. * Create an array of additional relationships in the form state. This array will then be
  464. * used to rebuild the form in subsequent builds
  465. *
  466. * @ingroup tripal_core
  467. */
  468. function chado_add_node_form_relationships_add_button_submit(&$form, &$form_state) {
  469. $details = unserialize($form_state['values']['relationship_table']['details']);
  470. // if the chado_relationships array is not set then this is the first time modifying the
  471. // relationship table. this means we need to include all the relationships from the db
  472. if (!isset($form_state['chado_relationships'])) {
  473. chado_add_node_form_relationships_create_relationship_formstate_array($form, $form_state);
  474. }
  475. $name = (isset($form_state['node']->{$details['base_table']}->uniquename)) ? $form_state['node']->{$details['base_table']}->uniquename : 'CURRENT';
  476. // get details for the new relationship
  477. if ($form_state['values']['relationship_table']['new']['subject_is_current']) {
  478. $relationship = array(
  479. 'type_id' => $form_state['values']['relationship_table']['new']['type_id'],
  480. 'type_name' => $form_state['values']['relationship_table']['new']['type_name'],
  481. 'object_id' => $form_state['values']['relationship_table']['new']['object_id'],
  482. 'object_name' => $form_state['values']['relationship_table']['new']['object_name'],
  483. 'subject_id' => $form_state['node']->{$details['base_table']}->{$details['base_foreign_key']},
  484. 'subject_name' => $name,
  485. 'rank' => '0',
  486. );
  487. }
  488. else {
  489. $relationship = array(
  490. 'type_id' => $form_state['values']['relationship_table']['new']['type_id'],
  491. 'type_name' => $form_state['values']['relationship_table']['new']['type_name'],
  492. 'object_id' => $form_state['node']->{$details['base_table']}->{$details['base_foreign_key']},
  493. 'object_name' => $name,
  494. 'subject_id' => $form_state['values']['relationship_table']['new']['subject_id'],
  495. 'subject_name' => $form_state['values']['relationship_table']['new']['subject_name'],
  496. 'rank' => '0',
  497. );
  498. }
  499. $key = $relationship['type_id'] . '-' . $relationship['rank'];
  500. $form_state['chado_relationships'][$key] = (object) $relationship;
  501. $form_state['rebuild'] = TRUE;
  502. }
  503. /**
  504. * There is no user input for the remove buttons so there is no need to validate
  505. * However, both a submit & validate need to be specified so this is just a placeholder
  506. *
  507. * Called by the many remove buttons in chado_add_node_form_relationships
  508. *
  509. * @ingroup tripal_core
  510. */
  511. function chado_add_node_form_relationships_form_remove_button_validate($form, $form_state) {
  512. // No Validation needed for remove
  513. }
  514. /**
  515. * Remove the correct relationship from the form
  516. * Called by the many remove buttons in chado_add_node_form_relationships
  517. *
  518. * @ingroup tripal_core
  519. */
  520. function chado_add_node_form_relationships_remove_button_submit(&$form, &$form_state) {
  521. // if the chado_relationships array is not set then this is the first time modifying the
  522. // relationship table. this means we need to include all the relationships from the db
  523. if (!isset($form_state['chado_relationships'])) {
  524. chado_add_node_form_relationships_create_relationship_formstate_array($form, $form_state);
  525. }
  526. // remove the specified relationship from the form relationship table
  527. if(preg_match('/rel_remove-([^-]+-[^-]+)/',$form_state['triggering_element']['#name'],$match)) {
  528. $key = $match[1];
  529. if (array_key_exists($key, $form_state['chado_relationships'])) {
  530. unset($form_state['chado_relationships'][$key]);
  531. }
  532. }
  533. $form_state['rebuild'] = TRUE;
  534. }
  535. /**
  536. * Ajax function which returns the section of the form to be re-rendered
  537. *
  538. * @ingroup tripal_core
  539. */
  540. function chado_add_node_form_relationships_ajax_update($form, $form_state) {
  541. return $form['relationships']['relationship_table'];
  542. }
  543. /**
  544. * Creates an array in form_state containing the existing relationships. This array is
  545. * then modified by the add/remove buttons and used as a source for rebuilding the form.
  546. *
  547. * $form_state['chado_relationships'] = array(
  548. * '[type_id]-[rank]' => array(
  549. * 'object_id' => [the _relationship.object_id value],
  550. * 'object_name' => [the base_table.uniquename value linked on base_foreign_key=object_id],
  551. * 'subject_id' => [the _relationship.subject_id value],
  552. * 'subject_name' => [the base_table.uniquename value linked on base_foreign_key=subject_id],
  553. * 'type_id' => [the _relationship.type_id value],
  554. * 'type_name' => [the cvterm.name value linked on type_id],
  555. * 'rank' => [the _relationship.rank value],
  556. * ),
  557. * );
  558. *
  559. * @ingroup tripal_core
  560. */
  561. function chado_add_node_form_relationships_create_relationship_formstate_array($form, &$form_state) {
  562. $form_state['chado_relationships'] = array();
  563. foreach (element_children($form['relationships']['relationship_table']) as $type_id) {
  564. if ($type_id != 'new') {
  565. foreach (element_children($form['relationships']['relationship_table'][$type_id]) as $rank) {
  566. $element = $form['relationships']['relationship_table'][$type_id][$rank];
  567. $rel = array(
  568. 'type_id' => $element['type_id']['#value'],
  569. 'object_id' => $element['object_id']['#value'],
  570. 'subject_id' => $element['subject_id']['#value'],
  571. 'type_name' => $element['type_name']['#markup'],
  572. 'object_name' => $element['object_name']['#markup'],
  573. 'subject_name' => $element['subject_name']['#markup'],
  574. 'rank' => $element['rank']['#markup']
  575. );
  576. $key = $rel['type_id'] . '-' . $rel['rank'];
  577. $form_state['chado_relationships'][$key] = (object) $rel;
  578. }
  579. }
  580. }
  581. }
  582. /**
  583. * Function to theme the add/remove relationships form into a table
  584. *
  585. * @ingroup tripal_chado_node_api
  586. */
  587. function theme_chado_add_node_form_relationships_table($variables) {
  588. $element = $variables['element'];
  589. $details = unserialize($element['details']['#value']);
  590. $header = array(
  591. 'object_name' => t('Object ' . $details['base_name_field']),
  592. 'type_name' => t('Type'),
  593. 'subject_name' => t('Subject ' . $details['base_name_field']),
  594. 'rel_action' => t('Action')
  595. );
  596. $rows = array();
  597. foreach (element_children($element) as $type_id) {
  598. if ($type_id == 'new') {
  599. $row = array();
  600. $row['data'] = array();
  601. foreach ($header as $fieldname => $title) {
  602. if ($fieldname == 'subject_name') {
  603. $row['data'][] = drupal_render($element[$type_id][$fieldname]) . drupal_render($element[$type_id]['subject_is_current']);
  604. }
  605. elseif ($fieldname == 'object_name') {
  606. $row['data'][] = drupal_render($element[$type_id][$fieldname]) . drupal_render($element[$type_id]['object_is_current']);
  607. }
  608. else {
  609. $row['data'][] = drupal_render($element[$type_id][$fieldname]);
  610. }
  611. }
  612. $rows[] = $row;
  613. }
  614. else {
  615. foreach (element_children($element[$type_id]) as $rank) {
  616. $row = array();
  617. $row['data'] = array();
  618. foreach ($header as $fieldname => $title) {
  619. $row['data'][] = drupal_render($element[$type_id][$rank][$fieldname]);
  620. }
  621. $rows[] = $row;
  622. }
  623. }
  624. }
  625. return theme('table', array(
  626. 'header' => $header,
  627. 'rows' => $rows
  628. ));
  629. }
  630. /**
  631. * This function is used in a hook_insert, hook_update for a node form
  632. * when the relationships form has been added to the form. It retrieves all of the relationships
  633. * and returns them in an array of the format:
  634. *
  635. * $relationships[<type_id>][<rank>] = array(
  636. * 'subject_id' => <subject_id>,
  637. * 'object_id' => <object_id>,
  638. * );
  639. *
  640. * This array can then be used for inserting or updating relationships manually
  641. *
  642. * @param $node
  643. *
  644. * @return
  645. * A relationship array
  646. *
  647. * @ingroup tripal_chado_node_api
  648. */
  649. function chado_retrieve_node_form_relationships($node) {
  650. $rels = array();
  651. if (isset($node->relationship_table)) {
  652. foreach ($node->relationship_table as $type_id => $elements) {
  653. if ($type_id != 'new' AND $type_id != 'details') {
  654. foreach ($elements as $rank => $relationships) {
  655. $rels[$type_id][$rank]['subject_id'] = $relationships['subject_id'];
  656. $rels[$type_id][$rank]['object_id'] = $relationships['object_id'];
  657. }
  658. }
  659. }
  660. }
  661. return $rels;
  662. }
  663. /**
  664. * This function is used in hook_insert or hook_update and handles inserting of
  665. * relationships between the current nodetype and other memebers of the same nodetype
  666. *
  667. * @param $node
  668. * The node passed into hook_insert & hook_update
  669. * @param $details
  670. * - relationship_table: the name of the _relationship linking table (ie: feature_relationship)
  671. * - foreignkey_value: the value of the foreign key (ie: 445, if there exists a feature where feature_id=445)
  672. * @param $retrieved_relationships
  673. * An array of relationships from chado_retrieve_node_form_relationships($node). This
  674. * can be used if you need special handling for some of the relationships.
  675. *
  676. * @ingroup tripal_chado_node_api
  677. */
  678. function chado_update_node_form_relationships($node, $details, $retrieved_relationships = FALSE) {
  679. $relationship_table = $details['relationship_table'];
  680. $current_id = $details['foreignkey_value'];
  681. if (isset($node->relationship_table) AND ($current_id > 0)) {
  682. // determine whether there is a rank in this relationship table
  683. $form_details = unserialize($node->relationship_table['details']);
  684. $has_rank = $form_details['table_has_rank'];
  685. // First remove existing relationships links
  686. chado_delete_record(
  687. $relationship_table,
  688. array($form_details['subject_field_name'] => $current_id)
  689. );
  690. chado_delete_record(
  691. $relationship_table,
  692. array($form_details['object_field_name'] => $current_id)
  693. );
  694. // Add back in relationships as needed
  695. if ($retrieved_relationships) {
  696. $relationships = $retrieved_relationships;
  697. }
  698. else {
  699. $relationships = chado_retrieve_node_form_relationships($node);
  700. }
  701. foreach ($relationships as $type_id => $ranks) {
  702. foreach ($ranks as $rank => $element) {
  703. $values = array(
  704. $form_details['subject_field_name'] => $element['subject_id'],
  705. 'type_id' => $type_id,
  706. $form_details['object_field_name'] => $element['object_id']
  707. );
  708. // Set the current id if not already
  709. // this is usually only necessary in an insert
  710. if (empty($values[$form_details['subject_field_name']])) {
  711. $values[$form_details['subject_field_name']] = $current_id;
  712. }
  713. if (empty($values[$form_details['object_field_name']])) {
  714. $values[$form_details['object_field_name']] = $current_id;
  715. }
  716. if ($has_rank) {
  717. // Ensure that the rank is Set & Current
  718. $rank_select = chado_get_table_max_rank(
  719. $relationship_table,
  720. array(
  721. $form_details['subject_field_name'] => $values['subject_id'],
  722. 'type_id' => $values['type_id'],
  723. $form_details['object_field_name'] => $values['object_id'],
  724. )
  725. );
  726. $values['rank'] = $rank_select + 1;
  727. }
  728. // add relationship
  729. $success_link = chado_insert_record(
  730. $relationship_table,
  731. $values
  732. );
  733. }
  734. }
  735. }
  736. }
  737. /**
  738. * Handles autocomplete for subject & object id
  739. *
  740. * @param $string
  741. * The part of the string already typed in the textfield
  742. *
  743. * @ingroup tripal_core
  744. */
  745. function chado_add_node_form_relationships_name_to_id_callback($base_table, $name_field, $string) {
  746. $matches = array();
  747. $base_key = $base_table.'_id';
  748. $result = db_select('chado.'.$base_table, 'b')
  749. ->fields('b', array($base_key, $name_field))
  750. ->condition($name_field, '%' . db_like($string) . '%', 'LIKE')
  751. ->execute();
  752. // save the query to matches
  753. foreach ($result as $row) {
  754. $key = '('.$row->{$base_key}.') '.substr($row->{$name_field},0,50) . '...';
  755. $matches[$key] = check_plain($row->{$name_field});
  756. }
  757. // return for JS
  758. drupal_json_output($matches);
  759. }