tripal_core.chado_nodes.relationships.api.inc

API to manage the chado _relationship table for various Tripal Node Types

How To Use:


 function chado_example_form($form, &$form_state) {

   // Default values for form elements can come in the following ways:
   //
   // 1) as elements of the $node object.  This occurs when editing an existing node
   // 2) in the $form_state['values'] array which occurs on a failed validation or
   //    ajax callbacks when the ajax call originates from non-submit fields other
   //    than button
   // 3) in the $form_state['input'] array which occurs on ajax callbacks from submit
   //    form elements (e.g. buttons) and the form is being rebuilt but has not yet
   //    been validated
   //
   // The reference elements added by this function do use AJAX calls from buttons,
   // therefore, it is important to check for form values in the $form_state['values']
   // for case #2 above, and in the $form_state['input'] for case #3.
   // See the chado analysis node form for an example.


   // Next, add in all the form array definition particular to your node type

   // To add in the relationship form elements, you first need to prepare the arguments
   // for the function call.

   $details = array(
     'relationship_table' => 'example_relationship',    // the name of the table linking additional dbxrefs to this node
     'base_table' => 'example',                         // the name of the chado table this node links to
     'base_foreign_key' => 'example_id',                // key to link to the chado content created by this node
     'base_key_value' => $example_id,                   // the value of the above key
     'fieldset_title' => 'Relationships',               // the non-translated title for this fieldset
     'additional_instructions' => ''                    // a non-stranslated string providing additional instructions
   );

   // Finally, and add the additional form elements to the form
   chado_add_node_form_relationships($form, $form_state, $details);

   return $form;
 }

 function chado_example_insert($node) {

   // if there is an example_id in the $node object then this must be a sync so
   // we can skip adding the chado_example as it is already there, although
   // we do need to proceed with the rest of the insert
   if (!property_exists($node, 'example_id')) {

     // Add record to chado example table

     // Add to any other tables needed

     // Add all relationships
     // Existing _relationship links with the current example as either the subject_id
     // or object_id will be cleared and then re-added
     chado_update_node_form_relationships(
       $node,
       'example_relationship',
       $node->example_id
     );
   }

   // Add record to chado_example linking example_id to new node

 }

 function chado_example_update($node) {


     // Update record in chado example table

     // Update any other tables needed

     // Update all additional database references
     // Existing _relationship links with the current example as either the subject_id
     // or object_id will be cleared and then re-added
     chado_update_node_form_relationships(
       $node,
       'example_relationship',
       $node->example_id
     );

   // Don't need to update chado_example linking table since niether example_id or nid can be changed in update

 }

File

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

Related topics