tripal_core_properties.api.inc 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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 properties 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 properties form elements, you first need to prepare the arguments
  25. // for the function call. One inportant argument is a list of properties that
  26. // will be made avaialble for the user to select from. You should query the
  27. // database to retrieve the applicable terms from the cvterm table and store them in an array
  28. // of where the cvterm.cvterm_id field is the key and the cvterm.name is the value.
  29. // these terms should all be from the same vocabulary.
  30. $properties = array();
  31. $properties[] = 'Select a Property';
  32. $sql = "
  33. SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition
  34. FROM {cvterm} CVT
  35. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  36. WHERE
  37. CV.name = :ontology_name AND
  38. NOT CVT.is_obsolete = 1
  39. ORDER BY CVT.name ASC
  40. ";
  41. $ontology_name = 'name_of_proptype_ontology'; //you need to set this variable with the cv.name of the ontology governing your prop tables type_id
  42. $prop_types = chado_query($sql, array(':ontology_name' => $ontology_name));
  43. while ($prop = $prop_types->fetchObject()) {
  44. $properties[$prop->cvterm_id] = $prop->name;
  45. }
  46. // the properties form will add a select dropdown of terms containing the items in the $properties array
  47. // constructed above, but it will also pre-populate rows of properties that already are associated
  48. // with the object. If you would like to pre-populated properties regardless if they exist in the database
  49. // or not, you can create an $include array which has the following format:
  50. // array(
  51. // array('cvterm' => $obj1, 'value' => $val1),
  52. // array('cvterm' => $obj2, 'value' => $val2),
  53. // ... etc
  54. // );
  55. // The 'cvterm' key should have as a value an object with these properties: 'name', 'cvterm_id', 'definition'.
  56. $include = array();
  57. // sometimes a property exists in the database and is properly associated with the object, but we do
  58. // not want it to appear in the list of properties that are pre-populated. It may be handled in some
  59. // other way. For example, for contacts, the description field is stored as a property because
  60. // the actual contact.description field is only 255 characters. The 'contact_description' property should
  61. // not be shown in the list of properties, even if present, because it is handled by
  62. // a different form element. This array holds the value of the cvterm.name column of the cvterms
  63. // to exclude
  64. $exclude = array();
  65. // the instructions argument provides additional instructions to the user beyond the default instructions.
  66. $instructions = t('To add additional properties to the drop down. ' . l("Add terms to the $ontology_name vocabulary", "admin/tripal/chado/tripal_cv/cvterm/add") . ".");
  67. // Finally, and add the properties form elements to the form
  68. tripal_core_properties_form(
  69. $form, $form_state, // form and form_state of the current form
  70. 'exampleprop', // properties table name
  71. 'example_id', // key to link to the chado content created by this node
  72. $ontology_name, // name of ontology governing your prop table type_id column
  73. $properties, // an array of properties to use in the drop-down
  74. $example_id, // the value of the above key
  75. $exclude, // elements from the ontology you don't want to be available as property types
  76. $include, // additional elements not in the ontology that you do what in the drop-down
  77. $instructions, // form specific instructions
  78. 'Properties' // name of the fieldset
  79. );
  80. return $form;
  81. }
  82. function chado_example_insert($node) {
  83. // if there is an example_id in the $node object then this must be a sync so
  84. // we can skip adding the chado_example as it is already there, although
  85. // we do need to proceed with the rest of the insert
  86. if (!property_exists($node, 'example_id')) {
  87. // Add record to chado example table
  88. // Add to any other tables needed
  89. // Add each property (exampleprop table). The tripal_core_properties_form_retrieve()
  90. // function retrieves all of the properties and returns them in an array of the format:
  91. //
  92. // $properties[<property name>][<rank>] = <value
  93. //
  94. // This array can then be used for inserting or updating properties using the API call
  95. // tripal_hook_insert_property()
  96. //
  97. // example_property = controlled vocab name for exampleprop.type_id
  98. $properties = tripal_core_properties_form_retreive($node, 'example_property');
  99. foreach ($properties as $property => $elements) {
  100. foreach ($elements as $rank => $value) {
  101. $success = tripal_core_insert_property(
  102. 'example', //base table name
  103. $example_id, // key to link to the chado content created by this node
  104. $property, // cvterm.name of the property to be added
  105. $ontology_name, // name of the ontology the cvterm is from
  106. $value // the value o the property
  107. );
  108. if (!$success) {
  109. watchdog(
  110. 'tripal_example',
  111. 'Example Update: Unable to insert property %cvterm %value.',
  112. array('%cvterm' => $property, '%value' => $value),
  113. WATCHDOG_ERROR
  114. );
  115. }
  116. }
  117. }
  118. }
  119. // Add record to chado_example linking example_id to new node
  120. }
  121. function chado_example_update($node) {
  122. // Update record in chado example table
  123. // Update any other tables needed
  124. // First delete any existing properties
  125. tripal_core_chado_delete(
  126. 'exampleprop', // the name of the prop table
  127. array('example_id' => $example_id) // name of your key and the current value used to determine which to delete
  128. );
  129. // Add each property (exampleprop table)
  130. // example_property = controlled vocab name for exampleprop.type_id
  131. $properties = tripal_core_properties_form_retreive($node, 'example_property');
  132. foreach ($properties as $property => $elements) {
  133. foreach ($elements as $rank => $value) {
  134. $success = tripal_core_insert_property(
  135. 'example', //base table name
  136. $example_id, // key to link to the chado content created by this node
  137. $property, // cvterm.name of the property to be added
  138. $ontology_name, // name of the ontology the cvterm is from
  139. $value // the value o the property
  140. );
  141. if (!$success) {
  142. watchdog(
  143. 'tripal_example',
  144. 'Example Update: Unable to insert property %cvterm %value.',
  145. array('%cvterm' => $property, '%value' => $value),
  146. WATCHDOG_ERROR
  147. );
  148. }
  149. }
  150. }
  151. }
  152. // Don't need to update chado_example linking table since niether example_id or nid can be changed in update
  153. }
  154. * @endcode
  155. */
  156. /**
  157. * Retrieve a property for a given base table record
  158. *
  159. * @param $basetable
  160. * The base table for which the property should be retrieved. Thus to retrieve a property
  161. * for a feature the basetable=feature and property is retrieved from featureprop
  162. * @param $record_id
  163. * The foriegn key field of the base table. This should be in integer.
  164. * @param $property
  165. * The cvterm name describing the type of properties to be retrieved
  166. * @param $cv_name
  167. * The name of the cv that the above cvterm is part of
  168. *
  169. * @return
  170. * An array in the same format as that generated by the function
  171. * tripal_core_generate_chado_var(). If only one record is returned it
  172. * is a single object. If more than one record is returned then it is an array
  173. * of objects
  174. *
  175. * @ingroup tripal_properties_api
  176. */
  177. function tripal_core_get_property($basetable, $record_id, $property, $cv_name) {
  178. // get the foreign key for this property table
  179. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  180. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  181. // construct the array of values to be selected
  182. $values = array(
  183. $fkcol => $record_id,
  184. 'type_id' => array(
  185. 'cv_id' => array(
  186. 'name' => $cv_name,
  187. ),
  188. 'name' => $property,
  189. 'is_obsolete' => 0
  190. ),
  191. );
  192. $results = tripal_core_generate_chado_var($basetable . 'prop', $values);
  193. if ($results) {
  194. $results = tripal_core_expand_chado_vars($results, 'field', $basetable . 'prop.value');
  195. }
  196. return $results;
  197. }
  198. /**
  199. * Insert a property for a given base table. By default if the property already
  200. * exists a new property is added with the next available rank. If
  201. * $update_if_present argument is specified then the record will be updated if it
  202. * exists rather than adding a new property.
  203. *
  204. * @param $basetable
  205. * The base table for which the property should be inserted. Thus to insert a property
  206. * for a feature the basetable=feature and property is inserted into featureprop
  207. * @param $record_id
  208. * The foriegn key value of the base table. This should be in integer.
  209. * @param $property
  210. * The cvterm name describing the type of properties to be inserted
  211. * @param $cv_name
  212. * The name of the cv that the above cvterm is part of
  213. * @param $value
  214. * The value of the property to be inserted (can be empty)
  215. * @param $update_if_present
  216. * A boolean indicating whether an existing record should be updated. If the
  217. * property already exists and this value is not specified or is zero then
  218. * a new property will be added with the next largest rank.
  219. *
  220. * @return
  221. * Return True on Insert/Update and False otherwise
  222. *
  223. * @ingroup tripal_properties_api
  224. */
  225. function tripal_core_insert_property($basetable, $record_id, $property,
  226. $cv_name, $value, $update_if_present = 0) {
  227. // first see if the property already exists, if the user want's to update
  228. // then we can do that, but otherwise we want to increment the rank and
  229. // insert
  230. $props = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  231. if (!is_array($props) and $props) {
  232. $props = array($props);
  233. }
  234. $rank = 0;
  235. if (count($props) > 0) {
  236. if ($update_if_present) {
  237. return tripal_core_update_property($basetable, $record_id, $property, $cv_name, $value);
  238. }
  239. else {
  240. // iterate through the properties returned and check to see if the
  241. // property with this value already exists if not, get the largest rank
  242. // and insert the same property but with this new value
  243. foreach ($props as $p) {
  244. if ($p->rank > $rank) {
  245. $rank = $p->rank;
  246. }
  247. if (strcmp($p->value, $value) == 0) {
  248. return TRUE;
  249. }
  250. }
  251. // now add 1 to the rank
  252. $rank++;
  253. }
  254. }
  255. // make sure the cvterm exists. Otherwise we'll get an error with
  256. // prepared statements not matching
  257. $values = array(
  258. 'cv_id' => array(
  259. 'name' => $cv_name,
  260. ),
  261. 'name' => $property,
  262. );
  263. $options = array();
  264. $term = tripal_core_chado_select('cvterm', array('cvterm_id'), $values, $options);
  265. if (!$term or count($term) == 0) {
  266. watchdog('tripal_core', "Cannot find property '%prop_name' in vocabulary '%cvname'.",
  267. array('%prop_name' => $property, '%cvname' => $cv_name), WATCHDOG_ERROR);
  268. return FALSE;
  269. }
  270. // get the foreign key for this property table
  271. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  272. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  273. // construct the array of values to be inserted
  274. $values = array(
  275. $fkcol => $record_id,
  276. 'type_id' => array(
  277. 'cv_id' => array(
  278. 'name' => $cv_name,
  279. ),
  280. 'name' => $property,
  281. ),
  282. 'value' => $value,
  283. 'rank' => $rank,
  284. );
  285. $options = array();
  286. $result = tripal_core_chado_insert($basetable . 'prop', $values, $options);
  287. return $result;
  288. }
  289. /**
  290. * Update a property for a given base table record and property name. This
  291. * function should be used only if one record of the property will be present.
  292. * If the property name can have multiple entries (with increasing rank) then
  293. * use the function named tripal_core_update_property_by_id
  294. *
  295. * @param $basetable
  296. * The base table for which the property should be updated. The property table
  297. * is constructed using a combination of the base table name and the suffix
  298. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  299. * @param $record_id
  300. * The foreign key of the basetable to update a property for. This should be in integer.
  301. * For example, if the basetable is 'feature' then the $record_id should be the feature_id
  302. * @param $property
  303. * The cvterm name of property to be updated
  304. * @param $cv_name
  305. * The name of the cv that the above cvterm is part of
  306. * @param $value
  307. * The value of the property to be inserted (can be empty)
  308. * @param $insert_if_missing
  309. * A boolean indicating whether a record should be inserted if one doesn't exist to update
  310. *
  311. * Note: The property to be updated is select via the unique combination of $record_id and
  312. * $property and then it is updated with the supplied value
  313. *
  314. * @return
  315. * Return True on Update/Insert and False otherwise
  316. *
  317. * @ingroup tripal_properties_api
  318. */
  319. function tripal_core_update_property($basetable, $record_id, $property,
  320. $cv_name, $value, $insert_if_missing = 0) {
  321. // first see if the property is missing (we can't update a missing property
  322. $prop = tripal_core_get_property($basetable, $record_id, $property, $cv_name);
  323. if (count($prop)==0) {
  324. if ($insert_if_missing) {
  325. return tripal_core_insert_property($basetable, $record_id, $property, $cv_name, $value);
  326. }
  327. else {
  328. return FALSE;
  329. }
  330. }
  331. // get the foreign key for this property table
  332. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  333. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  334. // construct the array that will match the exact record to update
  335. $match = array(
  336. $fkcol => $record_id,
  337. 'type_id' => array(
  338. 'cv_id' => array(
  339. 'name' => $cv_name,
  340. ),
  341. 'name' => $property,
  342. ),
  343. );
  344. // construct the array of values to be updated
  345. $values = array(
  346. 'value' => $value,
  347. );
  348. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  349. }
  350. /**
  351. * Update a property for a given base table record. This function should be
  352. * used if multiple records of the same property will be present. Also, use this
  353. * function to change the property name of an existing property.
  354. *
  355. * @param $basetable
  356. * The base table for which the property should be updated. The property table
  357. * is constructed using a combination of the base table name and the suffix
  358. * 'prop' (e.g. basetable = feature then property tabie is featureprop).
  359. * @param $record_id
  360. * The primary key of the base table. This should be in integer.
  361. * For example, if the basetable is 'feature' then the $record_id should be the featureprop_id
  362. * @param $property
  363. * The cvterm name of property to be updated
  364. * @param $cv_name
  365. * The name of the cv that the above cvterm is part of
  366. * @param $value
  367. * The value of the property to be inserted (can be empty)
  368. *
  369. * @return
  370. * Return True on Update/Insert and False otherwise
  371. *
  372. * @ingroup tripal_properties_api
  373. */
  374. function tripal_core_update_property_by_id($basetable, $record_id, $property,
  375. $cv_name, $value) {
  376. // get the primary key for this property table
  377. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  378. $pkcol = $table_desc['primary key'][0];
  379. // construct the array that will match the exact record to update
  380. $match = array(
  381. $pkcol => $record_id,
  382. );
  383. // construct the array of values to be updated
  384. $values = array(
  385. 'type_id' => array(
  386. 'cv_id' => array(
  387. 'name' => $cv_name,
  388. ),
  389. 'name' => $property,
  390. ),
  391. 'value' => $value,
  392. );
  393. return tripal_core_chado_update($basetable . 'prop', $match, $values);
  394. }
  395. /**
  396. * Deletes a property for a given base table record using the property name
  397. *
  398. * @param $basetable
  399. * The base table for which the property should be deleted. Thus to deleted a property
  400. * for a feature the basetable=feature and property is deleted from featureprop
  401. * @param $record_id
  402. * The primary key of the basetable to delete a property for. This should be in integer.
  403. * @param $property
  404. * The cvterm name describing the type of property to be deleted
  405. * @param $cv_name
  406. * The name of the cv that the above cvterm is part of
  407. *
  408. * Note: The property to be deleted is select via the unique combination of $record_id and $property
  409. *
  410. * @return
  411. * Return True on Delete and False otherwise
  412. *
  413. * @ingroup tripal_properties_api
  414. */
  415. function tripal_core_delete_property($basetable, $record_id, $property, $cv_name) {
  416. // get the foreign key for this property table
  417. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  418. $fkcol = key($table_desc['foreign keys'][$basetable]['columns']);
  419. // construct the array that will match the exact record to update
  420. $match = array(
  421. $fkcol => $record_id,
  422. 'type_id' => array(
  423. 'cv_id' => array(
  424. 'name' => $cv_name,
  425. ),
  426. 'name' => $property,
  427. ),
  428. );
  429. return tripal_core_chado_delete($basetable . 'prop', $match);
  430. }
  431. /**
  432. * Deletes a property using the property ID
  433. *
  434. * @param $basetable
  435. * The base table for which the property should be deleted. Thus to deleted a property
  436. * for a feature the basetable=feature and property is deleted from featureprop
  437. * @param $record_id
  438. * The primary key of the basetable to delete a property for. This should be in integer.
  439. *
  440. * @return
  441. * Return True on Delete and False otherwise
  442. *
  443. * @ingroup tripal_properties_api
  444. */
  445. function tripal_core_delete_property_by_id($basetable, $record_id) {
  446. // get the foreign key for this property table
  447. $table_desc = tripal_core_get_chado_table_schema($basetable . 'prop');
  448. $pkcol = $table_desc['primary key'][0];
  449. // construct the array that will match the exact record to update
  450. $match = array(
  451. $pkcol => $record_id,
  452. );
  453. return tripal_core_chado_delete($basetable . 'prop', $match);
  454. }
  455. /**
  456. * This function is a wrapper for adding fields to an existing form for managing properties.
  457. * Many of the chado tables have a corresponding 'prop' table (e.g. analysisprop, contactprop,
  458. * organismprop, etc) and those prop tables all have the same schema. Use this function
  459. * to add all the necessary components to a form for allowing the user to add/edit properties to
  460. * a given record. To retreive properties in hook_insert or hook_update of a node form use
  461. * use the function tripal_core_properties_form_retreive().
  462. *
  463. * @param $form
  464. * The Drupal form array into which the properties elements will be added
  465. * @param $form_state
  466. * The corresponding form_state array for the form
  467. * @param $prop_table
  468. * The name of the property table (e.g. anlaysisprop, contactprop)
  469. * @param $id_field
  470. * The name of the ID field in the property table (e.g. analysis_id, contact_id)
  471. * @param $cv_name
  472. * The name of the controlled vocabulary that these properties are derived from
  473. * @param $available_props
  474. * An array of properties to inclde in the properties drop down. This array should
  475. * have cvterm_id's as the key and the cvterm name as the value
  476. * @param $id
  477. * The current base table ID. For example, if the property table is analysisprop then the
  478. * value should be that of the analysis_id. If the property table is contactprop then the
  479. * value should be that of the contact_id. This is the record from which currently assigned
  480. * properties will be retrieved.
  481. * @param $exclude
  482. * An optional array of cvterms to exclude when retreiving terms already saved in the database.
  483. * Use this array when properties are present but should be handled elsewhere.
  484. * For example, for contacts, the description field is stored as a property because
  485. * the actual field is only 255 characters. The 'contact_description' therefore should
  486. * not be shown in the list of properties, even if present, because it is handled by
  487. * a different form element.
  488. * @param $include
  489. * An optional array of terms to pre-populate in the form. This argument can be used to
  490. * add a default set of pre-populated properties regardless if they exist in the database
  491. * or not. The array should be of the following form:
  492. * array(
  493. * array('cvterm' => $obj1, 'value' => $val1),
  494. * array('cvterm' => $obj2, 'value' => $val2),
  495. * ... etc
  496. * );
  497. * The 'cvterm' key should have as a value an object with these properties: 'name', 'cvterm_id', 'definition'.
  498. * @param $instructions
  499. * An optional additional set of instructions for the form properties.
  500. * @param $fset_title
  501. * A title for the property field set. The default is 'Additional Details'.
  502. * @ingroup tripal_properties_api
  503. */
  504. function tripal_core_properties_form(&$form, &$form_state, $prop_table, $id_field, $cv_name,
  505. $available_props, $id = NULL, $exclude = array(), $include = array(), $instructions = '',
  506. $fset_title = 'Additional Details') {
  507. $d_removed = array(); // lists removed properties
  508. // if we are re constructing the form from a failed validation or ajax callback
  509. // then use the $form_state['values'] values
  510. if (array_key_exists('values', $form_state)) {
  511. $d_removed = $form_state['values']['removed'];
  512. }
  513. // if we are re building the form from after submission (from ajax call) then
  514. // the values are in the $form_state['input'] array
  515. if (array_key_exists('input', $form_state) and !empty($form_state['input'])) {
  516. $d_removed = $form_state['input']['removed'];
  517. }
  518. $form['properties'] = array(
  519. '#type' => 'fieldset',
  520. '#title' => t($fset_title),
  521. '#description' => t('You may add additional properties by
  522. selecting a property type from the dropdown and adding text. You may add
  523. as many properties as desired by clicking the add button on the right. To
  524. remove a property, click the remove button. ' . $instructions),
  525. );
  526. $form['properties']['table'] = array(
  527. '#type' => 'markup',
  528. '#value' => '',
  529. '#prefix' => '<div id="tripal-generic-edit-properties-table">',
  530. '#suffix' => '</div>',
  531. );
  532. // this array keeps track of all properties we have and allows the functions
  533. // below to select the next rank if a property is dupliated
  534. $ranks = array();
  535. // add in the properties from the Chado prop table (only pertains to existing analyses)
  536. if ($id) {
  537. tripal_core_properties_form_add_prop_table_props($prop_table, $id_field, $cv_name,
  538. $form, $form_state, $id, $ranks, $d_removed, $exclude, $include);
  539. }
  540. // add in any new properties that have been added by the user through an AHAH callback
  541. tripal_core_properties_form_add_new_props($form, $form_state, $ranks, $d_removed);
  542. // add an empty row of field to allow for addition of a new property
  543. tripal_core_properties_form_add_new_empty_props($form, $form_state, $available_props);
  544. $form['properties']['table']['#theme'] = 'tripal_core_properties_form';
  545. }
  546. /**
  547. * This function is responsible for adding a blank row to the properties table for
  548. * adding a new property.
  549. */
  550. function tripal_core_properties_form_add_new_empty_props(&$form, &$form_state, $properties_select) {
  551. // get the field defaults either from $form_state['values'] or $form_state['input']
  552. $description = '';
  553. $text = '';
  554. $id = 0;
  555. if (array_key_exists('values', $form_state)) {
  556. $id = $form_state['values']['new_id'];
  557. $text = $form_state['values']['new_value'];
  558. }
  559. // if we have a property ID then get it's definition to display to the user
  560. if($id) {
  561. $values = array('cvterm_id' => $id);
  562. $cvterm = tripal_core_chado_select('cvterm', array('definition'), $values);
  563. if ($cvterm[0]->definition) {
  564. $description = $cvterm[0]->definition;
  565. }
  566. }
  567. $rows = 1;
  568. // add one more blank set of property fields
  569. $form['properties']['table']['new']["new_id"] = array(
  570. '#type' => 'select',
  571. '#options' => $properties_select,
  572. '#default_value' => $id,
  573. '#ajax' => array(
  574. 'callback' => "tripal_core_props_property_ajax_get_description",
  575. 'wrapper' => 'tripal-properties-new_value',
  576. 'effect' => 'fade',
  577. 'method' => 'replace',
  578. ),
  579. );
  580. $form['properties']['table']['new']["new_value"] = array(
  581. '#type' => 'textarea',
  582. '#default_value' => $text,
  583. '#cols' => 50,
  584. '#rows' => $rows,
  585. '#prefix' => '<div id="tripal-properties-new_value">',
  586. '#description' => '<span style="white-space: normal">' . $description . '</span>',
  587. '#suffix' => '</div>',
  588. );
  589. $form['properties']['table']['new']["add"] = array(
  590. '#type' => 'button',
  591. '#value' => t('Add'),
  592. '#name' => 'add',
  593. '#ajax' => array(
  594. 'callback' => "tripal_core_props_property_ajax_update",
  595. 'wrapper' => 'tripal-properties-edit-properties-table',
  596. 'effect' => 'fade',
  597. 'method' => 'replace',
  598. 'prevent' => 'click'
  599. ),
  600. // When this button is clicked, the form will be validated and submitted.
  601. // Therefore, we set custom submit and validate functions to override the
  602. // default form submit. In the validate function we set the form_state
  603. // to rebuild the form so the submit function never actually gets called,
  604. // but we need it or Drupal will run the default validate anyway.
  605. // we also set #limit_validation_errors to empty so fields that
  606. // are required that don't have values won't generate warnings.
  607. '#submit' => array('tripal_core_props_form_props_button_submit'),
  608. '#validate' => array('tripal_core_props_form_props_button_validate'),
  609. '#limit_validation_errors' => array(array('new_id')),
  610. );
  611. }
  612. /**
  613. * This function is used to rebuild the form if an ajax call is made vai a button.
  614. * The button causes the form to be submitted. We don't want this so we override
  615. * the validate and submit routines on the form button. Therefore, this function
  616. * only needs to tell Drupal to rebuild the form
  617. */
  618. function tripal_core_props_form_props_button_validate($form, &$form_state){
  619. if (array_key_exists('triggering_element', $form_state) and
  620. $form_state['triggering_element']['#name'] == 'add' and
  621. $form_state['input']['new_id'] == 0 ){
  622. form_set_error('new_id', "Please specify a property type");
  623. return;
  624. }
  625. $form_state['rebuild'] = TRUE;
  626. }
  627. /**
  628. * This function is just a dummy to override the default form submit on ajax calls for buttons
  629. */
  630. function tripal_core_props_form_props_button_submit($form, &$form_state){
  631. // do nothing
  632. }
  633. /**
  634. * This adds
  635. */
  636. function tripal_core_properties_form_add_new_props(&$form, &$form_state, &$ranks, &$d_removed) {
  637. // set some default values
  638. $j = 0;
  639. $num_properties = 0;
  640. $values = array();
  641. if (array_key_exists('values', $form_state)) {
  642. $values = $form_state['values'];
  643. }
  644. if (array_key_exists('input', $form_state) and !empty($form_state['input'])) {
  645. $values = $form_state['input'];
  646. }
  647. // first, add in all of the new properties that were added previously via this form
  648. foreach ($values as $element_name => $value) {
  649. if (preg_match('/new_value-(\d+)-(\d+)/', $element_name, $matches)) {
  650. $new_id = $matches[1];
  651. $rank = $matches[2];
  652. // skip any properties that the user requested to delete through a previous
  653. // ajax callback or through the current ajax callback
  654. if (array_key_exists("$new_id-$rank", $d_removed)) {
  655. continue;
  656. }
  657. if (array_key_exists('triggering_element', $form_state) and
  658. $form_state['triggering_element']['#name'] == 'remove-' . $new_id . '-' . $rank) {
  659. $d_removed["$new_id-$rank"] = 1;
  660. continue;
  661. }
  662. // get this new_id information
  663. $args = array('cvterm_id' => $new_id);
  664. $cvterm = tripal_core_chado_select('cvterm', array('name', 'definition'), $args);
  665. // add it to the $ranks array
  666. $ranks[$new_id][$rank]['name'] = $cvterm[0]->name;
  667. $ranks[$new_id][$rank]['id'] = $new_id;
  668. $ranks[$new_id][$rank]['value'] = $value;
  669. $ranks[$new_id][$rank]['definition'] = $cvterm[0]->definition;
  670. $num_properties++;
  671. // determine how many rows we need in the textarea
  672. $rows = 1;
  673. $rows = strlen($value) / 80 + 1;
  674. if ($rows > 10) {
  675. $rows = 10;
  676. }
  677. // add the new fields
  678. $form['properties']['table']['new'][$new_id][$rank]["new_id-$new_id-$rank"] = array(
  679. '#markup' => $cvterm[0]->name
  680. );
  681. $form['properties']['table']['new'][$new_id][$rank]["new_value-$new_id-$rank"] = array(
  682. '#type' => 'textarea',
  683. '#default_value' => $value,
  684. '#cols' => 50,
  685. '#rows' => $rows,
  686. '#description' => '<span style="white-space: normal">' . $cvterm[0]->definition . '</span>',
  687. );
  688. $form['properties']['table']['new'][$new_id][$rank]["remove-$new_id-$rank"] = array(
  689. '#type' => 'button',
  690. '#value' => t('Remove'),
  691. '#name' => "remove-$new_id-$rank",
  692. '#ajax' => array(
  693. 'callback' => "tripal_core_props_property_ajax_update",
  694. 'wrapper' => 'tripal-properties-edit-properties-table',
  695. 'effect' => 'fade',
  696. 'event' => 'mousedown',
  697. 'method' => 'replace',
  698. 'prevent' => 'click'
  699. ),
  700. // When this button is clicked, the form will be validated and submitted.
  701. // Therefore, we set custom submit and validate functions to override the
  702. // default form submit. In the validate function we set the form_state
  703. // to rebuild the form so the submit function never actually gets called,
  704. // but we need it or Drupal will run the default validate anyway.
  705. // we also set #limit_validation_errors to empty so fields that
  706. // are required that don't have values won't generate warnings.
  707. '#submit' => array('tripal_core_props_form_props_button_submit'),
  708. '#validate' => array('tripal_core_props_form_props_button_validate'),
  709. '#limit_validation_errors' => array(),
  710. );
  711. }
  712. }
  713. // second add in any new properties added during this callback
  714. if (array_key_exists('triggering_element', $form_state) and
  715. $form_state['triggering_element']['#name'] == 'add' and
  716. $form_state['input']['new_id'] != 0) {
  717. $new_id = $form_state['input']['new_id'];
  718. $new_value = $form_state['input']['new_value'];
  719. // get the rank by counting the number of entries
  720. $rank = count($ranks[$new_id]);
  721. // get this new_id information
  722. $cvterm = tripal_core_chado_select('cvterm', array('name', 'definition'), array('cvterm_id' => $new_id));
  723. // add it to the $ranks array
  724. $ranks[$new_id][$rank]['name'] = $cvterm[0]->name;
  725. $ranks[$new_id][$rank]['id'] = $new_id;
  726. $ranks[$new_id][$rank]['value'] = $value;
  727. $ranks[$new_id][$rank]['definition'] = $cvterm[0]->definition;
  728. $num_properties++;
  729. // determine how many rows we need in the textarea
  730. $rows = 1;
  731. // add the new fields
  732. $form['properties']['table']['new'][$new_id][$rank]["new_id-$new_id-$rank"] = array(
  733. '#markup' => $cvterm[0]->name
  734. );
  735. $form['properties']['table']['new'][$new_id][$rank]["new_value-$new_id-$rank"] = array(
  736. '#type' => 'textarea',
  737. '#default_value' => $new_value,
  738. '#cols' => 50,
  739. '#rows' => $rows,
  740. '#description' => $cvterm[0]->definition,
  741. );
  742. $form['properties']['table']['new'][$new_id][$rank]["remove-$new_id-$rank"] = array(
  743. '#type' => 'button',
  744. '#value' => t('Remove'),
  745. '#name' => "remove-$new_id-$rank",
  746. '#ajax' => array(
  747. 'callback' => "tripal_core_props_property_ajax_update",
  748. 'wrapper' => 'tripal-properties-edit-properties-table',
  749. 'effect' => 'fade',
  750. 'event' => 'mousedown',
  751. 'method' => 'replace',
  752. 'prevent' => 'click'
  753. ),
  754. // When this button is clicked, the form will be validated and submitted.
  755. // Therefore, we set custom submit and validate functions to override the
  756. // default form submit. In the validate function we set the form_state
  757. // to rebuild the form so the submit function never actually gets called,
  758. // but we need it or Drupal will run the default validate anyway.
  759. // we also set #limit_validation_errors to empty so fields that
  760. // are required that don't have values won't generate warnings.
  761. '#submit' => array('tripal_core_props_form_props_button_submit'),
  762. '#validate' => array('tripal_core_props_form_props_button_validate'),
  763. '#limit_validation_errors' => array(),
  764. );
  765. }
  766. return $num_properties;
  767. }
  768. /**
  769. * This function queries the proper xxxprop table to look for existing values for the given
  770. * $id. It then adds these properties to the form for editing. It also will incorporate
  771. * extra properties that were specified manually by the caller.
  772. *
  773. */
  774. function tripal_core_properties_form_add_prop_table_props($prop_table, $id_field, $cv_name,
  775. &$form, $form_state, $id, &$ranks, &$d_removed, $exclude = array(), $include = array()) {
  776. // get the existing properties
  777. $num_properties = 0;
  778. if (!$id) {
  779. return;
  780. }
  781. // create an array of properties so we can merge those in the database with those provided by the caller
  782. $all_props = array();
  783. foreach ($include as $prop) {
  784. $all_props[] = $prop;
  785. }
  786. // now merge in properties saved in the database
  787. $sql = "
  788. SELECT CVT.cvterm_id, CVT.name, CVT.definition, PP.value, PP.rank
  789. FROM {" . $prop_table . "} PP
  790. INNER JOIN {cvterm} CVT ON CVT.cvterm_id = PP.type_id
  791. INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
  792. WHERE
  793. PP.$id_field = :id AND
  794. CV.name = '$cv_name'
  795. ORDER BY CVT.name, PP.rank
  796. ";
  797. $props = chado_query($sql, array(':id' => $id));
  798. while ($prop = $props->fetchObject()) {
  799. $all_props[] = array('cvterm' => $prop, 'value' => $prop->value);
  800. }
  801. // iterate through the properties
  802. foreach ($all_props as $prop) {
  803. $type_id = $prop['cvterm']->cvterm_id;
  804. $value = $prop['value'];
  805. $name = $prop['cvterm']->name;
  806. $definition = $prop['cvterm']->definition;
  807. $rank = 0;
  808. if(array_key_exists($type_id, $ranks)) {
  809. $rank = count($ranks[$type_id]);
  810. }
  811. // skip any properties that the user requested to delete through a previous
  812. // AHAH callback or through the current AHAH callback
  813. if (array_key_exists("$type_id-$rank", $d_removed)) {
  814. continue;
  815. }
  816. // skip any properties that should be excluded
  817. if (count(array_intersect(array($name), $exclude)) == 1) {
  818. continue;
  819. }
  820. if (array_key_exists('triggering_element', $form_state) and
  821. $form_state['triggering_element']['#name'] == 'remove-' . $type_id . '-' . $rank) {
  822. $d_removed["$type_id-$rank"] = 1;
  823. continue;
  824. }
  825. $ranks[$type_id][$rank]['name'] = $name;
  826. $ranks[$type_id][$rank]['id'] = $type_id;
  827. $ranks[$type_id][$rank]['value'] = $value;
  828. $num_properties++;
  829. $rows = 1;
  830. $rows = strlen($value) / 80 + 1;
  831. if ($rows > 10) {
  832. $rows = 10;
  833. }
  834. $form['properties']['table'][$type_id][$rank]["prop_id-$type_id-$rank"] = array(
  835. '#markup' => $name,
  836. );
  837. $form['properties']['table'][$type_id][$rank]["prop_value-$type_id-$rank"] = array(
  838. '#type' => 'textarea',
  839. '#default_value' => $value,
  840. '#cols' => 50,
  841. '#rows' => $rows,
  842. '#description' => '<span style="white-space: normal">' . $definition . '</span>',
  843. );
  844. $form['properties']['table'][$type_id][$rank]["remove-$type_id-$rank"] = array(
  845. '#type' => 'button',
  846. '#value' => t('Remove'),
  847. '#name' => "remove-$type_id-$rank",
  848. '#ajax' => array(
  849. 'callback' => "tripal_core_props_property_ajax_update",
  850. 'wrapper' => 'tripal-properties-edit-properties-table',
  851. 'effect' => 'fade',
  852. 'event' => 'mousedown',
  853. 'method' => 'replace',
  854. 'prevent' => 'click'
  855. ),
  856. // When this button is clicked, the form will be validated and submitted.
  857. // Therefore, we set custom submit and validate functions to override the
  858. // default form submit. In the validate function we set the form_state
  859. // to rebuild the form so the submit function never actually gets called,
  860. // but we need it or Drupal will run the default validate anyway.
  861. // we also set #limit_validation_errors to empty so fields that
  862. // are required that don't have values won't generate warnings.
  863. '#submit' => array('tripal_core_props_form_props_button_submit'),
  864. '#validate' => array('tripal_core_props_form_props_button_validate'),
  865. '#limit_validation_errors' => array(),
  866. );
  867. }
  868. return $num_properties;
  869. }
  870. /**
  871. * Form AJAX callback for adding a blank property row
  872. *
  873. * We only want to return the properties as that's all we'll replace with this callback
  874. */
  875. function tripal_core_props_property_ajax_update($form, $form_state) {
  876. $properties_html = tripal_core_props_theme_node_form_properties($form['properties']['table']);
  877. $form['properties']['table'] = array(
  878. '#markup' => $properties_html,
  879. '#prefix' => '<div id="tripal-properties-edit-properties-table">',
  880. '#suffix' => '</div>',
  881. );
  882. return $form['properties']['table'];
  883. }
  884. /**
  885. * Form AJAX callback for updating a property description. This
  886. * function only gets called when the property drop down is changed
  887. * on the bottom (empty) row of properties
  888. */
  889. function tripal_core_props_property_ajax_get_description($form, $form_state) {
  890. return $form['properties']['table']['new']["new_value"];
  891. }
  892. /**
  893. * We need to theme the form so that the properties fields look good
  894. */
  895. function theme_tripal_core_properties_form($variables) {
  896. $form = $variables['form'];
  897. $properties_table = tripal_core_props_theme_node_form_properties($form);
  898. $markup = $properties_table;
  899. $form['properties']['table'] = array(
  900. '#markup' => $markup,
  901. '#prefix' => '<div id="tripal-properties-edit-properties-table">',
  902. '#suffix' => '</div>',
  903. );
  904. $form['buttons']['#weight'] = 50;
  905. return drupal_render($form['properties']['table']);
  906. }
  907. /**
  908. *
  909. */
  910. function tripal_core_props_theme_node_form_properties($form) {
  911. $rows = array();
  912. // first add in the properties derived from the prop table
  913. // the array tree for these properties looks like this:
  914. // $form['properties']['table'][$type_id][$rank]["prop_id-$type_id-$rank"]
  915. foreach ($form as $type_id => $elements) {
  916. // there are other fields in the properties array so we only
  917. // want the numeric ones those are our type_id
  918. if (is_numeric($type_id)) {
  919. foreach ($elements as $rank => $element) {
  920. if (is_numeric($rank)) {
  921. $rows[] = array(
  922. drupal_render($element["prop_id-$type_id-$rank"]),
  923. drupal_render($element["prop_value-$type_id-$rank"]),
  924. drupal_render($element["remove-$type_id-$rank"]),
  925. );
  926. }
  927. }
  928. }
  929. }
  930. // second, add in any new properties added by the user through AHAH callbacks
  931. // the array tree for these properties looks like this:
  932. // $form['properties']['table']['new'][$type_id][$rank]["new_id-$new_id-$rank"]
  933. foreach ($form['new'] as $type_id => $elements) {
  934. if (is_numeric($type_id)) {
  935. foreach ($elements as $rank => $element) {
  936. if (is_numeric($rank)) {
  937. $rows[] = array(
  938. drupal_render($element["new_id-$type_id-$rank"]),
  939. drupal_render($element["new_value-$type_id-$rank"]),
  940. drupal_render($element["remove-$type_id-$rank"]),
  941. );
  942. }
  943. }
  944. }
  945. }
  946. // finally add in a set of blank field for adding a new property
  947. $rows[] = array(
  948. drupal_render($form['new']['new_id']),
  949. array(
  950. 'data' => drupal_render($form['new']['new_value']),
  951. 'width' => '60%',
  952. ),
  953. drupal_render($form['new']['add']),
  954. );
  955. $headers = array('Property Type', 'Value', 'Actions');
  956. $table = array(
  957. 'header' => $headers,
  958. 'rows' => $rows,
  959. 'attributes' => array(),
  960. 'sticky' => TRUE,
  961. 'caption' => '',
  962. 'colgroups' => array(),
  963. 'empty' => '',
  964. );
  965. return theme_table($table);
  966. }
  967. /**
  968. * This function is used in a hook_insert, hook_update for a node form
  969. * when the properties form has been added to the form. It retrieves all of the properties
  970. * and returns them in an array of the format:
  971. *
  972. * $properties[<property name>][<rank>] = <value
  973. *
  974. * This array can then be used for inserting or updating properties using the API call
  975. * tripal_hook_insert_property()
  976. *
  977. * @param $node
  978. * @param $cvname
  979. * The name of the controlled vocabulary that the properties belong to
  980. *
  981. * @return
  982. * A properties array
  983. *
  984. * @ingroup tripal_properties_api
  985. */
  986. function tripal_core_properties_form_retreive($node, $cv_name) {
  987. // now add the properties
  988. $properties = array(); // stores all of the properties we need to add
  989. // get the list of properties for easy lookup (without doing lots of database queries
  990. $properties_list = array();
  991. $sql = "
  992. SELECT DISTINCT CVT.cvterm_id, CVT.name, CVT.definition
  993. FROM {cvterm} CVT
  994. INNER JOIN {cv} ON CVT.cv_id = CV.cv_id
  995. WHERE
  996. CV.name = '$cv_name' AND
  997. NOT CVT.is_obsolete = 1
  998. ORDER BY CVT.name ASC
  999. ";
  1000. $prop_types = chado_query($sql);
  1001. while ($prop = $prop_types->fetchObject()) {
  1002. $properties_list[$prop->cvterm_id] = $prop->name;
  1003. }
  1004. // get the properties that should be added. Properties are in one of two forms:
  1005. // 1) prop_value-[type id]-[index]
  1006. // 2) new_value-[type id]-[index]
  1007. // 3) new_id, new_value
  1008. foreach ($node as $name => $value) {
  1009. if (preg_match('/^new_value-(\d+)-(\d+)/', $name, $matches)) {
  1010. $type_id = $matches[1];
  1011. $index = $matches[2];
  1012. $name = $properties_list[$type_id];
  1013. $properties[$name][$index] = trim($value);
  1014. }
  1015. if (preg_match('/^prop_value-(\d+)-(\d+)/', $name, $matches)) {
  1016. $type_id = $matches[1];
  1017. $index = $matches[2];
  1018. $name = $properties_list[$type_id];
  1019. $properties[$name][$index] = trim($value);
  1020. }
  1021. }
  1022. if (property_exists($node, 'new_id') and $node->new_id and property_exists($node, 'new_value') and $node->new_value) {
  1023. $type_id = $node->new_id;
  1024. $name = $properties_list[$type_id];
  1025. $index = 0;
  1026. if (array_key_exists($name, $properties)) {
  1027. $index = count($properties[$name]);
  1028. }
  1029. $properties[$name][$index] = trim($node->new_value);
  1030. }
  1031. return $properties;
  1032. }