tripal_core.chado_nodes.properties.api.inc

API to manage the chado prop 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 chado properties form elements, you first need to prepare the arguments
   // for the function call.

   $details = array(
     'property_table' => 'example_property',      // the name of the table linking additional properties to this node
     'chado_id_field' => 'example_id',          // key to link to the chado content created by this node
     'chado_id' => $example_id,             // the value of the above key
     'cv_name' => 'example_prop_cv',              // the name of the cv governing the _prop.type_id
     'fieldset_title' => 'Additional References', // 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_properties($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 properties
     // Existing _property links will be cleared and then re-added
     tripal_api_chado_node_properties_form_update_properties(
       $node,                // the node object passed in via hook_insert()
       'example_property',   // the name of the _property linking table
       'example',            // the name of the base chado table for the node
       'example_id',         // key to link to the chado content created by this node
       $node->example_id     // value of the above key
     );
   }

   // 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 properties
     // Existing _property links will be cleared and then re-added
     tripal_api_chado_node_properties_form_update_properties(
       $node,                // the node object passed in via hook_insert()
       'example_property',   // the name of the _property linking table
       'example',            // the name of the base chado table for the node
       'example_id',         // key to link to the chado content created by this node
       $node->example_id     // value of the above key
     );

   // 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.properties.api.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * API to manage the chado prop 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 chado properties form elements, you first need to prepare the arguments
  25. // for the function call.
  26. $details = array(
  27. 'property_table' => 'example_property', // the name of the table linking additional properties to this node
  28. 'chado_id_field' => 'example_id', // key to link to the chado content created by this node
  29. 'chado_id' => $example_id, // the value of the above key
  30. 'cv_name' => 'example_prop_cv', // the name of the cv governing the _prop.type_id
  31. 'fieldset_title' => 'Additional References', // 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_properties($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 properties
  46. // Existing _property links will be cleared and then re-added
  47. tripal_api_chado_node_properties_form_update_properties(
  48. $node, // the node object passed in via hook_insert()
  49. 'example_property', // the name of the _property linking table
  50. 'example', // the name of the base chado table for the node
  51. 'example_id', // key to link to the chado content created by this node
  52. $node->example_id // value of the above key
  53. );
  54. }
  55. // Add record to chado_example linking example_id to new node
  56. }
  57. function chado_example_update($node) {
  58. // Update record in chado example table
  59. // Update any other tables needed
  60. // Update all properties
  61. // Existing _property links will be cleared and then re-added
  62. tripal_api_chado_node_properties_form_update_properties(
  63. $node, // the node object passed in via hook_insert()
  64. 'example_property', // the name of the _property linking table
  65. 'example', // the name of the base chado table for the node
  66. 'example_id', // key to link to the chado content created by this node
  67. $node->example_id // value of the above key
  68. );
  69. // Don't need to update chado_example linking table since niether example_id or nid can be changed in update
  70. }
  71. * @endcode
  72. *
  73. * @ingroup tripal_chado_node_api
  74. */
  75. /**
  76. * Provides a form for adding to BASEprop table
  77. *
  78. * @param $form
  79. * The Drupal form array into which the property form elements will be added
  80. * @param $form_state
  81. * The corresponding form_state array for the form
  82. * @param $details
  83. * An array defining details used by this form.
  84. * Required keys that are always required:
  85. * - property_table: the name of the property table (e.g.: featureprop, stockprop, etc.)
  86. * Required keys for forms that update a record.
  87. * - chado_id: the id of the record to which properties will be associated (e.g.: if a
  88. * feature has a feature_id of 999 and we want to associate properties for that feature
  89. * then the chado_id option should be 999)
  90. * Require ONE of the following to identify the controlled vocabulary containing the properties to use:
  91. * - cv_id: the unique key from the cv table
  92. * - cv_name: the cv.name field uniquely identifying the controlled vocabulary
  93. * Optional keys include:
  94. * - chado_id_field: the foreign key field that links properties to the
  95. * chado_id record. If this value is not specified it is determined using the
  96. * traditional Chado naming scheme for property tables.
  97. * - additional_instructions: provides additional instructions to the user
  98. * for dealing with the property elements. These instructions are appended
  99. * to the default instructions
  100. * - fieldset_title: An alternate name for the fieldset in which the properties
  101. * form is placed. By default the title is 'Properties'.
  102. * - default_properties: An array of properties used to initialize the
  103. * properties form. Each property shoudl be represented as an array with
  104. * the following keys and values:
  105. * 'cvterm': The cvterm object for the property type
  106. * 'value': The property value
  107. * - select_options: an array of terms to use for the drop down select box.
  108. * this array will be used rather than populating the drop down with terms
  109. * from the named vocabulary. The array must have keys with the cvterm_id
  110. * and values with the cvterm name.
  111. *
  112. * @ingroup tripal_chado_node_api
  113. */
  114. function chado_add_node_form_properties(&$form, &$form_state, $details) {
  115. // Set defaults for optional fields
  116. if (!array_key_exists('fieldset_title', $details)){
  117. $details['fieldset_title'] = 'Properties';
  118. }
  119. if (!array_key_exists('additional_instructions', $details)){
  120. $details['additional_instructions'] = '';
  121. };
  122. if (!array_key_exists('default_properties', $details)){
  123. $details['default_properties'] = array();
  124. };
  125. if (!is_array($details['default_properties'])) {
  126. drupal_set_message("The 'default_properties' option must be an array", "error");
  127. tripal_report_error('tcprops_form', TRIPAL_ERROR,
  128. "The 'default_properties' option must be an array",
  129. array());
  130. return;
  131. }
  132. // make sure the property table exists before proceeding.
  133. if (!chado_table_exists($details['property_table'])) {
  134. drupal_set_message("Cannot add property elements to the form. The property table, '" .
  135. $details['property_table'] . "', does not exists", "error");
  136. tripal_report_error('tcprops_form', TRIPAL_ERROR,
  137. "Cannot add property elements to the form. The property table, '%name', cannot be found.",
  138. array('%name' => $details['property_table']));
  139. return;
  140. }
  141. // if the chado_id_field is not specified then set it using the
  142. // typical chado naming scheme
  143. if (!array_key_exists('chado_id_field', $details)) {
  144. $chado_id_table = preg_replace('/prop$/', '', $details['property_table']);
  145. $chado_id_field = $chado_id_table . '_id';
  146. $details['nodetype'] = $chado_id_table;
  147. $details['chado_id_field'] = $chado_id_field;
  148. }
  149. else {
  150. $details['nodetype'] = str_replace('_id', '', $details['chado_id_field']);
  151. }
  152. // make sure the specified cv exists
  153. if (isset($details['cv_name'])) {
  154. // make sure the cv_name is real
  155. $result = chado_select_record('cv',array('cv_id'),array('name' => $details['cv_name']));
  156. if (count($result) == 0) {
  157. drupal_set_message("Cannot add property elements to the form. The CV name, '" .
  158. $details['cv_name'] . "', does not exists", "error");
  159. tripal_report_error('tcprops_form', TRIPAL_ERROR,
  160. "Cannot add property elements to the form. The CV named, '%name', cannot be found.",
  161. array('%name' => $details['cv_name']));
  162. return;
  163. }
  164. // add the cv_id option to the details array
  165. $details['cv_id'] = $result[0]->cv_id;
  166. }
  167. elseif (isset($details['cv_id'])) {
  168. // make sure the cv_id is real
  169. $result = chado_select_record('cv', array('name'), array('cv_id' => $details['cv_id']));
  170. if (count($result) == 0) {
  171. drupal_set_message("Cannot add property elements to the form. The CV ID, '" .
  172. $details['cv_id'] . "', does not exist", "error");
  173. tripal_report_error('tcprops_form', TRIPAL_ERROR,
  174. "Cannot add property elements to the form. The CV ID, '%id', cannot be found.",
  175. array('%id' => $details['cv_id']));
  176. return;
  177. }
  178. // add the cv_name option to the details array
  179. $details['cv_name'] = $result[0]->name;
  180. }
  181. else {
  182. // If we didn't get given a cv identifier, then try retrieving the default one
  183. // using the new cv defaults api
  184. $default_cv = tripal_get_default_cv($details['property_table'], 'type_id');
  185. if (!empty($default_cv)) {
  186. $details['cv_id'] = $default_cv->cv_id;
  187. $details['cv_name'] = $default_cv->name;
  188. }
  189. else {
  190. $default_form_link = l('vocabulary defaults configuration page',
  191. 'admin/tripal/chado/tripal_cv/defaults',
  192. array('attributes' => array('target' => '_blank')));
  193. $message = "There is not a default vocabulary set for Property Types. Please set one using the $default_form_link.";
  194. if (preg_match('/(\w+)_id/',$details['chado_id_field'],$matches)) {
  195. $table = $matches[1];
  196. $table = ucwords(str_replace('_',' ',$table));
  197. $message = "There is not a default vocabulary set for $table Property Types. Please set one using the $default_form_link.";
  198. }
  199. tripal_set_message($message, TRIPAL_WARNING);
  200. tripal_report_error('tcprops_form', TRIPAL_ERROR,
  201. "Please provide either a 'cv_name' or 'cv_id' as an option for adding properties to the form",
  202. array());
  203. }
  204. return;
  205. }
  206. // Get property types for the select list. If the user has provided a set
  207. // then use those, otherwise get them from the cvterm table for specified cv.
  208. if (array_key_exists('select_options', $details) and
  209. is_array($details['select_options'])) {
  210. $property_options = $details['select_options'];
  211. }
  212. // if the select options are not provided then try to get them on our own
  213. else {
  214. // if the vocabulary name is provided in the details then use that to
  215. // get the terms
  216. if (isset($details['cv_name'])) {
  217. $property_options = array();
  218. $property_options[] = 'Select a Property';
  219. $sql = "
  220. SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition, CV.cv_id as cv_id
  221. FROM {cvterm} CVT
  222. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  223. WHERE
  224. CV.name = :cv_name AND
  225. NOT CVT.is_obsolete = 1
  226. ORDER BY CVT.name ASC
  227. ";
  228. $prop_types = chado_query($sql, array(':cv_name' => $details['cv_name']));
  229. while ($prop = $prop_types->fetchObject()) {
  230. $property_options[$prop->cvterm_id] = $prop->name;
  231. }
  232. }
  233. // if the cv_id is set in the $details array then use that to get the terms
  234. elseif (isset($details['cv_id'])) {
  235. $property_options = array();
  236. $property_options[] = 'Select a Property';
  237. $sql = "
  238. SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition, CV.name as cv_name
  239. FROM {cvterm} CVT
  240. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  241. WHERE
  242. CV.cv_id = :cv_id AND
  243. NOT CVT.is_obsolete = 1
  244. ORDER BY CVT.name ASC
  245. ";
  246. $prop_types = chado_query($sql, array(':cv_id' => $details['cv_id']));
  247. while ($prop = $prop_types->fetchObject()) {
  248. $property_options[$prop->cvterm_id] = $prop->name;
  249. }
  250. }
  251. }
  252. // Tell tripal administrators how to add terms to the property types drop down.
  253. if (empty($property_options)) {
  254. $tripal_message = tripal_set_message(
  255. t('There are currently no property types! To add properties to the drop
  256. down list, you need to <a href="@cvtermlink">add a controlled vocabulary term</a>
  257. to the %cv_name controlled vocabulary.',
  258. array(
  259. '%cv_name' => $details['cv_name'],
  260. '@cvtermlink' => url('admin/tripal/chado/tripal_cv/cv/' . $details['cv_id'] . '/cvterm/add')
  261. )
  262. ),
  263. TRIPAL_NOTICE,
  264. array('return_html' => TRUE)
  265. );
  266. }
  267. else {
  268. $tripal_message = tripal_set_message(
  269. t('To add additional properties to the drop down list, you need to <a href="@cvtermlink">add
  270. a controlled vocabulary term</a> to the %cv_name controlled vocabulary.',
  271. array(
  272. '%cv_name' => $details['cv_name'],
  273. '@cvtermlink' => url('admin/tripal/chado/tripal_cv/cv/' . $details['cv_id'] . '/cvterm/add')
  274. )
  275. ),
  276. TRIPAL_INFO,
  277. array('return_html' => TRUE)
  278. );
  279. }
  280. // Group all of the chado node api fieldsets into vertical tabs.
  281. $form['chado_node_api'] = array(
  282. '#type' => 'vertical_tabs',
  283. '#attached' => array(
  284. 'css' => array(
  285. 'chado-node-api' => drupal_get_path('module', 'tripal_core') . '/theme/css/chado_node_api.css',
  286. ),
  287. ),
  288. );
  289. // the fieldset of the property elements
  290. $instructions = 'To add properties of the current %nodetype, select the type of
  291. information from the drop-down below and enter the information in the text box before
  292. clicking "Add". To remove incorrect information, click the "Remove" button.
  293. Note: you cannot edit previously added information but instead need to
  294. remove and re-add it.';
  295. $form['properties'] = array(
  296. '#type' => 'fieldset',
  297. '#title' => t($details['fieldset_title']),
  298. '#description' => t('<p><strong>Additional information about a
  299. %nodetype.</strong></p><p>'. $instructions . $details['additional_instructions'] . '</p>', array('%nodetype' => $details['nodetype'])) ,
  300. '#collapsible' => TRUE,
  301. '#collapsed' => TRUE,
  302. '#group' => 'chado_node_api',
  303. '#weight' => 8,
  304. '#attributes' => array('class' => array('chado-node-api','properties')),
  305. '#attached' => array(
  306. 'js' => array(
  307. 'chado-node-api-vertical-tabs' => drupal_get_path('module', 'tripal_core') . '/theme/js/chadoNodeApi_updateVerticalTabSummary.js',
  308. ),
  309. ),
  310. );
  311. // this form element is a tree, so that we don't puke all of the values into then node variable
  312. // it is set as a tree, and keeps them in the $form_state['values']['property_table'] heading.
  313. $form['properties']['property_table'] = array(
  314. '#type' => 'markup',
  315. '#tree' => TRUE,
  316. '#prefix' => '<div id="tripal-generic-edit-properties-table">',
  317. '#suffix' => '</div>',
  318. '#theme' => 'chado_node_properties_form_table'
  319. );
  320. // We need to provide feedback to the user that changes made
  321. // are not saved until the node is saved.
  322. $form['properties']['property_table']['save_warning'] = array(
  323. '#type' => 'markup',
  324. '#prefix' => '<div id="property-save-warning" class="messages warning" style="display:none;">',
  325. '#suffix' => '</div>',
  326. '#markup' => '* The changes to these properties will not be saved until the
  327. "Save" button at the bottom of this form is clicked. <span class="specific-changes"></span>',
  328. '#attached' => array(
  329. 'js' => array(
  330. 'chado-node-api-unsaved' => drupal_get_path('module', 'tripal_core') . '/theme/js/chadoNodeApi_unsavedNotify.js',
  331. ),
  332. ),
  333. );
  334. // Add defaults into form_state to be used elsewhere
  335. $form['properties']['property_table']['details'] = array(
  336. '#type' => 'hidden',
  337. '#value' => serialize($details)
  338. );
  339. /* Properties can come to us in two ways:
  340. * 1) As entries in the $details['default_properties'] option
  341. *
  342. * 2) In the form state in the $form_state['chado_properties']. Data is in this field
  343. * when an AJAX call updates the form state or a validation error.
  344. *
  345. * 3) Directly from the database if the record already has properties associated. This
  346. * data is only used the first time the form is loaded. On AJAX calls or validation
  347. * errors the fields on the form are populated from the $form_state['chado_properties']
  348. * entry.
  349. */
  350. if (isset($form_state['chado_properties'])) {
  351. $existing_properties = $form_state['chado_properties'];
  352. }
  353. else {
  354. // build the SQL for extracting properties already assigned to this record
  355. $sql_args = array();
  356. $sql_args[':chado_id'] = $details['chado_id'];
  357. if (array_key_exists('cv_name', $details)) {
  358. $cv_where = "CV.name = :cvname";
  359. $sql_args[':cvname'] = $details['cv_name'];
  360. }
  361. elseif (array_key_exists('cv_id', $details)) {
  362. $cv_where = "CV.cv_id = :cvid";
  363. $sql_args[':cvid'] = $details['cv_id'];
  364. }
  365. $existing_properties = chado_query(
  366. "SELECT
  367. PP.".$details['property_table']."_id property_id,
  368. CVT.cvterm_id as type_id,
  369. CVT.name as type_name,
  370. CVT.definition,
  371. PP.value,
  372. PP.rank
  373. FROM {" . $details['property_table'] . "} PP
  374. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = PP.type_id
  375. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  376. WHERE
  377. PP." . $details['chado_id_field'] . " = :chado_id AND
  378. $cv_where
  379. ORDER BY CVT.name, PP.rank", $sql_args)->fetchAll();
  380. // next add in any default properties
  381. if (array_key_exists('default_properties', $details)) {
  382. // next iterate through each of the default properties and create a new
  383. // stdClass array that contains the fields needed.
  384. foreach ($details['default_properties'] as $property) {
  385. $new_prop = new stdClass();
  386. $new_prop->type_id = $property['cvterm']->cvterm_id;
  387. $new_prop->type_name = $property['cvterm']->name;
  388. $new_prop->definition = $property['cvterm']->definition;
  389. $new_prop->value = $property['value'];
  390. $new_prop->property_id = 'TEMP' . uniqid();
  391. $new_prop->rank = 'TEMP' . uniqid();
  392. $existing_properties[] = $new_prop;
  393. }
  394. }
  395. }
  396. /* The format of the $existing_properties array is either:
  397. *
  398. * From the chado_properties array:
  399. * $form_state['chado_properties'] = array(
  400. * '[type_id]-[rank]' => array(
  401. * 'type_id' => [the cvterm.cvterm_id value]
  402. * 'type_name' => [the cvterm.name value]
  403. * 'property_id' => [the property.property_id value, or temporary value if it doesn't yet exist],
  404. * 'value' => [the BASEprop.value value],
  405. * 'rank' => [the BASEprop.rank value or NULL if not saved yet],
  406. * ),
  407. * );
  408. *
  409. * OR
  410. * Populated from the database:
  411. * $existing_property = array(
  412. * 0 => array(
  413. * 'property_id' => [the property.property_id value],
  414. * 'type_id' => [the cvterm.cvterm_id value]
  415. * 'type_name' => [the cvterm.name value]
  416. * 'value' => [the BASEprop.value value],
  417. * 'rank' => [the BASEprop.rank value],
  418. * ),
  419. * );
  420. *
  421. * NOTE: The main difference is the key
  422. *
  423. * Loop on the array elements of the $existing_properties array and add
  424. * an element to the form for each one as long as it's also in the
  425. * $properties_options array.
  426. */
  427. $num_properties = 0;
  428. foreach ($existing_properties as $property) {
  429. if (array_key_exists($property->type_id, $property_options)) {
  430. $num_properties++;
  431. $form['properties']['property_table'][$property->type_id]['#type'] = 'markup';
  432. $form['properties']['property_table'][$property->type_id]['#value'] = '';
  433. $form['properties']['property_table'][$property->type_id][$property->property_id]['#type'] = 'markup';
  434. $form['properties']['property_table'][$property->type_id][$property->property_id]['#value'] = '';
  435. $form['properties']['property_table'][$property->type_id][$property->property_id]['#attributes'] = array(
  436. 'class' => array('property', 'saved')
  437. );
  438. // Determine whether this property is unsaved or not.
  439. // We can tell this by looking at the property_id: if it's not
  440. // saved yet we will have entered a TEMP###.
  441. if (preg_match('/^TEMP/', $property->property_id)) {
  442. $form['properties']['property_table'][$property->type_id][$property->property_id]['#attributes'] = array(
  443. 'class' => array('property', 'unsaved')
  444. );
  445. }
  446. $form['properties']['property_table'][$property->type_id][$property->property_id]['prop_type_id'] = array(
  447. '#type' => 'hidden',
  448. '#value' => $property->type_id
  449. );
  450. $form['properties']['property_table'][$property->type_id][$property->property_id]['prop_value'] = array(
  451. '#type' => 'hidden',
  452. '#value' => $property->value
  453. );
  454. $form['properties']['property_table'][$property->type_id][$property->property_id]['prop_rank'] = array(
  455. '#type' => 'hidden',
  456. '#value' => $property->rank
  457. );
  458. $form['properties']['property_table'][$property->type_id][$property->property_id]['property_id'] = array(
  459. '#type' => 'hidden',
  460. '#value' => $property->property_id
  461. );
  462. $form['properties']['property_table'][$property->type_id][$property->property_id]['type'] = array(
  463. '#type' => 'markup',
  464. '#markup' => $property->type_name,
  465. '#prefix' => '<span class="row-unsaved-warning"></span>'
  466. );
  467. // If a definition is available we want to add that to the type column
  468. // to make it easier for users to determine what an added property means.
  469. if (isset($property->definition)) {
  470. $form['properties']['property_table'][$property->type_id][$property->property_id]['type']['#markup'] = $property->type_name . '<br><i>' . $property->definition . '</i>';
  471. }
  472. $form['properties']['property_table'][$property->type_id][$property->property_id]['value'] = array(
  473. '#type' => 'markup',
  474. '#markup' => $property->value,
  475. );
  476. $form['properties']['property_table'][$property->type_id][$property->property_id]['rank'] = array(
  477. '#type' => 'markup',
  478. '#markup' => $property->rank
  479. );
  480. // remove button
  481. $form['properties']['property_table'][$property->type_id][$property->property_id]['property_action'] = array(
  482. '#type' => 'submit',
  483. '#value' => t('Remove'),
  484. '#name' => "properties_remove-".$property->type_id.'-'.$property->property_id,
  485. '#ajax' => array(
  486. 'callback' => "chado_add_node_form_subtable_ajax_update",
  487. 'wrapper' => 'tripal-generic-edit-properties-table',
  488. 'effect' => 'fade',
  489. 'method' => 'replace',
  490. 'prevent' => 'click'
  491. ),
  492. // When this button is clicked, the form will be validated and submitted.
  493. // Therefore, we set custom submit and validate functions to override the
  494. // default node form submit. In the validate function we validate only the
  495. // property fields and in the submit we remove the indicated property
  496. // from the chado_properties array. In order to keep validate errors
  497. // from the node form validate and Drupal required errors for non-property fields
  498. // preventing the user from removing properties we set the #limit_validation_errors below
  499. '#validate' => array('chado_add_node_form_subtables_remove_button_validate'),
  500. '#submit' => array('chado_add_node_form_subtables_remove_button_submit'),
  501. // Limit the validation of the form upon clicking this button to the property_table tree
  502. // No other fields will be validated (ie: no fields from the main form or any other api
  503. // added form).
  504. '#limit_validation_errors' => array(
  505. array('property_table') // Validate all fields within $form_state['values']['property_table']
  506. ),
  507. );
  508. }
  509. }
  510. // Quickly add a hidden field stating how many properties are currently added.
  511. $form['properties']['num_properties'] = array(
  512. '#type' => 'hidden',
  513. '#value' => $num_properties,
  514. '#attributes' => array('class' => 'num-properties')
  515. );
  516. // Form elements for adding a new property
  517. //---------------------------------------------
  518. $form['properties']['property_table']['new'] = array(
  519. '#type' => 'markup',
  520. '#prefix' => '<span class="addtl-properties-add-new-property">',
  521. '#suffix' => '</span>'
  522. );
  523. // get the value selected (only works on AJAX call) and print the
  524. // description
  525. $type_desc = '';
  526. if (isset($form_state['input']['property_table']['new']['type'])) {
  527. $new_type_id = $form_state['input']['property_table']['new']['type'];
  528. $new_term = tripal_get_cvterm(array('cvterm_id' => $new_type_id));
  529. if ($new_term) {
  530. $type_desc = $new_term->definition;
  531. }
  532. }
  533. $form['properties']['property_table']['new']['type'] = array(
  534. '#type' => 'select',
  535. '#options' => $property_options, // Set at top of form
  536. '#prefix' => '<span id="tripal-generic-edit-properties-new-desc">',
  537. '#suffix' => '<i>' . $type_desc . '</i></span>',
  538. '#ajax' => array(
  539. 'callback' => "chado_add_node_form_properties_ajax_desc",
  540. 'wrapper' => 'tripal-generic-edit-properties-new-desc',
  541. 'effect' => 'fade',
  542. 'method' => 'replace',
  543. ),
  544. );
  545. $form['properties']['property_table']['new']['value'] = array(
  546. '#type' => 'textarea',
  547. '#rows' => 2,
  548. );
  549. // add button
  550. $form['properties']['property_table']['new']['property_action'] = array(
  551. '#type' => 'submit',
  552. '#value' => t('Add'),
  553. '#name' => "properties-add",
  554. '#ajax' => array(
  555. 'callback' => "chado_add_node_form_subtable_ajax_update",
  556. 'wrapper' => 'tripal-generic-edit-properties-table',
  557. 'effect' => 'fade',
  558. 'method' => 'replace',
  559. 'prevent' => 'click'
  560. ),
  561. // When this button is clicked, the form will be validated and submitted.
  562. // Therefore, we set custom submit and validate functions to override the
  563. // default node form submit. In the validate function we validate only the
  564. // additional property fields and in the submit we add them to the chado_properties
  565. // array. In order to keep validate errors from the node form validate and Drupal
  566. // required errors for non-property fields preventing the user from adding properties we
  567. // set the #limit_validation_errors below
  568. '#validate' => array('chado_add_node_form_subtables_add_button_validate'),
  569. '#submit' => array('chado_add_node_form_subtables_add_button_submit'),
  570. // Limit the validation of the form upon clicking this button to the property_table tree
  571. // No other fields will be validated (ie: no fields from the main form or any other api
  572. // added form).
  573. '#limit_validation_errors' => array(
  574. array('property_table') // Validate all fields within $form_state['values']['property_table']
  575. )
  576. );
  577. $form['properties']['admin_message'] = array(
  578. '#type' => 'markup',
  579. '#markup' => $tripal_message
  580. );
  581. }
  582. /**
  583. * Validate the user input for creating a new property
  584. * Called by the add button in chado_add_node_form_properties
  585. *
  586. * @ingroup tripal_core
  587. */
  588. function chado_add_node_form_properties_add_button_validate($form, &$form_state) {
  589. // Ensure the type_id is supplied & Valid
  590. $cvterm = chado_select_record(
  591. 'cvterm',
  592. array('cvterm_id', 'name', 'definition'),
  593. array('cvterm_id' => $form_state['values']['property_table']['new']['type'])
  594. );
  595. if (!isset($cvterm[0])) {
  596. form_set_error('property_table][new][cvterm', 'Please select a property type before attempting to add a new property.');
  597. }
  598. else {
  599. $form_state['values']['property_table']['new']['type_name'] = $cvterm[0]->name;
  600. $form_state['values']['property_table']['new']['definition'] = $cvterm[0]->definition;
  601. }
  602. // Ensure value is supplied
  603. if (empty($form_state['values']['property_table']['new']['value'])) {
  604. form_set_error('property_table][new][value','You must enter the property value before attempting to add a new property.');
  605. }
  606. }
  607. /**
  608. * Called by the add button in chado_add_node_form_properties
  609. *
  610. * Create an array of properties in the form state. This array will then be
  611. * used to rebuild the form in subsequent builds
  612. *
  613. * @ingroup tripal_core
  614. */
  615. function chado_add_node_form_properties_add_button_submit($form, &$form_state) {
  616. $details = unserialize($form_state['values']['property_table']['details']);
  617. // if the chado_additional_properties array is not set then this is the first time modifying the
  618. // property table. this means we need to include all the properties from the db
  619. if (!isset($form_state['chado_properties'])) {
  620. chado_add_node_form_properties_create_property_formstate_array($form, $form_state);
  621. }
  622. // get details for the new property
  623. $property = array(
  624. 'type_id' => $form_state['values']['property_table']['new']['type'],
  625. 'type_name' => $form_state['values']['property_table']['new']['type_name'],
  626. 'definition' => $form_state['values']['property_table']['new']['definition'],
  627. 'property_id' => 'TEMP' . uniqid(),
  628. 'value' => $form_state['values']['property_table']['new']['value'],
  629. 'rank' => 'TEMP' . uniqid(),
  630. );
  631. $key = $property['type_id'] . '-' . $property['property_id'];
  632. $form_state['chado_properties'][$key] = (object) $property;
  633. // we don't want the new element to pick up the values from the previous element so wipe them out
  634. unset($form_state['input']['property_table']['new']['type']);
  635. unset($form_state['input']['property_table']['new']['type_name']);
  636. unset($form_state['input']['property_table']['new']['definition']);
  637. unset($form_state['input']['property_table']['new']['value']);
  638. }
  639. /**
  640. * Called by the many remove buttons in chado_add_node_form_properties
  641. *
  642. * @ingroup tripal_core
  643. */
  644. function chado_add_node_form_properties_remove_button_validate($form, &$form_state) {
  645. // No validation needed.
  646. }
  647. /**
  648. * Remove the correct property from the form
  649. * Called by the many remove buttons in chado_add_node_form_properties
  650. *
  651. * @ingroup tripal_core
  652. */
  653. function chado_add_node_form_properties_remove_button_submit(&$form, &$form_state) {
  654. // if the chado_properties array is not set then this is the first time modifying the
  655. // property table. this means we need to include all the properties from the db
  656. if (!isset($form_state['chado_properties'])) {
  657. chado_add_node_form_properties_create_property_formstate_array($form, $form_state);
  658. }
  659. // remove the specified property from the form property table
  660. if(preg_match('/properties_remove-([^-]+-[^-]+)/',$form_state['triggering_element']['#name'],$match)) {
  661. $key = $match[1];
  662. if (array_key_exists($key, $form_state['chado_properties'])) {
  663. unset($form_state['chado_properties'][$key]);
  664. }
  665. }
  666. }
  667. function chado_add_node_form_properties_ajax_desc($form, $form_state) {
  668. return $form['properties']['property_table']['new']['type'];
  669. }
  670. /**
  671. * Creates an array in form_state containing the existing properties. This array is
  672. * then modified by the add/remove buttons and used as a source for rebuilding the form.
  673. * This function get's called at each button (add and remove) button submits the first
  674. * time one of the button's is clicked to instantiates the $form_state['chado_properties'] array
  675. *
  676. * $form_state['chado_properties'] = array(
  677. * '[type_id]-[rank]' => array(
  678. * 'type_id' => [the cvterm.cvterm_id value]
  679. * 'type_name' => [the cvterm.name value]
  680. * 'property_id' => [the property.property_id value, or NULL if it doesn't yet exist],
  681. * 'value' => [the BASEprop.value value],
  682. * 'rank' => [the BASEprop.rank value],
  683. * ),
  684. * );
  685. *
  686. * @ingroup tripal_core
  687. */
  688. function chado_add_node_form_properties_create_property_formstate_array($form, &$form_state) {
  689. $form_state['chado_properties'] = array();
  690. foreach (element_children($form['properties']['property_table']) as $type_id) {
  691. if ($type_id != 'new') {
  692. foreach (element_children($form['properties']['property_table'][$type_id]) as $property_id) {
  693. $element = $form['properties']['property_table'][$type_id][$property_id];
  694. $property = array(
  695. 'type_id' => $element['prop_type_id']['#value'],
  696. 'type_name' => $element['type']['#markup'],
  697. 'property_id' => $element['property_id']['#value'],
  698. 'value' => $element['value']['#markup'],
  699. 'rank' => $element['rank']['#markup']
  700. );
  701. $key = $property['type_id'] . '-' . $property['property_id'];
  702. $form_state['chado_properties'][$key] = (object) $property;
  703. }
  704. }
  705. }
  706. }
  707. /**
  708. * Function to theme the add/remove properties form into a table
  709. *
  710. * @ingroup tripal_chado_node_api
  711. */
  712. function theme_chado_add_node_form_properties($variables) {
  713. $element = $variables['element'];
  714. $header = array(
  715. 'type' => array('data' => t('Type'), 'width' => '30%'),
  716. 'value' => array('data' => t('Value'), 'width' => '50%'),
  717. 'property_action' => array('data' => t('Actions'),'width' => '20%'),
  718. );
  719. $rows = array();
  720. foreach (element_children($element) as $type_id) {
  721. if ($type_id == 'new') {
  722. $row = array();
  723. $row['data'] = array();
  724. foreach ($header as $fieldname => $title) {
  725. $row['data'][] = drupal_render($element[$type_id][$fieldname]);
  726. }
  727. $rows[] = $row;
  728. }
  729. else {
  730. foreach (element_children($element[$type_id]) as $version) {
  731. $row = array();
  732. $row['data'] = array();
  733. $row['class'] = $element[$type_id][$version]['#attributes']['class'];
  734. foreach ($header as $fieldname => $title) {
  735. $row['data'][] = drupal_render($element[$type_id][$version][$fieldname]);
  736. }
  737. $rows[] = $row;
  738. }
  739. }
  740. }
  741. return render($element['save_warning']) . theme('table', array(
  742. 'header' => $header,
  743. 'rows' => $rows
  744. ));
  745. }
  746. /**
  747. * This function is used in a hook_insert, hook_update for a node form
  748. * when the chado node properties form has been added to the form. It retrieves all of the properties
  749. * and returns them in an array of the format:
  750. *
  751. * $dbxefs[<type_id>][<rank>] = <value>
  752. *
  753. * This array can then be used for inserting or updating properties
  754. *
  755. * @param $node
  756. *
  757. * @return
  758. * A property array
  759. *
  760. * @ingroup tripal_chado_node_api
  761. */
  762. function chado_retrieve_node_form_properties($node) {
  763. $properties = array();
  764. if (isset($node->property_table)) {
  765. foreach ($node->property_table as $type_id => $elements) {
  766. if ($type_id != 'new' AND $type_id != 'details') {
  767. foreach ($elements as $property_id => $element) {
  768. $properties[$type_id][$element['prop_rank']] = $element['prop_value'];
  769. }
  770. }
  771. }
  772. }
  773. return $properties;
  774. }
  775. /**
  776. * This function is used in hook_insert or hook_update and handles inserting of any new
  777. * properties
  778. *
  779. * @param $node
  780. * The node passed into hook_insert & hook_update
  781. * @param $details
  782. * - property_table: the name of the _property linking table (ie: feature_property)
  783. * - base_table: the name of the base table (ie: feature)
  784. * - foreignkey_name: the name of the foreign key used to link to the node content (ie: feature_id)
  785. * - foreignkey_value: the value of the foreign key (ie: 445, if there exists a feature where feature_id=445)
  786. * @param $retrieved_properties
  787. * An array of properties from chado_retrieve_node_form_properties($node). This can be used if you need
  788. * special handling for some of the properties (See FeatureMap chado_featuremap_insert for an example)
  789. *
  790. * @ingroup tripal_chado_node_api
  791. */
  792. function chado_update_node_form_properties($node, $details, $retrieved_properties = FALSE) {
  793. $details['foreignkey_value'] = (isset($details['foreignkey_value'])) ? $details['foreignkey_value'] : 0;
  794. if (isset($node->property_table) AND ($details['foreignkey_value'] > 0)) {
  795. // First remove existing property links
  796. chado_delete_record($details['property_table'], array($details['foreignkey_name'] => $details['foreignkey_value']));
  797. // Add back in property links and insert properties as needed
  798. if ($retrieved_properties) {
  799. $properties = $retrieved_properties;
  800. }
  801. else {
  802. $properties = chado_retrieve_node_form_properties($node);
  803. }
  804. foreach ($properties as $type_id => $ranks) {
  805. foreach ($ranks as $rank => $value) {
  806. if (preg_match('/^TEMP/', $rank)) {
  807. $rank = chado_get_table_max_rank(
  808. $details['property_table'],
  809. array(
  810. $details['foreignkey_name'] => $details['foreignkey_value'],
  811. 'type_id' => $type_id
  812. )
  813. );
  814. $rank = strval($rank + 1);
  815. }
  816. $success = chado_insert_record(
  817. $details['property_table'],
  818. array(
  819. $details['foreignkey_name'] => $details['foreignkey_value'],
  820. 'type_id' => $type_id,
  821. 'value' => $value,
  822. 'rank' => $rank
  823. )
  824. );
  825. if (!$success) {
  826. tripal_report_error('tripal_' . $details['base_table'], TRIPAL_ERROR,
  827. $details['base_table'] . ' Insert: Unable to insert property type_id %cvterm with value %value.',
  828. array('%cvterm' => $type_id, '%value' => $value));
  829. }
  830. }
  831. }
  832. }
  833. }

Related topics