How can i ommit an condition in Entity Field Query if variable do not exist, for example

->fieldCondition('field_filter_color', 'tid', $filter_color)

Recieves in $filter_color one term id. But there are situations where $filter_color is not present, so i would like to do: if $filter_color is empty, ignore this condition.

Alternative is to present it as an array like

->fieldCondition('field_filter_color', 'tid', $filter_color, 'IN')

and prepopulate all values in $filter_color, and if $filter_color is chosen, create array with only one value, but i am not sure it is best way to do it.

2 Answers 2


You can simply do this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
// all other conditions go here

if (isset($my_field_val)) {
  $query->fieldCondition('my_field', 'value', $my_field_val);
$result = $query->execute();

Untried code as I don't have access to my files at the moment.


Unfortunately EntityFieldQuery can only query for what is there, it doesn't have the capacity to query based on empty fields.

However cumbersome it might be, your solution is about all you can do other than add a tag to the query, and implement hook_query_alter() to manually add the "empty" condition to it.

  • Thanks! I am thinking, can i somehow achieve to exclude whole parameter ( ->fieldCondition ... on some external condition). That way, if condition is met, ->fieldCondition is in the query, if not, it is not. But i guess i would need somehow to "construct" whole query on the fly ?
    – NenadP
    Sep 8, 2012 at 15:48
  • 1
    To be honest I normally just construct my own queries and go into the field tables directly when EntityFieldQuery's limitations kick in. If you're using MySQL for field storage it's probably easier than trying to work round the problem, however creative you get
    – Clive
    Sep 8, 2012 at 16:08
  • You mean, you use db_select ? I am thinking hard how to stay in EntityFieldQuery for this task, for now if $field_color is not defined, i offer for $field_color an array with all values to simulate non-existance of value :D
    – NenadP
    Sep 8, 2012 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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