EntityFieldQuery d7

WebMaster's picture
  • For general samples see How to use EntityFieldQuery. Here we highlight only important tips
  • 1. propertyCondition

  • There is a confusion between propertyCondition and fieldCondition. The most common is node title. Correct use
  • ->propertyCondition('title', 'blah', 'CONTAINS')

    2. fieldCondition

    • ->fieldCondition('body', 'value', 'A', 'STARTS_WITH')
    • column. This is the column in the database that should be matched, with field name prefix removed. For body field, the database columns are: body_value, body_summary, body_format, and language. 'value', 'summary', 'format', and 'language' are the actual arguments you would use. Likewise an image field would use 'fid', 'alt', and 'title' as column names; an entity reference field would use 'target_id' and 'target_type' as column names.
      • This is a real drupalism
    • Tip For other custom modules, checking the hook_field_schema() makes it easy to identity the column name
    <?php
     
    // Implements hook_field_info().
    function rolereference_field_schema($field) {
     
    $columns = array(
       
    'rid' => array(
         
    'type' => 'int',
         
    'unsigned' => TRUE,
         
    'not null' => FALSE,
        ),
      );
      return array(
       
    'columns' => $columns,
       
    'indexes' => array('rid' => array('rid')),
       
    'foreign keys' => array(
         
    'rid' => array(
           
    'table' => 'role',
           
    'columns' => array('rid' => 'rid'),
          ),
        ),
      );
    }
    ?>


  • Implementation in EntityFieldQuery
  • ->fieldCondition('field_ref_role', 'rid' , $rid ,'=')

    3. Multi step conditions

  • Best approach, sample code via Querying to get a list of taxonomy terms or nodes using EntityFieldQuery
  • <?php
    $query
    = new EntityFieldQuery();
     
    $entities = $query->entityCondition('entity_type', 'node')
        ->
    entityCondition('bundle', 'article')
        ->
    fieldCondition('field_ref_role', 'rid' , $rid ,'=')
        ->
    propertyOrderBy('created', $direction = 'DESC')
        ->
    range(0,1);

      if (

    in_array('power user', $user->roles)) {
       
    $entities->fieldCondition('field_dummy','value',$myvalue,'=');
      }
     
    $result = $entities->execute();
    ?>


  • Tag approach, doesn't work with field condition, via
  • <?php
    function mymodule_superblock(){
       
    $query = new EntityFieldQuery();
           
    $result = $query
               
    ->entityCondition('entity_type', 'node')
                ->
    fieldCondition('field_categories', 'tid', array('12','13'), 'IN')
                ->
    propertyCondition('status', 1)
                ->
    addTag('random')
                ->
    range(0,5)
                ->
    execute();
    }
    function
    mymodule_query_random_alter($query){
       
    $query->orderRandom();
    }
    ?>


    Drupal documentation wiki style