tripal_chado.field_storage.inc 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. <?php
  2. /**
  3. * Implements hook_field_storage_info().
  4. */
  5. function tripal_chado_field_storage_info() {
  6. return array(
  7. 'field_chado_storage' => array(
  8. 'label' => t('Chado'),
  9. 'description' => t('Stores fields in the local Chado database.'),
  10. 'settings' => array(
  11. 'tripal_storage_api' => TRUE,
  12. ),
  13. // The logo_url key is supported by Tripal. It's not a Drupal key. It's
  14. // used for adding a logo or picture for the data store to help make it
  15. // more easily recognized on the field_ui_field_overview_form. Ideally
  16. // the URL should point to a relative path on the local Drupal site.
  17. 'logo_url' => url(drupal_get_path('module', 'tripal') . '/theme/images/250px-ChadoLogo.png'),
  18. ),
  19. );
  20. }
  21. /**
  22. * Implements hook_field_storage_write().
  23. */
  24. function tripal_chado_field_storage_write($entity_type, $entity, $op, $fields) {
  25. // Get the bundle and the term for this entity.
  26. $bundle = tripal_load_bundle_entity(array('name' => $entity->bundle));
  27. $term = entity_load('TripalTerm', array('id' => $entity->term_id));
  28. $term = reset($term);
  29. // Convert the Tripal term entity into the appropriate record in Chado.
  30. $dbxref = chado_get_dbxref(array('accession' => $term->accession, 'db_id' => array('name' => $term->vocab->vocabulary)));
  31. $cvterm = chado_get_cvterm(array('dbxref_id' => $dbxref->dbxref_id));
  32. // Get the base table, type field and record_id from the entity.
  33. $base_table = $entity->chado_table;
  34. $type_field = $entity->chado_column;
  35. $record = $entity->chado_record;
  36. $record_id = $entity->chado_record_id;
  37. $linker = property_exists($entity, 'chado_linker') ? $entity->chado_linker : '';
  38. $base_schema = chado_get_schema($base_table);
  39. $base_pkey = $base_schema['primary key'][0];
  40. // Convert the fields into a key/value list of fields and their values.
  41. list($field_vals, $field_items) = tripal_chado_field_storage_write_merge_fields($fields, $entity_type, $entity);
  42. // dpm($field_vals);
  43. // First, write the record for the base table.
  44. $values = $field_vals[$base_table];
  45. if ($record_id) {
  46. $values[$base_pkey] = $record_id;
  47. }
  48. elseif ($type_field and !$linker) {
  49. $values[$type_field] = $cvterm->cvterm_id;
  50. }
  51. $base_record_id = tripal_chado_field_storage_write_table($base_table, $values, $base_table);
  52. if (!$base_record_id) {
  53. throw new Exception('Unable to write fields to Chado: ' . print_r($field_items, TRUE));
  54. }
  55. // If this is an insert then add the chado_entity record.
  56. if ($op == FIELD_STORAGE_INSERT) {
  57. // Add the record to the proper chado entity table
  58. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  59. $record_id = db_insert($chado_entity_table)
  60. ->fields(array(
  61. 'entity_id' => $entity->id,
  62. 'record_id' => $base_record_id
  63. ))
  64. ->execute();
  65. if (!$record_id) {
  66. throw new Exception('Unable to insert new Chado entity.');
  67. }
  68. }
  69. // Now that we have handled the base table, we need to handle linking tables.
  70. foreach ($field_vals as $table_name => $details) {
  71. // Skip the base table as we've already dealt with it.
  72. if ($table_name == $base_table) {
  73. continue;
  74. }
  75. foreach ($details as $delta => $values) {
  76. $record_id = tripal_chado_field_storage_write_table($table_name, $values, $base_table, $base_pkey, $base_record_id);
  77. }
  78. }
  79. }
  80. /**
  81. * Write (inserts/updates/deletes) values for a Chado table.
  82. *
  83. * The $values array is of the same format used by chado_insert_record() and
  84. * chado_update_record(). However, both of those methods will use any nested
  85. * arrays (i.e. representing foreign keys) to select an appropriate record ID
  86. * that can be substituted as the value. Here, the nested arrays are
  87. * either inserted or updated as well, but the choice is determined if the
  88. * primary key value is present. If present an update occurs, if not present
  89. * then an insert occurs.
  90. *
  91. * This function is recursive and nested arrays from the lowest point of the
  92. * "tree" are dealt with first.
  93. *
  94. * @param $table_name
  95. * The name of the table on which the insertion/update is performed.
  96. * @param $values
  97. * The values array for the insertion.
  98. *
  99. * @throws Exception
  100. *
  101. * @return
  102. * The unique record ID.
  103. */
  104. function tripal_chado_field_storage_write_table($table_name, $values, $base_table, $base_pkey = NULL, $base_record_id = NULL) {
  105. $schema = chado_get_schema($table_name);
  106. $fkeys = $schema['foreign keys'];
  107. $pkey = $schema['primary key'][0];
  108. // Fields with a cardinality greater than 1 will often submit an
  109. // empty form. We want to remove these empty submissions. We can detect
  110. // them if all of the fields are empty.
  111. $num_empty = 0;
  112. foreach ($values as $column => $value) {
  113. if (!$value) {
  114. $num_empty++;
  115. }
  116. }
  117. if ($num_empty == count(array_keys($values))) {
  118. return '';
  119. }
  120. // If the primary key column has a value but all other values are empty then
  121. // this is a delete.
  122. if (array_key_exists($pkey, $values) and $values[$pkey]) {
  123. $num_vals = 0;
  124. foreach ($values as $value) {
  125. if ($value) {
  126. $num_vals++;
  127. }
  128. }
  129. if ($num_vals == 1) {
  130. $new_vals[$pkey] = $values[$pkey];
  131. if (!chado_delete_record($table_name, $new_vals)) {
  132. throw new Exception('Could not delete record from table: "' . $table_name . '".');
  133. }
  134. return '';
  135. }
  136. }
  137. // If the primary key column does not have a value then this is an insert.
  138. if (!array_key_exists($pkey, $values) or !$values[$pkey] or !isset($values[$pkey])) {
  139. // Before inserting, we want to make sure the record does not
  140. // already exist. Using the unique constraint check for a matching record.
  141. $options = array('is_duplicate' => TRUE);
  142. $is_duplicate = chado_select_record($table_name, array('*'), $values, $options);
  143. if($is_duplicate) {
  144. $record = chado_select_record($table_name, array('*'), $values);
  145. return $record[0]->$pkey;
  146. }
  147. // If this table_name is a linker table then we want to be sure to add in
  148. // the value for the $base_record_id it it isn't set. This would only
  149. // occur on an insert.
  150. if (array_key_exists($base_table, $fkeys) and $base_table != $table_name) {
  151. foreach ($fkeys[$base_table]['columns'] as $lkey => $rkey) {
  152. if ($rkey == $base_pkey and !array_key_exists($lkey, $values) or empty($values[$lkey])) {
  153. $values[$lkey] = $base_record_id;
  154. }
  155. }
  156. }
  157. // Insert the values array as a new record in the table but remove the
  158. // pkey as it should be set.
  159. $new_vals = $values;
  160. unset($new_vals[$pkey]);
  161. $record = chado_insert_record($table_name, $new_vals);
  162. if ($record === FALSE) {
  163. throw new Exception('Could not insert Chado record into table: "' . $table_name . '": ' . print_r($new_vals, TRUE));
  164. }
  165. return $record[$pkey];
  166. }
  167. // If we've made it to this point then this is an update.
  168. // TODO: what if the unique constraint matches another record? That is
  169. // not being tested for here.
  170. $match[$pkey] = $values[$pkey];
  171. if (!chado_update_record($table_name, $match, $values)) {
  172. drupal_set_message("Could not update Chado record in table: $table_name.", 'error');
  173. }
  174. return $values[$pkey];
  175. }
  176. /**
  177. * Implements hook_field_storage_pre_load().
  178. *
  179. * Adds a 'chado_record' object containing the base record for the
  180. * entity.
  181. */
  182. function tripal_chado_field_storage_pre_load($entity_type, $entities, $age,
  183. $fields, $options) {
  184. // Itereate through the entities and add in the Chado record.
  185. foreach ($entities as $id => $entity) {
  186. // Only deal with Tripal Entities.
  187. if ($entity_type != 'TripalEntity') {
  188. continue;
  189. }
  190. $record_id = NULL;
  191. if (property_exists($entity, 'chado_table')) {
  192. // Get the base table and record id for the fields of this entity.
  193. $base_table = $entity->chado_table;
  194. $type_field = $entity->chado_column;
  195. $record_id = $entity->chado_record_id;
  196. }
  197. else {
  198. $bundle = tripal_load_bundle_entity(array('name' => $entity->bundle));
  199. $base_table = $bundle->data_table;
  200. $type_field = $bundle->type_column;
  201. // Get the record id for the fields of this entity.
  202. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  203. $details = db_select($chado_entity_table, 'ce')
  204. ->fields('ce')
  205. ->condition('entity_id', $entity->id)
  206. ->execute()
  207. ->fetchObject();
  208. if ($details) {
  209. $record_id = isset($details->record_id) ? $details->record_id : '';
  210. }
  211. $entity->chado_table = $base_table;
  212. $entity->chado_record_id = $record_id;
  213. $entity->chado_column = $type_field;
  214. }
  215. if ($record_id) {
  216. // Get this table's schema.
  217. $schema = chado_get_schema($base_table);
  218. $pkey_field = $schema['primary key'][0];
  219. // Get the base record if one exists
  220. $columns = array('*');
  221. $match = array($pkey_field => $record_id);
  222. $record = chado_generate_var($base_table, $match);
  223. $entity->chado_record = $record;
  224. }
  225. }
  226. }
  227. /**
  228. * Implements hook_field_storage_load().
  229. *
  230. * Responsible for loading the fields from the Chado database and adding
  231. * their values to the entity.
  232. */
  233. function tripal_chado_field_storage_load($entity_type, $entities, $age,
  234. $fields, $options) {
  235. $load_current = $age == FIELD_LOAD_CURRENT;
  236. global $language;
  237. $langcode = $language->language;
  238. foreach ($entities as $id => $entity) {
  239. $base_table = $entity->chado_table;
  240. $type_field = $entity->chado_column;
  241. $record_id = $entity->chado_record_id;
  242. $record = $entity->chado_record;
  243. $schema = chado_get_schema($base_table);
  244. // Iterate through the entity's fields so we can get the column names
  245. // that need to be selected from each of the tables represented.
  246. $tables = array();
  247. foreach ($fields as $field_id => $ids) {
  248. // By the time this hook runs, the relevant field definitions have been
  249. // populated and cached in FieldInfo, so calling field_info_field_by_id()
  250. // on each field individually is more efficient than loading all fields in
  251. // memory upfront with field_info_field_by_ids().
  252. $field = field_info_field_by_id($field_id);
  253. $field_name = $field['field_name'];
  254. $field_type = $field['type'];
  255. $field_module = $field['module'];
  256. // Get the instance for this field. If no instance exists then skip
  257. // loading of this field. This can happen when a field is deleted from
  258. // a bundle using the user UI form.
  259. // TODO: how to deal with deleted fields?
  260. $instance = field_info_instance($entity_type, $field_name, $entity->bundle);
  261. if (!$instance) {
  262. continue;
  263. }
  264. // Skip fields that don't map to a Chado table.
  265. if (!array_key_exists('settings', $instance) or
  266. !array_key_exists('chado_table', $instance['settings'])) {
  267. continue;
  268. }
  269. // Get the Chado table and column for this field.
  270. $field_table = $instance['settings']['chado_table'];
  271. $field_column = $instance['settings']['chado_column'];
  272. // There are only two types of fields: 1) fields that represent a single
  273. // column of the base table, or 2) fields that represent a linked record
  274. // in a many-to-one relationship with the base table.
  275. // Type 1: fields from base tables.
  276. if ($field_table == $base_table) {
  277. // Set an empty value by default, and if there is a record, then update.
  278. $entity->{$field_name}['und'][0]['value'] = '';
  279. if ($record and property_exists($record, $field_column)) {
  280. // If the field column is an object then it's a FK to another table.
  281. // and because $record object is created by the chado_generate_var()
  282. // function we must go one more level deeper to get the value
  283. if (is_object($record->$field_column)) {
  284. $fkey_column = $field_column;
  285. foreach($schema['foreign keys'] as $table => $fk_details) {
  286. foreach($fk_details['columns'] as $lfkey => $rfkey) {
  287. if ($lfkey == $field_column) {
  288. $fkey_column = $rfkey;
  289. }
  290. }
  291. }
  292. $entity->{$field_name}['und'][0]['chado-' . $field_table . '__' . $field_column] = $record->$field_column->$fkey_column;
  293. }
  294. else {
  295. // For non FK fields we'll make the field value be the same
  296. // as the column value.
  297. $entity->{$field_name}['und'][0]['value'] = $record->$field_column;
  298. $entity->{$field_name}['und'][0]['chado-' . $field_table . '__' . $field_column] = $record->$field_column;
  299. }
  300. }
  301. // Allow the creating module to alter the value if desired. The
  302. // module should do this if the field has any other form elements
  303. // that need populationg besides the value which was set above.
  304. tripal_load_include_field_class($field_type);
  305. if (class_exists($field_type) and is_subclass_of($field_type, 'TripalField')) {
  306. $tfield = new $field_type($field, $instance);
  307. $tfield->load($entity, array('record' => $record));
  308. }
  309. // For text fields that were not handled by a TripalField class we
  310. // want to automatically expand those fields.
  311. else {
  312. if ($schema['fields'][$field_column]['type'] == 'text') {
  313. $record = chado_expand_var($record, 'field', "$field_table.$field_column");
  314. $entity->{$field_name}['und'][0]['value'] = $record->$field_column;
  315. // Text fields that have a text_processing == 1 setting need a
  316. // special 'format' element too:
  317. if (array(key_exists('text_processing', $instance['settings']) and
  318. $instance['settings']['text_processing'] == 1)) {
  319. // TODO: we need a way to write the format back to the
  320. // instance settings if the user changes it when using the form.
  321. $entity->{$field_name}['und'][0]['format'] = array_key_exists('format', $instance['settings']) ? $instance['settings']['format'] : 'full_html';
  322. }
  323. }
  324. }
  325. }
  326. // Type 2: fields for linked records. These fields will have any number
  327. // of form elements that might need populating so we'll offload the
  328. // loading of these fields to the field itself.
  329. if ($field_table != $base_table) {
  330. // Set an empty value by default, and let the hook function update it.
  331. $entity->{$field_name}['und'][0]['value'] = '';
  332. tripal_load_include_field_class($field_type);
  333. if (class_exists($field_type) && method_exists($field_type, 'load')) {
  334. $tfield = new $field_type($field, $instance);
  335. $tfield->load($entity, array('record' => $record));
  336. }
  337. }
  338. } // end: foreach ($fields as $field_id => $ids) {
  339. } // end: foreach ($entities as $id => $entity) {
  340. }
  341. /**
  342. * Merges the values of all fields into a single array keyed by table name.
  343. */
  344. function tripal_chado_field_storage_write_merge_fields($fields, $entity_type, $entity) {
  345. $all_fields = array();
  346. $base_fields = array();
  347. $field_items = array();
  348. // Iterate through all of the fields and organize them into a
  349. // new fields array keyed by the table name
  350. foreach ($fields as $field_id => $ids) {
  351. // Get the field name and information about it.
  352. $field = field_info_field_by_id($field_id);
  353. $field_name = $field['field_name'];
  354. $instance = field_info_instance('TripalEntity', $field['field_name'], $entity->bundle);
  355. // Some fields don't add data to
  356. // Chado so they don't have a table, but they are still attached to the
  357. // entity. Just skip these.
  358. if (!array_key_exists('chado_table', $instance['settings'])) {
  359. continue;
  360. }
  361. $chado_table = $instance['settings']['chado_table'];
  362. $chado_column = $instance['settings']['chado_column'];
  363. $base_table = $instance['settings']['base_table'];
  364. // Iterate through the field's items. Fields with cardinality ($delta) > 1
  365. // are multi-valued.
  366. $items = field_get_items($entity_type, $entity, $field_name);
  367. $temp = array();
  368. $field_items[$field_name] = $items;
  369. foreach ($items as $delta => $item) {
  370. // A field may have multiple items. The field can use items
  371. // indexed with "chado-" to represent values that should map directly
  372. // to chado tables and fields.
  373. $value_set = FALSE;
  374. foreach ($item as $item_name => $value) {
  375. $matches = array();
  376. if (preg_match('/^chado-(.*?)__(.*?)$/', $item_name, $matches)) {
  377. $table_name = $matches[1];
  378. $column_name = $matches[2];
  379. // If this field belongs to the base table then we just add
  380. // those values in... there's no delta.
  381. if ($table_name == $base_table) {
  382. $base_fields[$table_name][$column_name] = $value;
  383. }
  384. else {
  385. $temp[$table_name][$delta][$column_name] = $value;
  386. }
  387. $value_set = TRUE;
  388. }
  389. }
  390. // If there is no value set for the field using the
  391. // chado-[table_name]__[field name] naming schema then check if a 'value'
  392. // item is present and if so use that for the table column value.
  393. if (!$value_set and array_key_exists('value', $items[$delta]) and
  394. !is_array($items[$delta]['value'])) {
  395. // If this field belongs to the base table then we just add
  396. // those values in... there's no delta.
  397. if ($base_table == $chado_table) {
  398. $base_fields[$chado_table][$chado_column] = $item['value'];
  399. }
  400. else {
  401. $temp[$chado_table][$delta][$chado_column] = $item['value'];
  402. }
  403. }
  404. }
  405. // Now merge the records for this field with the $new_fields array
  406. foreach ($temp as $table_name => $details) {
  407. foreach ($details as $delta => $list) {
  408. $all_fields[$table_name][] = $list;
  409. }
  410. }
  411. }
  412. $all_fields = array_merge($base_fields, $all_fields);
  413. return [$all_fields, $field_items];
  414. }
  415. /**
  416. * Implements hook_field_storage_query().
  417. */
  418. function tripal_chado_field_storage_query($query) {
  419. // Initialize the result array.
  420. $result = array(
  421. 'TripalEntity' => array()
  422. );
  423. // There must always be an entity filter that includes the bundle. Otherwise
  424. // it would be too overwhelming to search every table of every content type
  425. // for a matching field.
  426. if (!array_key_exists('bundle', $query->entityConditions)) {
  427. return $result;
  428. }
  429. $bundle = tripal_load_bundle_entity(array('name' => $query->entityConditions['bundle']));
  430. if (!$bundle) {
  431. return;
  432. }
  433. $data_table = $bundle->data_table;
  434. $type_column = $bundle->type_column;
  435. $type_id = $bundle->type_id;
  436. $schema = chado_get_schema($data_table);
  437. $pkey = $schema['primary key'][0];
  438. // Initialize the Query object.
  439. $cquery = chado_db_select($data_table, 'base');
  440. $cquery->fields('base', array($pkey));
  441. // Iterate through all the conditions and add to the filters array
  442. // a chado_select_record compatible set of filters.
  443. foreach ($query->fieldConditions as $index => $condition) {
  444. $field = $condition['field'];
  445. $field_name = $field['field_name'];
  446. $field_type = $field['type'];
  447. // Skip conditions that don't belong to this storage type.
  448. if ($field['storage']['type'] != 'field_chado_storage') {
  449. continue;
  450. }
  451. // The Chado settings for a field are part of the instance and each bundle
  452. // can have the same field but with different Chado mappings. Therefore,
  453. // we need to iterate through the bundles to get the field instances.
  454. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  455. // If there is a bundle filter for the entity and if the field is not
  456. // associated with the bundle then skip it.
  457. if (array_key_exists('bundle', $query->entityConditions)) {
  458. if (strtolower($query->entityConditions['bundle']['operator']) == 'in' and
  459. !array_key_exists($bundle_name, $query->entityConditions['bundle']['value'])) {
  460. continue;
  461. }
  462. else if ($query->entityConditions['bundle']['value'] != $bundle_name) {
  463. continue;
  464. }
  465. }
  466. // Allow the field to update the query object.
  467. $instance = field_info_instance('TripalEntity', $field['field_name'], $bundle_name);
  468. if (tripal_load_include_field_class($field_type)) {
  469. $field_obj = new $field_type($field, $instance);
  470. $field_obj->query($cquery, $condition);
  471. }
  472. // If there is not a ChadoField class for this field then add the
  473. // condition as is.
  474. else {
  475. $alias = $field['field_name'];
  476. $chado_table = $instance['settings']['chado_table'];
  477. $base_table = $instance['settings']['base_table'];
  478. $bschema = chado_get_schema($base_table);
  479. $bpkey = $bschema['primary key'][0];
  480. if ($chado_table == $base_table) {
  481. // Get the base table column that is associated with the term
  482. // passed as $condition['column'].
  483. $base_field = chado_get_semweb_column($chado_table, $condition['column']);
  484. $matches = array();
  485. $key = $condition['value'];
  486. $op = array_key_exists('operator', $condition) ? $condition['operator'] : '=';
  487. if (preg_match('/^(.+);(.+)$/', $key, $matches)) {
  488. $key = $matches[1];
  489. $op = $matches[2];
  490. }
  491. switch ($op) {
  492. case 'eq':
  493. $op = '=';
  494. break;
  495. case 'gt':
  496. $op = '>';
  497. break;
  498. case 'gte':
  499. $op = '>=';
  500. break;
  501. case 'lt':
  502. $op = '<';
  503. break;
  504. case 'lte':
  505. $op = '<=';
  506. break;
  507. case '<>':
  508. case 'ne':
  509. $op = '!=';
  510. break;
  511. case 'LIKE':
  512. case 'contains':
  513. $op = 'LIKE';
  514. if (!preg_match('/\%/', $key)) {
  515. $key = '%' . $key . '%';
  516. }
  517. break;
  518. case 'NOT LIKE':
  519. $op = 'NOT LIKE';
  520. if (!preg_match('/\%/', $key)) {
  521. $key = '%' . $key . '%';
  522. }
  523. break;
  524. case 'starts':
  525. $op = 'LIKE';
  526. $key = $key . '%';
  527. break;
  528. default:
  529. $op = '=';
  530. }
  531. $cquery->condition('base.' . $base_field , $key, $op);
  532. }
  533. if ($chado_table != $base_table) {
  534. // TODO: I don't think we'll get here because linker fields will
  535. // always have a custom field that should implement a query()
  536. // function. But just in case here's a note to handle it.
  537. }
  538. }
  539. }
  540. } // end foreach ($query->fieldConditions as $index => $condition) {
  541. // Now join with the chado entity table to get published records only.
  542. $chado_entity_table = chado_get_bundle_entity_table($bundle);
  543. $cquery->join($chado_entity_table, 'CE', "CE.record_id = base.$pkey");
  544. $cquery->join('tripal_entity', 'TE', "CE.entity_id = TE.id");
  545. $cquery->fields('CE', array('entity_id'));
  546. $cquery->fields('TE', array('bundle'));
  547. if (array_key_exists('start', $query->range)) {
  548. $cquery->range($query->range['start'], $query->range['length']);
  549. }
  550. // Make sure we only get records of the correct entity type
  551. $cquery->condition('TE.bundle', $query->entityConditions['bundle']['value']);
  552. // Iterate through all the property conditions. These will be filters
  553. // on the tripal_entity table.
  554. foreach ($query->propertyConditions as $index => $condition) {
  555. $cquery->condition('TE.' . $condition['column'], $condition['value']);
  556. }
  557. // If there is an entity_id filter then apply that.
  558. if (array_key_exists('entity_id', $query->entityConditions)) {
  559. $value = $query->entityConditions['entity_id']['value'];
  560. $op = '';
  561. if (array_key_exists('op', $query->entityConditions['entity_id'])) {
  562. $op = $query->entityConditions['entity_id']['op'];
  563. }
  564. // Handle a single entity_id
  565. if (!is_array($value)) {
  566. switch ($op) {
  567. case 'CONTAINS':
  568. $op = 'LIKE';
  569. $value = '%' . $value . '%';
  570. break;
  571. case 'STARTS_WITH':
  572. $op = 'LIKE';
  573. $value = $value . '%';
  574. break;
  575. case 'BETWEEN':
  576. // This case doesn't make sense for a single value. So, just set it
  577. // equal to the end.
  578. $op = '=';
  579. default:
  580. $op = $op ? $op : '=';
  581. }
  582. }
  583. // Handle multiple entitie IDs.
  584. else {
  585. switch ($op) {
  586. case 'CONTAINS':
  587. $op = 'IN';
  588. break;
  589. case 'STARTS_WITH':
  590. $op = 'IN';
  591. break;
  592. case 'BETWEEN':
  593. $op = 'BETWEEN';
  594. default:
  595. $op = 'IN';
  596. }
  597. }
  598. if ($op == 'BETWEEN') {
  599. $cquery->condition('TE.id', $value[0], '>');
  600. $cquery->condition('TE.id', $value[1], '<');
  601. }
  602. else {
  603. $cquery->condition('TE.id', $value, $op);
  604. }
  605. }
  606. // Now set any ordering.
  607. foreach ($query->order as $index => $sort) {
  608. // Add in property ordering.
  609. if ($sort['type'] == 'property') {
  610. // TODO: support ordering by bundle properties.
  611. }
  612. // Add in filter ordering
  613. if ($sort['type'] == 'field') {
  614. $field = $sort['specifier']['field'];
  615. $field_type = $field['type'];
  616. $field_name = $field['field_name'];
  617. // Skip sorts that don't belong to this storage type.
  618. if ($field['storage']['type'] != 'field_chado_storage') {
  619. continue;
  620. }
  621. $column = $sort['specifier']['column'];
  622. $direction = $sort['direction'];
  623. // The Chado settings for a field are part of the instance and each bundle
  624. // can have the same field but with different Chado mappings. Therefore,
  625. // we need to iterate through the bundles to get the field instances.
  626. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  627. // If there is a bundle filter for the entity and if the field is not
  628. // associated with the bundle then skip it.
  629. if (array_key_exists('bundle', $query->entityConditions)) {
  630. if (strtolower($query->entityConditions['bundle']['operator']) == 'in' and
  631. !array_key_exists($bundle_name, $query->entityConditions['bundle']['value'])) {
  632. continue;
  633. }
  634. else if ($query->entityConditions['bundle']['value'] != $bundle_name) {
  635. continue;
  636. }
  637. }
  638. // See if there is a ChadoField class for this instance. If not then do
  639. // our best to order the field.
  640. $instance = field_info_instance('TripalEntity', $field_name, $bundle_name);
  641. if (tripal_load_include_field_class($field_type)) {
  642. $field_obj = new $field_type($field, $instance);
  643. $field_obj->queryOrder($cquery, array('column' => $column, 'direction' => $direction));
  644. }
  645. // There is no class so do our best to order the data by this field
  646. else {
  647. $base_table = $instance['settings']['base_table'];
  648. $chado_table = $instance['settings']['chado_table'];
  649. $table_column = chado_get_semweb_column($chado_table, $column);
  650. if ($table_column) {
  651. if ($chado_table == $base_table) {
  652. $cquery->orderBy('base.' . $table_column, $direction);
  653. }
  654. else {
  655. // TODO: how do we handle a field that doesn't map to the base table.
  656. // We would expect that all of these would be custom field and
  657. // the ChadoField::queryOrder() function would be implemented.
  658. }
  659. }
  660. else {
  661. // TODO: handle when the name can't be matched to a table column.
  662. }
  663. }
  664. } // end foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  665. } // end if ($sort['type'] == 'field') {
  666. } // end foreach ($query->order as $index => $sort) {
  667. // Only include records that are deleted. Tripal doesn't keep track of
  668. // records that are deleted that need purging separately so we can do nothing
  669. // with this.
  670. if (property_exists($query, 'deleted') and $query->deleted) {
  671. // There won't ever be field data marked as deleted so just created a
  672. // condition that always evaluates to false.
  673. $cquery->where('1=0');
  674. }
  675. // Please keep these dpm's they help with debugging
  676. // dpm($cquery->__toString());
  677. // dpm($cquery->getArguments());
  678. $records = $cquery->execute();
  679. // If this is not a count query then return the results.
  680. $result = array();
  681. while ($record = $records->fetchObject()) {
  682. $ids = array($record->entity_id, 0, $record->bundle);
  683. $result['TripalEntity'][$record->entity_id] = entity_create_stub_entity('TripalEntity', $ids);
  684. }
  685. return $result;
  686. }
  687. /**
  688. * Implements hook_field_storage_bundle_mapping_form().
  689. *
  690. * This is a Tripal added hook to the field storage API.
  691. */
  692. function tripal_chado_field_storage_bundle_mapping_form($form, &$form_state,
  693. $term, &$submit_disabled) {
  694. $selected_term_id = (is_object($term)) ? $term->cvterm_id : NULL;
  695. // Initialize the form.
  696. $form = array();
  697. // Get the form default values.
  698. $default = array(
  699. 'table' => '',
  700. 'has_all' => 'No',
  701. 'use_cvterm' => 'cv',
  702. 'cv_id' => '',
  703. 'use_linker' => 'Yes',
  704. 'use_prop' => 'Yes',
  705. 'type_column' => '',
  706. 'prop_term_name' => '',
  707. 'prop_term_value' => '',
  708. );
  709. if (array_key_exists('base_chado_table', $form_state['values'])
  710. and $form_state['values']['base_chado_table']) {
  711. $default['table'] = $form_state['values']['base_chado_table'];
  712. }
  713. else {
  714. $mapped_table = chado_get_cvterm_mapping(array('cvterm_id' => $selected_term_id));
  715. if ($mapped_table) {
  716. $default['table'] = $mapped_table->chado_table;
  717. }
  718. }
  719. if (array_key_exists('chado_table_has_all', $form_state['values'])
  720. and $form_state['values']['chado_table_has_all']) {
  721. $default['has_all'] = $form_state['values']['chado_table_has_all'];
  722. }
  723. if (array_key_exists('chado_type_use_linker', $form_state['values'])
  724. and $form_state['values']['chado_type_use_linker']) {
  725. $default['use_linker'] = $form_state['values']['chado_type_use_linker'];
  726. }
  727. if (array_key_exists('chado_type_use_prop', $form_state['values'])
  728. and $form_state['values']['chado_type_use_prop']) {
  729. $default['use_prop'] = $form_state['values']['chado_type_use_prop'];
  730. }
  731. if (array_key_exists('type_column', $form_state['values'])
  732. and $form_state['values']['type_column']) {
  733. $default['type_column'] = $form_state['values']['type_column'];
  734. }
  735. if (array_key_exists('type_column_ignore', $form_state['values'])
  736. and $form_state['values']['type_column_ignore']) {
  737. $default['type_column_ignore'] = $form_state['values']['type_column_ignore'];
  738. }
  739. if (array_key_exists('prop_term_name', $form_state['values'])
  740. and $form_state['values']['prop_term_name']) {
  741. $default['prop_term_name'] = $form_state['values']['prop_term_name'];
  742. }
  743. if (array_key_exists('prop_term_value', $form_state['values'])
  744. and $form_state['values']['prop_term_value']) {
  745. $default['prop_term_value'] = $form_state['values']['prop_term_value'];
  746. }
  747. if (array_key_exists('chado_type_use_cv', $form_state['values'])
  748. and $form_state['values']['chado_type_use_cv']) {
  749. $default['use_cvterm'] = $form_state['values']['chado_type_use_cv'];
  750. }
  751. if (array_key_exists('chado_type_cv_id', $form_state['values'])
  752. and $form_state['values']['chado_type_cv_id']) {
  753. $default['cv_id'] = $form_state['values']['chado_type_cv_id'];
  754. }
  755. $form['selected_cvterm_id'] = array(
  756. '#type' => 'value',
  757. '#value' => $selected_term_id,
  758. );
  759. $base_tables = chado_get_base_tables();
  760. $options = array(0 => '-- Select table --');
  761. foreach ($base_tables AS $tablename) {
  762. $options[$tablename] = $tablename;
  763. }
  764. $form['base_chado_table'] = array(
  765. '#type' => 'select',
  766. '#title' => 'Chado table',
  767. '#options' => $options,
  768. '#description' => 'Select the Chado table into which the primary records for this content type will be stored.',
  769. '#default_value' => $default['table'],
  770. '#ajax' => array(
  771. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  772. 'wrapper' => "tripal-vocab-select-form",
  773. 'effect' => 'fade',
  774. 'method' => 'replace'
  775. ),
  776. );
  777. $form_state['input']['base_chado_table'] = $default['table'];
  778. // Return now if the user hasn't provided a table.
  779. if (!$default['table']) {
  780. return $form;
  781. }
  782. // Get the schema for this table.
  783. $schema = chado_get_schema($default['table']);
  784. // If the selected base table is 'cvterm' then handle it specially.
  785. if ($default['table'] == 'cvterm') {
  786. tripal_chado_field_storage_bundle_mapping_form_add_cvterm($form,
  787. $form_state, $term, $default);
  788. if ($default['use_cvterm'] == 'cv' and $default['cv_id']) {
  789. $submit_disabled = FALSE;
  790. }
  791. if ($default['use_cvterm'] == 'parent') {
  792. $submit_disabled = FALSE;
  793. }
  794. return $form;
  795. }
  796. // Ask the user if all of the records in the default table are of one type.
  797. tripal_chado_field_storage_bundle_mapping_form_add_allrecs($form,
  798. $form_state, $term, $default);
  799. // If all the records in the table are of this type then we're done.
  800. if ($default['has_all'] == 'Yes') {
  801. $submit_disabled = FALSE;
  802. return $form;
  803. }
  804. // If this table has a field that maps to a cvterm record then we want
  805. // to ask if the user wants to use that field.
  806. tripal_chado_field_storage_bundle_mapping_form_add_type($form,
  807. $form_state, $term, $default);
  808. // If the type_column is set then we're done! We know the deafult table
  809. // and column to map this data type.
  810. if (!empty($default['type_column'])) {
  811. $submit_disabled = FALSE;
  812. return $form;
  813. }
  814. // If the type column is not disabled and the user has not selected
  815. // a type then return.
  816. if (!$default['type_column_ignore'] and empty($default['type_column'])) {
  817. return $form;
  818. }
  819. // Let's set the names of the linker and prop table for use below.
  820. $linker_table = $default['table'] . '_cvterm';
  821. $prop_table = $default['table']. 'prop';
  822. $linker_exists = chado_table_exists($linker_table);
  823. $prop_exists = chado_table_exists($prop_table);
  824. // Ask the user if they want to use a linker table if it exists.
  825. if ($prop_exists) {
  826. tripal_chado_field_storage_bundle_mapping_form_add_prop($form,
  827. $form_state, $term, $prop_table, $default);
  828. // If the user wants to use the property table then we're done!
  829. if ($default['use_prop'] == 'Yes') {
  830. $submit_disabled = FALSE;
  831. return $form;
  832. }
  833. // Ask if the user wants to use the linker table if it exists.
  834. if ($linker_exists) {
  835. tripal_chado_field_storage_bundle_mapping_form_add_linker($form,
  836. $form_state, $term, $linker_table, $default);
  837. // If the user wants to use the linker table then we're done!
  838. if ($default['use_linker'] == 'Yes') {
  839. $submit_disabled = FALSE;
  840. return $form;
  841. }
  842. }
  843. }
  844. // A prop table doesn't exist then ask the user if they want
  845. // to use the linker table to associate records.
  846. else if ($linker_exists) {
  847. tripal_chado_field_storage_bundle_mapping_form_add_prop($form,
  848. $form_state, $term, $prop_table, $default);
  849. // If the user wants to use the linker table then we're done!
  850. if ($default['use_linker'] == 'Yes') {
  851. $submit_disabled = FALSE;
  852. return $form;
  853. }
  854. }
  855. $form['notice'] = array(
  856. '#type' => 'item',
  857. '#markup' => '<font color="red">Unfortunately, the options selected above do not allow for mapping of this content type to records in Chado.</font>'
  858. );
  859. return $form;
  860. }
  861. /**
  862. *
  863. */
  864. function tripal_chado_field_storage_bundle_mapping_form_add_type(&$form,
  865. &$form_state, $term, &$default){
  866. $term_name = $term->name;
  867. // Get the list of columns in the default table.
  868. $schema = chado_get_schema($default['table']);
  869. $column_options = array('none' => '--None--');
  870. $cvt_fkeys = (isset($schema['foreign keys']['cvterm'])) ? array_keys($schema['foreign keys']['cvterm']['columns']) : array();
  871. foreach ($schema['fields'] as $column_name => $column_details) {
  872. if (in_array($column_name, $cvt_fkeys)) {
  873. $column_options[$column_name] = $column_name;
  874. }
  875. }
  876. // If this table has no types then just return.
  877. if (count($column_options) == 1) {
  878. $default['type_column'] = '';
  879. return;
  880. }
  881. $default_column_ignore = !empty($default['type_column_ignore']) ? $default['type_column_ignore'] : 0;
  882. $default_column = !empty($default['type_column']) ? $default['type_column'] : 'type_id';
  883. $form['type_column'] = array(
  884. '#type' => 'select',
  885. '#title' => 'Type Column',
  886. '#options' => $column_options,
  887. '#description' => 'Please select the column in the "' .
  888. $default['table'] . '" table that will identify a record as being of type "' .
  889. $term_name . '". If you select "--None--" then you will be asked
  890. if you the type can be identified using a property or linker table.
  891. Only fields that have a foreign key to the cvterm table will be listed.',
  892. '#default_value' => $default_column,
  893. '#ajax' => array(
  894. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  895. 'wrapper' => "tripal-vocab-select-form",
  896. 'effect' => 'fade',
  897. 'method' => 'replace'
  898. ),
  899. '#disabled' => $default_column_ignore,
  900. );
  901. $form['type_column_ignore'] = array(
  902. '#type' => 'checkbox',
  903. '#title' => 'The type column does not distinguish the type',
  904. '#default_value' => $default_column_ignore,
  905. '#ajax' => array(
  906. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  907. 'wrapper' => "tripal-vocab-select-form",
  908. 'effect' => 'fade',
  909. 'method' => 'replace'
  910. ),
  911. );
  912. // Set the default value so we can short circuit the form.
  913. $default['type_column'] = $default_column;
  914. if ($default['type_column'] == 'none') {
  915. $default['type_column'] = '';
  916. }
  917. }
  918. /**
  919. *
  920. */
  921. function tripal_chado_field_storage_bundle_mapping_form_add_allrecs(&$form,
  922. &$form_state, $term, $default) {
  923. $term_name = $term->name;
  924. // Form elements to determine if all records in base table are of this type.
  925. $form['chado_table_has_all'] = array(
  926. '#type' => 'radios',
  927. '#options' => array(
  928. 'Yes' => 'Yes',
  929. 'No' => 'No'
  930. ),
  931. '#title' => 'Are all records in the "' . $default['table'] .
  932. '" table of type "'. $term_name . '"?',
  933. '#description' => 'Select "No" if the "' .
  934. $default['table'] . '" table houses more than just data of type "' .
  935. $term_name . '".',
  936. '#default_value' => $default['has_all'],
  937. '#ajax' => array(
  938. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  939. 'wrapper' => "tripal-vocab-select-form",
  940. 'effect' => 'fade',
  941. 'method' => 'replace'
  942. ),
  943. );
  944. }
  945. /**
  946. *
  947. */
  948. function tripal_chado_field_storage_bundle_mapping_form_add_linker(&$form,
  949. &$form_state, $term, $linker_table, $default){
  950. $form['chado_type_use_linker'] = array(
  951. '#type' => 'radios',
  952. '#title' => 'Do you want to use the "' . $linker_table . '" table
  953. to distinguish between content types?',
  954. '#options' => array(
  955. 'Yes' => 'Yes',
  956. 'No' => 'No'
  957. ),
  958. '#description' => t('Sometimes records can be distringuished
  959. using a linker table, especially if there is no column
  960. in the specified Chado table to identify the
  961. record type. In these cases the linker table can be used.'),
  962. '#default_value' => $default['use_linker'],
  963. '#ajax' => array(
  964. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  965. 'wrapper' => "tripal-vocab-select-form",
  966. 'effect' => 'fade',
  967. 'method' => 'replace'
  968. ),
  969. );
  970. }
  971. /**
  972. *
  973. */
  974. function tripal_chado_field_storage_bundle_mapping_form_add_prop(&$form,
  975. &$form_state, $term, $prop_table, $default){
  976. $form['chado_type_use_prop'] = array(
  977. '#type' => 'radios',
  978. '#title' => 'Do you want to use the "' . $prop_table . '" table
  979. to distinguish between content types?',
  980. '#options' => array(
  981. 'Yes' => 'Yes',
  982. 'No' => 'No'
  983. ),
  984. '#description' => t('Sometimes records can be distringuished
  985. using a value in property table, especially if there is no column
  986. in the specified Chado table to identify the
  987. record type. In these cases the property table can be used.'),
  988. '#default_value' => $default['use_prop'],
  989. '#ajax' => array(
  990. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  991. 'wrapper' => "tripal-vocab-select-form",
  992. 'effect' => 'fade',
  993. 'method' => 'replace'
  994. ),
  995. );
  996. if ($default['use_prop'] == 'Yes') {
  997. $prop_term_name = $default['prop_term_name'];
  998. $prop_term_value = $default['prop_term_value'];
  999. $form['prop_term_name'] = array(
  1000. '#title' => t('Property Type'),
  1001. '#type' => 'textfield',
  1002. '#description' => t('The content type "' . $term->name . '" must be
  1003. associated with a property type. The property type must be the
  1004. name of a term in a controlled vocabulary and the controlled
  1005. vocabulary should already be loaded into Tripal. Please select
  1006. the property type that will be used to identify records of this
  1007. type'),
  1008. '#required' => TRUE,
  1009. '#default_value' => $prop_term_name,
  1010. '#autocomplete_path' => "admin/tripal/storage/chado/auto_name/cvterm/",
  1011. );
  1012. $form['prop_term_select_button'] = array(
  1013. '#type' => 'submit',
  1014. '#value' => t('Lookup Term'),
  1015. '#name' => 'select_prop_cvterm',
  1016. '#ajax' => array(
  1017. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  1018. 'wrapper' => "tripal-vocab-select-form",
  1019. 'effect' => 'fade',
  1020. 'method' => 'replace'
  1021. ),
  1022. );
  1023. // If the term has been provided by the user then we want to search for
  1024. // matching terms in the database and let them select among any matches.
  1025. if ($prop_term_name) {
  1026. $form['prop_terms_list'] = array(
  1027. '#type' => 'fieldset',
  1028. '#title' => t('Matching Terms'),
  1029. '#description' => t('Please select the term the best matches the
  1030. property type.')
  1031. );
  1032. $match = array(
  1033. 'name' => $prop_term_name,
  1034. );
  1035. $pterms = chado_generate_var('cvterm', $match, array('return_array' => TRUE));
  1036. $pterms = chado_expand_var($pterms, 'field', 'cvterm.definition');
  1037. $num_terms = 0;
  1038. // Let the user select from any matching terms. Sometimes there may be
  1039. // more than one that match.
  1040. foreach ($pterms as $pterm) {
  1041. // Save the user a click by setting the default value as 1 if there's
  1042. // only one matching term.
  1043. $default = FALSE;
  1044. $attrs = array();
  1045. if ($num_terms == 0 and count($pterms) == 1) {
  1046. $default = TRUE;
  1047. $attrs = array('checked' => 'checked');
  1048. }
  1049. $term_element_name = 'prop_term-' . $pterm->cvterm_id;
  1050. $form['prop_terms_list'][$term_element_name] = array(
  1051. '#type' => 'checkbox',
  1052. '#title' => $pterm->name,
  1053. '#default_value' => $default,
  1054. '#attributes' => $attrs,
  1055. '#description' => '<b>Vocabulary:</b> ' . $pterm->cv_id->name . ' (' . $pterm->dbxref_id->db_id->name . ') ' . $pterm->cv_id->definition .
  1056. '<br><b>Term: </b> ' . $pterm->dbxref_id->db_id->name . ':' . $pterm->dbxref_id->accession . '. ' .
  1057. '<br><b>Definition:</b> ' . $pterm->definition,
  1058. '#ajax' => array(
  1059. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  1060. 'wrapper' => "tripal-vocab-select-form",
  1061. 'effect' => 'fade',
  1062. 'method' => 'replace'
  1063. ),
  1064. );
  1065. $num_terms++;
  1066. }
  1067. $form['prop_term_value'] = array(
  1068. '#type' => 'textfield',
  1069. '#title' => 'Property Value',
  1070. '#description' => t('All properties have a type and a value. Above you
  1071. indicated the type of property. Now you must specify the value
  1072. that this properly must have in order to be considered of
  1073. type "' . $term->name . '".'),
  1074. '#default_value' => $prop_term_value,
  1075. '#required' => TRUE,
  1076. );
  1077. }
  1078. }
  1079. }
  1080. /**
  1081. *
  1082. */
  1083. function tripal_chado_field_storage_bundle_mapping_form_add_cvterm(&$form,
  1084. &$form_state, $term, &$default){
  1085. $form['chado_type_use_cv'] = array(
  1086. '#type' => 'radios',
  1087. '#title' => 'How do you want to distinguish the "' . $term->name . '" records
  1088. within the cvterm table?',
  1089. '#options' => array(
  1090. 'cv' => 'All records that belong to a single controlled vocabulary?',
  1091. 'parent' => 'All child records of the specified term?'
  1092. ),
  1093. '#description' => t('Records in the cvterm table are often not used for content
  1094. types. The records in the cvterm table are meant to be vocabulary terms.
  1095. However, there are times when records in the cvterm table can be
  1096. used for a content type. One example is for trait "pages" that
  1097. use phenotype values stored in the phenotype table. Because records in
  1098. the cvterm table are vocabulary terms they do not have "types" so the
  1099. only ways to distinguish them are 1) to use the controlled vocabulary to
  1100. distinguish the records or 2) to use all children records of the
  1101. selected term. Please select the appropriate value for this case.'),
  1102. '#default_value' => $default['use_cvterm'],
  1103. '#ajax' => array(
  1104. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  1105. 'wrapper' => "tripal-vocab-select-form",
  1106. 'effect' => 'fade',
  1107. 'method' => 'replace'
  1108. ),
  1109. );
  1110. if ($default['use_cvterm'] == 'cv') {
  1111. $cvs = chado_get_cv_select_options();
  1112. $form['chado_type_cv_id'] = array(
  1113. '#type' => select,
  1114. '#options' => $cvs,
  1115. '#title' => t('Select a controlled vocabulary'),
  1116. '#default_value' => $default['cv_id'],
  1117. '#ajax' => array(
  1118. 'callback' => "tripal_admin_add_type_form_ajax_callback",
  1119. 'wrapper' => "tripal-vocab-select-form",
  1120. 'effect' => 'fade',
  1121. 'method' => 'replace'
  1122. ),
  1123. );
  1124. }
  1125. }
  1126. /**
  1127. * Implements hook_field_stoage_bundle_mapping_form_validate().
  1128. */
  1129. function tripal_chado_field_storage_bundle_mapping_form_validate($form, &$form_state) {
  1130. // Get the form values
  1131. $default = array(
  1132. 'table' => '',
  1133. 'has_all' => 'No',
  1134. 'use_cvterm' => 'cv',
  1135. 'cv_id' => '',
  1136. 'use_linker' => 'Yes',
  1137. 'use_prop' => 'Yes',
  1138. 'type_column' => '',
  1139. 'prop_term_name' => '',
  1140. 'prop_term_value' => '',
  1141. );
  1142. if (array_key_exists('base_chado_table', $form_state['values'])
  1143. and $form_state['values']['base_chado_table']) {
  1144. $default['table'] = $form_state['values']['base_chado_table'];
  1145. }
  1146. if (array_key_exists('chado_table_has_all', $form_state['values'])
  1147. and $form_state['values']['chado_table_has_all']) {
  1148. $default['has_all'] = $form_state['values']['chado_table_has_all'];
  1149. }
  1150. if (array_key_exists('chado_type_use_linker', $form_state['values'])
  1151. and $form_state['values']['chado_type_use_linker']) {
  1152. $default['use_linker'] = $form_state['values']['chado_type_use_linker'];
  1153. }
  1154. if (array_key_exists('chado_type_use_prop', $form_state['values'])
  1155. and $form_state['values']['chado_type_use_prop']) {
  1156. $default['use_prop'] = $form_state['values']['chado_type_use_prop'];
  1157. }
  1158. if (array_key_exists('type_column', $form_state['values'])
  1159. and $form_state['values']['type_column']) {
  1160. $default['type_column'] = $form_state['values']['type_column'];
  1161. }
  1162. if (array_key_exists('prop_term_name', $form_state['values'])
  1163. and $form_state['values']['prop_term_name']) {
  1164. $default['prop_term_name'] = $form_state['values']['prop_term_name'];
  1165. // Make sure we have only one property cvterm selected
  1166. $num_selected = 0;
  1167. foreach ($form_state['values'] as $key => $value) {
  1168. $matches = array();
  1169. if (preg_match("/^prop_term-(\d+)$/", $key, $matches) and
  1170. $form_state['values']['prop_term-' . $matches[1]]) {
  1171. $cvterm_id = $matches[1];
  1172. $term = chado_generate_var('cvterm', array('cvterm_id' => $cvterm_id));
  1173. $num_selected++;
  1174. }
  1175. }
  1176. if ($num_selected == 0) {
  1177. form_set_error('', 'Please select at least one property term.');
  1178. }
  1179. else if ($num_selected > 1) {
  1180. form_set_error('prop_term-' . $cvterm_id, 'Please select only one property term from the list below.');
  1181. }
  1182. $form_state['prop_term'] = $term;
  1183. }
  1184. if (array_key_exists('prop_term_value', $form_state['values'])
  1185. and $form_state['values']['prop_term_value']) {
  1186. $default['prop_term_value'] = $form_state['values']['prop_term_value'];
  1187. }
  1188. if (array_key_exists('chado_type_use_cv', $form_state['values'])
  1189. and $form_state['values']['chado_type_use_cv']) {
  1190. $default['use_cvterm'] = $form_state['values']['chado_type_use_cv'];
  1191. }
  1192. if (array_key_exists('chado_type_cv_id', $form_state['values'])
  1193. and $form_state['values']['chado_type_cv_id']) {
  1194. $default['cv_id'] = $form_state['values']['chado_type_cv_id'];
  1195. }
  1196. // Make sure a default table is selected
  1197. if (!$default['table']) {
  1198. form_set_error('base_chado_table', 'Please select a default table.');
  1199. }
  1200. }
  1201. /**
  1202. * Implements hook_field_stoage_bundle_mapping_form_submit().
  1203. *
  1204. * Here we do no action on submit other than set the storage_args
  1205. * variable that is passed by reference.
  1206. */
  1207. function tripal_chado_field_storage_bundle_mapping_form_submit($form,
  1208. &$form_state, $term, &$storage_args) {
  1209. // Get the form values
  1210. $default = array(
  1211. 'table' => '',
  1212. 'has_all' => 'No',
  1213. 'use_cvterm' => '',
  1214. 'cv_id' => '',
  1215. 'use_linker' => 'No',
  1216. 'use_prop' => 'No',
  1217. 'type_column' => '',
  1218. 'prop_term_name' => '',
  1219. 'prop_term_value' => '',
  1220. );
  1221. if (array_key_exists('base_chado_table', $form_state['values'])
  1222. and $form_state['values']['base_chado_table']) {
  1223. $default['table'] = $form_state['values']['base_chado_table'];
  1224. }
  1225. if (array_key_exists('chado_table_has_all', $form_state['values'])
  1226. and $form_state['values']['chado_table_has_all']) {
  1227. $default['has_all'] = $form_state['values']['chado_table_has_all'];
  1228. }
  1229. if (array_key_exists('chado_type_use_linker', $form_state['values'])
  1230. and $form_state['values']['chado_type_use_linker']) {
  1231. $default['use_linker'] = $form_state['values']['chado_type_use_linker'];
  1232. }
  1233. if (array_key_exists('chado_type_use_prop', $form_state['values'])
  1234. and $form_state['values']['chado_type_use_prop']) {
  1235. $default['use_prop'] = $form_state['values']['chado_type_use_prop'];
  1236. }
  1237. if (array_key_exists('type_column', $form_state['values'])
  1238. and $form_state['values']['type_column']) {
  1239. $default['type_column'] = $form_state['values']['type_column'];
  1240. }
  1241. if (array_key_exists('prop_term_name', $form_state['values'])
  1242. and $form_state['values']['prop_term_name']) {
  1243. $default['prop_term_name'] = $form_state['values']['prop_term_name'];
  1244. }
  1245. if (array_key_exists('prop_term_value', $form_state['values'])
  1246. and $form_state['values']['prop_term_value']) {
  1247. $default['prop_term_value'] = $form_state['values']['prop_term_value'];
  1248. }
  1249. if (array_key_exists('chado_type_use_cv', $form_state['values'])
  1250. and $form_state['values']['chado_type_use_cv']) {
  1251. $default['use_cvterm'] = $form_state['values']['chado_type_use_cv'];
  1252. }
  1253. if (array_key_exists('chado_type_cv_id', $form_state['values'])
  1254. and $form_state['values']['chado_type_cv_id']) {
  1255. $default['cv_id'] = $form_state['values']['chado_type_cv_id'];
  1256. }
  1257. // If the user selected to use the cvterm table then we have to
  1258. // handle it specially.
  1259. if ($default['use_cvterm'] == 'cv' and !empty($default['cv_id'])) {
  1260. $storage_args['data_table'] = $default['table'];
  1261. $storage_args['type_id'] = $form_state['values']['selected_cvterm_id'];
  1262. $storage_args['type_value'] = '';
  1263. if ($default['cv_id']) {
  1264. $storage_args['type_value'] = $default['cv_id'];
  1265. }
  1266. $storage_args['type_column'] = '';
  1267. return;
  1268. }
  1269. // If we have a type_column then we know this type uses a column in the
  1270. // base table, so we can set the storage args and return.
  1271. if ($default['type_column'] and $default['type_column'] != 'none') {
  1272. $storage_args['data_table'] = $default['table'];
  1273. $storage_args['type_column'] = $default['type_column'];
  1274. return;
  1275. }
  1276. // If the user indicated that all the records in a table are of this type.
  1277. if ($default['has_all'] == 'Yes') {
  1278. $storage_args['data_table'] = $default['table'];
  1279. $storage_args['type_id'] = $form_state['values']['selected_cvterm_id'];
  1280. $storage_args['type_linker_table'] = '';
  1281. $storage_args['type_column'] = '';
  1282. $storage_args['type_value'] = '';
  1283. }
  1284. // If the user indicated they wanted to use the prop table then we'll
  1285. // set the storage args and return.
  1286. else if ($default['use_prop'] == 'Yes') {
  1287. $storage_args['data_table'] = $default['table'];
  1288. $storage_args['type_linker_table'] = $default['table'] . 'prop';
  1289. $storage_args['type_column'] = 'type_id';
  1290. $storage_args['type_id'] = $form_state['prop_term']->cvterm_id;
  1291. $storage_args['type_value'] = $default['prop_term_value'];
  1292. }
  1293. // If the user indicated they wanted to use the linker tables then we'll
  1294. // set the storage args and return.
  1295. else if ($default['use_linker'] == 'Yes') {
  1296. $storage_args['data_table'] = $default['table'];
  1297. $storage_args['type_id'] = $form_state['values']['selected_cvterm_id'];
  1298. $storage_args['type_linker_table'] = $default['table'] . '_cvterm';
  1299. $storage_args['type_column'] = 'cvterm_id';
  1300. }
  1301. }