0

What is the Drupal way of creating queries which are dynamic in nature ? What I mean is for example- In my module I am asking the user to select some content types and the fields associated with each of them. If node type "article" is present the user can select it and also select some fields lets say- field3, field4 - out of all the fields present field1-10. This custom selection is then stored in a table lets say "custom_table"

How can i create queries of the form- 
db_select('node','n')
->fields('n','field3','field4') //fields are dynamic based on user's choice stored in custom_table
->condition('n.node-type', 'article') //node type is dynamic based on user's choice stored in custom_table
->join with fields table to get field value //only for value fields

I really dont want to use php string handling and create a "select from node..." type string while looping over values in custom_table.

Is there a less time and space complex drupal way to achieve this ?

1 Answer 1

2

Don't chain your query, just put in some ifs and add to the query. Like so

$query = db_select('node', 'n');
if(isset($field)) {
  // Add each field separate
  $query->addField('n', 'title', 'title');
}

if(isset($article)) {
  $query->condition('n.node-type', 'article', '=');
}

if(isset($join)) {
  $query->join()....
}

$query->execute();

I think this will get you to where you want. Please also see this thread: http://drupal.org/node/310075

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.