tripal_core.chado_nodes.properties.api.inc 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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. // Add defaults into form_state to be used elsewhere
  321. $form['properties']['property_table']['details'] = array(
  322. '#type' => 'hidden',
  323. '#value' => serialize($details)
  324. );
  325. /* Properties can come to us in two ways:
  326. * 1) As entries in the $details['default_properties'] option
  327. *
  328. * 2) In the form state in the $form_state['chado_properties']. Data is in this field
  329. * when an AJAX call updates the form state or a validation error.
  330. *
  331. * 3) Directly from the database if the record already has properties associated. This
  332. * data is only used the first time the form is loaded. On AJAX calls or validation
  333. * errors the fields on the form are populated from the $form_state['chado_properties']
  334. * entry.
  335. */
  336. if (isset($form_state['chado_properties'])) {
  337. $existing_properties = $form_state['chado_properties'];
  338. }
  339. else {
  340. // build the SQL for extracting properties already assigned to this record
  341. $sql_args = array();
  342. $sql_args[':chado_id'] = $details['chado_id'];
  343. if (array_key_exists('cv_name', $details)) {
  344. $cv_where = "CV.name = :cvname";
  345. $sql_args[':cvname'] = $details['cv_name'];
  346. }
  347. elseif (array_key_exists('cv_id', $details)) {
  348. $cv_where = "CV.cv_id = :cvid";
  349. $sql_args[':cvid'] = $details['cv_id'];
  350. }
  351. $existing_properties = chado_query(
  352. "SELECT
  353. PP.".$details['property_table']."_id property_id,
  354. CVT.cvterm_id as type_id,
  355. CVT.name as type_name,
  356. CVT.definition,
  357. PP.value,
  358. PP.rank
  359. FROM {" . $details['property_table'] . "} PP
  360. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = PP.type_id
  361. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  362. WHERE
  363. PP." . $details['chado_id_field'] . " = :chado_id AND
  364. $cv_where
  365. ORDER BY CVT.name, PP.rank", $sql_args)->fetchAll();
  366. // next add in any default properties
  367. if (array_key_exists('default_properties', $details)) {
  368. // next iterate through each of the default properties and create a new
  369. // stdClass array that contains the fields needed.
  370. foreach ($details['default_properties'] as $property) {
  371. $new_prop = new stdClass();
  372. $new_prop->type_id = $property['cvterm']->cvterm_id;
  373. $new_prop->type_name = $property['cvterm']->name;
  374. $new_prop->definition = $property['cvterm']->definition;
  375. $new_prop->value = $property['value'];
  376. $new_prop->property_id = 'TEMP' . uniqid();
  377. $new_prop->rank = 'TEMP' . uniqid();
  378. $existing_properties[] = $new_prop;
  379. }
  380. }
  381. }
  382. /* The format of the $existing_properties array is either:
  383. *
  384. * From the chado_properties array:
  385. * $form_state['chado_properties'] = array(
  386. * '[type_id]-[rank]' => array(
  387. * 'type_id' => [the cvterm.cvterm_id value]
  388. * 'type_name' => [the cvterm.name value]
  389. * 'property_id' => [the property.property_id value, or temporary value if it doesn't yet exist],
  390. * 'value' => [the BASEprop.value value],
  391. * 'rank' => [the BASEprop.rank value or NULL if not saved yet],
  392. * ),
  393. * );
  394. *
  395. * OR
  396. * Populated from the database:
  397. * $existing_property = array(
  398. * 0 => array(
  399. * 'property_id' => [the property.property_id value],
  400. * 'type_id' => [the cvterm.cvterm_id value]
  401. * 'type_name' => [the cvterm.name value]
  402. * 'value' => [the BASEprop.value value],
  403. * 'rank' => [the BASEprop.rank value],
  404. * ),
  405. * );
  406. *
  407. * NOTE: The main difference is the key
  408. *
  409. * Loop on the array elements of the $existing_properties array and add
  410. * an element to the form for each one as long as it's also in the
  411. * $properties_options array.
  412. */
  413. $num_properties = 0;
  414. foreach ($existing_properties as $property) {
  415. if (array_key_exists($property->type_id, $property_options)) {
  416. $num_properties++;
  417. $form['properties']['property_table'][$property->type_id]['#type'] = 'markup';
  418. $form['properties']['property_table'][$property->type_id]['#value'] = '';
  419. $form['properties']['property_table'][$property->type_id][$property->property_id]['#type'] = 'markup';
  420. $form['properties']['property_table'][$property->type_id][$property->property_id]['#value'] = '';
  421. $form['properties']['property_table'][$property->type_id][$property->property_id]['#attributes'] = array(
  422. 'class' => array('property', 'saved')
  423. );
  424. // Determine whether this property is unsaved or not.
  425. // We can tell this by looking at the property_id: if it's not
  426. // saved yet we will have entered a TEMP###.
  427. if (preg_match('/^TEMP/', $property->property_id)) {
  428. $form['properties']['property_table'][$property->type_id][$property->property_id]['#attributes'] = array(
  429. 'class' => array('property', 'unsaved')
  430. );
  431. }
  432. $form['properties']['property_table'][$property->type_id][$property->property_id]['prop_type_id'] = array(
  433. '#type' => 'hidden',
  434. '#value' => $property->type_id
  435. );
  436. $form['properties']['property_table'][$property->type_id][$property->property_id]['prop_value'] = array(
  437. '#type' => 'hidden',
  438. '#value' => $property->value
  439. );
  440. $form['properties']['property_table'][$property->type_id][$property->property_id]['prop_rank'] = array(
  441. '#type' => 'hidden',
  442. '#value' => $property->rank
  443. );
  444. $form['properties']['property_table'][$property->type_id][$property->property_id]['property_id'] = array(
  445. '#type' => 'hidden',
  446. '#value' => $property->property_id
  447. );
  448. $form['properties']['property_table'][$property->type_id][$property->property_id]['type'] = array(
  449. '#type' => 'markup',
  450. '#markup' => $property->type_name
  451. );
  452. // If a definition is available we want to add that to the type column
  453. // to make it easier for users to determine what an added property means.
  454. if (isset($property->definition)) {
  455. $form['properties']['property_table'][$property->type_id][$property->property_id]['type']['#markup'] = $property->type_name . '<br><i>' . $property->definition . '</i>';
  456. }
  457. $form['properties']['property_table'][$property->type_id][$property->property_id]['value'] = array(
  458. '#type' => 'markup',
  459. '#markup' => $property->value,
  460. );
  461. $form['properties']['property_table'][$property->type_id][$property->property_id]['rank'] = array(
  462. '#type' => 'markup',
  463. '#markup' => $property->rank
  464. );
  465. // remove button
  466. $form['properties']['property_table'][$property->type_id][$property->property_id]['property_action'] = array(
  467. '#type' => 'submit',
  468. '#value' => t('Remove'),
  469. '#name' => "properties_remove-".$property->type_id.'-'.$property->property_id,
  470. '#ajax' => array(
  471. 'callback' => "chado_add_node_form_subtable_ajax_update",
  472. 'wrapper' => 'tripal-generic-edit-properties-table',
  473. 'effect' => 'fade',
  474. 'method' => 'replace',
  475. 'prevent' => 'click'
  476. ),
  477. // When this button is clicked, the form will be validated and submitted.
  478. // Therefore, we set custom submit and validate functions to override the
  479. // default node form submit. In the validate function we validate only the
  480. // property fields and in the submit we remove the indicated property
  481. // from the chado_properties array. In order to keep validate errors
  482. // from the node form validate and Drupal required errors for non-property fields
  483. // preventing the user from removing properties we set the #limit_validation_errors below
  484. '#validate' => array('chado_add_node_form_subtables_remove_button_validate'),
  485. '#submit' => array('chado_add_node_form_subtables_remove_button_submit'),
  486. // Limit the validation of the form upon clicking this button to the property_table tree
  487. // No other fields will be validated (ie: no fields from the main form or any other api
  488. // added form).
  489. '#limit_validation_errors' => array(
  490. array('property_table') // Validate all fields within $form_state['values']['property_table']
  491. ),
  492. );
  493. }
  494. }
  495. // Quickly add a hidden field stating how many properties are currently added.
  496. $form['properties']['num_properties'] = array(
  497. '#type' => 'hidden',
  498. '#value' => $num_properties,
  499. '#attributes' => array('class' => 'num-properties')
  500. );
  501. // Form elements for adding a new property
  502. //---------------------------------------------
  503. $form['properties']['property_table']['new'] = array(
  504. '#type' => 'markup',
  505. '#prefix' => '<span class="addtl-properties-add-new-property">',
  506. '#suffix' => '</span>'
  507. );
  508. // get the value selected (only works on AJAX call) and print the
  509. // description
  510. $type_desc = '';
  511. if (isset($form_state['input']['property_table']['new']['type'])) {
  512. $new_type_id = $form_state['input']['property_table']['new']['type'];
  513. $new_term = tripal_get_cvterm(array('cvterm_id' => $new_type_id));
  514. if ($new_term) {
  515. $type_desc = $new_term->definition;
  516. }
  517. }
  518. $form['properties']['property_table']['new']['type'] = array(
  519. '#type' => 'select',
  520. '#options' => $property_options, // Set at top of form
  521. '#prefix' => '<span id="tripal-generic-edit-properties-new-desc">',
  522. '#suffix' => '<i>' . $type_desc . '</i></span>',
  523. '#ajax' => array(
  524. 'callback' => "chado_add_node_form_properties_ajax_desc",
  525. 'wrapper' => 'tripal-generic-edit-properties-new-desc',
  526. 'effect' => 'fade',
  527. 'method' => 'replace',
  528. ),
  529. );
  530. $form['properties']['property_table']['new']['value'] = array(
  531. '#type' => 'textarea',
  532. '#rows' => 2,
  533. );
  534. // add button
  535. $form['properties']['property_table']['new']['property_action'] = array(
  536. '#type' => 'submit',
  537. '#value' => t('Add'),
  538. '#name' => "properties-add",
  539. '#ajax' => array(
  540. 'callback' => "chado_add_node_form_subtable_ajax_update",
  541. 'wrapper' => 'tripal-generic-edit-properties-table',
  542. 'effect' => 'fade',
  543. 'method' => 'replace',
  544. 'prevent' => 'click'
  545. ),
  546. // When this button is clicked, the form will be validated and submitted.
  547. // Therefore, we set custom submit and validate functions to override the
  548. // default node form submit. In the validate function we validate only the
  549. // additional property fields and in the submit we add them to the chado_properties
  550. // array. In order to keep validate errors from the node form validate and Drupal
  551. // required errors for non-property fields preventing the user from adding properties we
  552. // set the #limit_validation_errors below
  553. '#validate' => array('chado_add_node_form_subtables_add_button_validate'),
  554. '#submit' => array('chado_add_node_form_subtables_add_button_submit'),
  555. // Limit the validation of the form upon clicking this button to the property_table tree
  556. // No other fields will be validated (ie: no fields from the main form or any other api
  557. // added form).
  558. '#limit_validation_errors' => array(
  559. array('property_table') // Validate all fields within $form_state['values']['property_table']
  560. )
  561. );
  562. $form['properties']['admin_message'] = array(
  563. '#type' => 'markup',
  564. '#markup' => $tripal_message
  565. );
  566. }
  567. /**
  568. * Validate the user input for creating a new property
  569. * Called by the add button in chado_add_node_form_properties
  570. *
  571. * @ingroup tripal_core
  572. */
  573. function chado_add_node_form_properties_add_button_validate($form, &$form_state) {
  574. // Ensure the type_id is supplied & Valid
  575. $cvterm = chado_select_record(
  576. 'cvterm',
  577. array('cvterm_id', 'name', 'definition'),
  578. array('cvterm_id' => $form_state['values']['property_table']['new']['type'])
  579. );
  580. if (!isset($cvterm[0])) {
  581. form_set_error('property_table][new][cvterm', 'Please select a property type before attempting to add a new property.');
  582. }
  583. else {
  584. $form_state['values']['property_table']['new']['type_name'] = $cvterm[0]->name;
  585. $form_state['values']['property_table']['new']['definition'] = $cvterm[0]->definition;
  586. }
  587. // Ensure value is supplied
  588. if (empty($form_state['values']['property_table']['new']['value'])) {
  589. form_set_error('property_table][new][value','You must enter the property value before attempting to add a new property.');
  590. }
  591. }
  592. /**
  593. * Called by the add button in chado_add_node_form_properties
  594. *
  595. * Create an array of properties in the form state. This array will then be
  596. * used to rebuild the form in subsequent builds
  597. *
  598. * @ingroup tripal_core
  599. */
  600. function chado_add_node_form_properties_add_button_submit($form, &$form_state) {
  601. $details = unserialize($form_state['values']['property_table']['details']);
  602. // if the chado_additional_properties array is not set then this is the first time modifying the
  603. // property table. this means we need to include all the properties from the db
  604. if (!isset($form_state['chado_properties'])) {
  605. chado_add_node_form_properties_create_property_formstate_array($form, $form_state);
  606. }
  607. // get details for the new property
  608. $property = array(
  609. 'type_id' => $form_state['values']['property_table']['new']['type'],
  610. 'type_name' => $form_state['values']['property_table']['new']['type_name'],
  611. 'definition' => $form_state['values']['property_table']['new']['definition'],
  612. 'property_id' => 'TEMP' . uniqid(),
  613. 'value' => $form_state['values']['property_table']['new']['value'],
  614. 'rank' => 'TEMP' . uniqid(),
  615. );
  616. $key = $property['type_id'] . '-' . $property['property_id'];
  617. $form_state['chado_properties'][$key] = (object) $property;
  618. // we don't want the new element to pick up the values from the previous element so wipe them out
  619. unset($form_state['input']['property_table']['new']['type']);
  620. unset($form_state['input']['property_table']['new']['type_name']);
  621. unset($form_state['input']['property_table']['new']['definition']);
  622. unset($form_state['input']['property_table']['new']['value']);
  623. }
  624. /**
  625. * Called by the many remove buttons in chado_add_node_form_properties
  626. *
  627. * @ingroup tripal_core
  628. */
  629. function chado_add_node_form_properties_remove_button_validate($form, &$form_state) {
  630. // No validation needed.
  631. }
  632. /**
  633. * Remove the correct property from the form
  634. * Called by the many remove buttons in chado_add_node_form_properties
  635. *
  636. * @ingroup tripal_core
  637. */
  638. function chado_add_node_form_properties_remove_button_submit(&$form, &$form_state) {
  639. // if the chado_properties array is not set then this is the first time modifying the
  640. // property table. this means we need to include all the properties from the db
  641. if (!isset($form_state['chado_properties'])) {
  642. chado_add_node_form_properties_create_property_formstate_array($form, $form_state);
  643. }
  644. // remove the specified property from the form property table
  645. if(preg_match('/properties_remove-([^-]+-[^-]+)/',$form_state['triggering_element']['#name'],$match)) {
  646. $key = $match[1];
  647. if (array_key_exists($key, $form_state['chado_properties'])) {
  648. unset($form_state['chado_properties'][$key]);
  649. }
  650. }
  651. }
  652. function chado_add_node_form_properties_ajax_desc($form, $form_state) {
  653. return $form['properties']['property_table']['new']['type'];
  654. }
  655. /**
  656. * Creates an array in form_state containing the existing properties. This array is
  657. * then modified by the add/remove buttons and used as a source for rebuilding the form.
  658. * This function get's called at each button (add and remove) button submits the first
  659. * time one of the button's is clicked to instantiates the $form_state['chado_properties'] array
  660. *
  661. * $form_state['chado_properties'] = array(
  662. * '[type_id]-[rank]' => array(
  663. * 'type_id' => [the cvterm.cvterm_id value]
  664. * 'type_name' => [the cvterm.name value]
  665. * 'property_id' => [the property.property_id value, or NULL if it doesn't yet exist],
  666. * 'value' => [the BASEprop.value value],
  667. * 'rank' => [the BASEprop.rank value],
  668. * ),
  669. * );
  670. *
  671. * @ingroup tripal_core
  672. */
  673. function chado_add_node_form_properties_create_property_formstate_array($form, &$form_state) {
  674. $form_state['chado_properties'] = array();
  675. foreach (element_children($form['properties']['property_table']) as $type_id) {
  676. if ($type_id != 'new') {
  677. foreach (element_children($form['properties']['property_table'][$type_id]) as $property_id) {
  678. $element = $form['properties']['property_table'][$type_id][$property_id];
  679. $property = array(
  680. 'type_id' => $element['prop_type_id']['#value'],
  681. 'type_name' => $element['type']['#markup'],
  682. 'property_id' => $element['property_id']['#value'],
  683. 'value' => $element['value']['#markup'],
  684. 'rank' => $element['rank']['#markup']
  685. );
  686. $key = $property['type_id'] . '-' . $property['property_id'];
  687. $form_state['chado_properties'][$key] = (object) $property;
  688. }
  689. }
  690. }
  691. }
  692. /**
  693. * Function to theme the add/remove properties form into a table
  694. *
  695. * @ingroup tripal_chado_node_api
  696. */
  697. function theme_chado_add_node_form_properties($variables) {
  698. $element = $variables['element'];
  699. $header = array(
  700. 'type' => array('data' => t('Type'), 'width' => '30%'),
  701. 'value' => array('data' => t('Value'), 'width' => '50%'),
  702. 'property_action' => array('data' => t('Actions'),'width' => '20%'),
  703. );
  704. $rows = array();
  705. foreach (element_children($element) as $type_id) {
  706. if ($type_id == 'new') {
  707. $row = array();
  708. $row['data'] = array();
  709. foreach ($header as $fieldname => $title) {
  710. $row['data'][] = drupal_render($element[$type_id][$fieldname]);
  711. }
  712. $rows[] = $row;
  713. }
  714. else {
  715. foreach (element_children($element[$type_id]) as $version) {
  716. $row = array();
  717. $row['data'] = array();
  718. $row['class'] = $element[$type_id][$version]['#attributes']['class'];
  719. foreach ($header as $fieldname => $title) {
  720. $row['data'][] = drupal_render($element[$type_id][$version][$fieldname]);
  721. }
  722. $rows[] = $row;
  723. }
  724. }
  725. }
  726. return theme('table', array(
  727. 'header' => $header,
  728. 'rows' => $rows
  729. ));
  730. }
  731. /**
  732. * This function is used in a hook_insert, hook_update for a node form
  733. * when the chado node properties form has been added to the form. It retrieves all of the properties
  734. * and returns them in an array of the format:
  735. *
  736. * $dbxefs[<type_id>][<rank>] = <value>
  737. *
  738. * This array can then be used for inserting or updating properties
  739. *
  740. * @param $node
  741. *
  742. * @return
  743. * A property array
  744. *
  745. * @ingroup tripal_chado_node_api
  746. */
  747. function chado_retrieve_node_form_properties($node) {
  748. $properties = array();
  749. if (isset($node->property_table)) {
  750. foreach ($node->property_table as $type_id => $elements) {
  751. if ($type_id != 'new' AND $type_id != 'details') {
  752. foreach ($elements as $property_id => $element) {
  753. $properties[$type_id][$element['prop_rank']] = $element['prop_value'];
  754. }
  755. }
  756. }
  757. }
  758. return $properties;
  759. }
  760. /**
  761. * This function is used in hook_insert or hook_update and handles inserting of any new
  762. * properties
  763. *
  764. * @param $node
  765. * The node passed into hook_insert & hook_update
  766. * @param $details
  767. * - property_table: the name of the _property linking table (ie: feature_property)
  768. * - base_table: the name of the base table (ie: feature)
  769. * - foreignkey_name: the name of the foreign key used to link to the node content (ie: feature_id)
  770. * - foreignkey_value: the value of the foreign key (ie: 445, if there exists a feature where feature_id=445)
  771. * @param $retrieved_properties
  772. * An array of properties from chado_retrieve_node_form_properties($node). This can be used if you need
  773. * special handling for some of the properties (See FeatureMap chado_featuremap_insert for an example)
  774. *
  775. * @ingroup tripal_chado_node_api
  776. */
  777. function chado_update_node_form_properties($node, $details, $retrieved_properties = FALSE) {
  778. $details['foreignkey_value'] = (isset($details['foreignkey_value'])) ? $details['foreignkey_value'] : 0;
  779. if (isset($node->property_table) AND ($details['foreignkey_value'] > 0)) {
  780. // First remove existing property links
  781. chado_delete_record($details['property_table'], array($details['foreignkey_name'] => $details['foreignkey_value']));
  782. // Add back in property links and insert properties as needed
  783. if ($retrieved_properties) {
  784. $properties = $retrieved_properties;
  785. }
  786. else {
  787. $properties = chado_retrieve_node_form_properties($node);
  788. }
  789. foreach ($properties as $type_id => $ranks) {
  790. foreach ($ranks as $rank => $value) {
  791. if (preg_match('/^TEMP/', $rank)) {
  792. $rank = chado_get_table_max_rank(
  793. $details['property_table'],
  794. array(
  795. $details['foreignkey_name'] => $details['foreignkey_value'],
  796. 'type_id' => $type_id
  797. )
  798. );
  799. $rank = strval($rank + 1);
  800. }
  801. $success = chado_insert_record(
  802. $details['property_table'],
  803. array(
  804. $details['foreignkey_name'] => $details['foreignkey_value'],
  805. 'type_id' => $type_id,
  806. 'value' => $value,
  807. 'rank' => $rank
  808. )
  809. );
  810. if (!$success) {
  811. tripal_report_error('tripal_' . $details['base_table'], TRIPAL_ERROR,
  812. $details['base_table'] . ' Insert: Unable to insert property type_id %cvterm with value %value.',
  813. array('%cvterm' => $type_id, '%value' => $value));
  814. }
  815. }
  816. }
  817. }
  818. }