Key Takeaways
- EntityFieldQuery is a class in Drupal that allows developers to fetch information about entities from the database without having to write SQL queries, making it easier to retrieve, filter, and sort data. This is particularly useful when needing to fetch data from multiple tables or when wanting to apply complex conditions to queries.
- The EntityFieldQuery class can be extended to create your own child class, allowing you to build the same query in multiple places. For example, you may want to build a query to get all active users in ascending order of their creation date. This can be achieved by creating a new class that extends EntityFieldQuery and sets the appropriate conditions and order.
- EntityFieldQuery supports various methods such as `entityCondition` for fetching data from a specific entity type, `propertyCondition` for adding conditions based on the properties of the entity, `fieldCondition` for fetching data from custom fields, and `propertyOrderBy` for sorting the results. However, it only supports fetching data from one entity type at a time. If you need to fetch data from multiple entity types, you will need to run separate queries for each type.
Introduction
When building complex web apps, you’ll eventually have to interact with a database. To retrieve data in Drupal one can use the database abstraction layer provided, which requires some SQL knowledge to be used properly. From Drupal 7 EntityFieldQuery API is provided, which lets you fetch information about entities from Drupal without actually building SQL queries. In this article, let’s see how we can use the EntityFieldQuery API to fetch data from Drupal and use it in our modules.
The EntityFieldQuery class
The EntityFieldQuery class is used to find entities in Drupal, which match some conditions. The EntityFieldQuery is present in the includes/entity.inc file in your Drupal installation.
This class has different methods to specify the entity type and certain conditions based on which we can filter which data we want to fetch. We will see those methods in detail throughout this article.
The basic usage, which you will follow while using EntityFieldQuery will be, first and foremost, creating an object of this class. Once the object is created you will add some conditions to it and then call the execute method to fetch the results.
The general template is as follows
<span>$entityquery = new EntityFieldQuery(); </span><span>/// Set some conditions </span><span>$result = $query->execute ();</span>
We are now going to create a Drupal module which will install 3 new Drupal node types: Product, Movies and Books and a block in which we will display our results. You can see how to create a node type in this article
The code for the module is
entityquery.info
name <span>= entityquery </span>description <span>= Shows how to use entity query to fetch data from drupal </span>package <span>= Entity Query Example </span>core <span>= 7.x</span>
entityquery.install
<span><span><?php </span></span><span><span>/** </span></span><span><span> * Implement hook_install(). </span></span><span><span> */ </span></span><span><span>function entityquery_install() { </span></span><span> <span>node_types_rebuild(); </span></span><span> <span>$types = node_type_get_types(); </span></span><span> <span>node_add_body_field($types['product']); </span></span><span> <span>node_add_body_field($types['movies']); </span></span><span> <span>node_add_body_field($types['books']); </span></span><span><span>}</span></span>
entityquery.module
<span>$entityquery = new EntityFieldQuery(); </span><span>/// Set some conditions </span><span>$result = $query->execute ();</span>
Put this module in your modules folder and if everything has gone well you will be able to see the entityquery module in your module list as shown below.
Once you have installed the module you should be able to see the new node types also in the Add content section of your Drupal admin panel as follows
Executing a simple query using EntityFieldQuery
Once we have the basic module set up for using EntityFieldQuery, let’s start writing some queries to fetch data from Drupal. The first query we will write is to get all the nodes using EntityFieldQuery. Then we will use that to display the titles of the nodes in our block.
As stated earlier the first thing to do is to create an instance of EFQ. To fetch a type of entity you have to add the entity_type condition to it. In this case we want to fetch nodes so the code for it will be as follows:
name <span>= entityquery </span>description <span>= Shows how to use entity query to fetch data from drupal </span>package <span>= Entity Query Example </span>core <span>= 7.x</span>
The entity condition is set using the function entityCondition in which we are setting the entity type as node. Once we have set the entity condition, we are ready to execute the query. The node ids are returned in an array in the node key of the result. The complete code to display the nodes will be as follows:
<span><span><?php </span></span><span><span>/** </span></span><span><span> * Implement hook_install(). </span></span><span><span> */ </span></span><span><span>function entityquery_install() { </span></span><span> <span>node_types_rebuild(); </span></span><span> <span>$types = node_type_get_types(); </span></span><span> <span>node_add_body_field($types['product']); </span></span><span> <span>node_add_body_field($types['movies']); </span></span><span> <span>node_add_body_field($types['books']); </span></span><span><span>}</span></span>
Now if you go and see your block you should be able to see all nodes in it as follows
You should now try to add different nodes like movies and books and check them being displayed in the block. In the above, code once we have the node ids from EntityFieldQuery, we load the nodes using node_load_multiple and display them.
Adding entity conditions to EntityFieldQuery
You can add entity conditions to show only particular types of nodes. If we want to display only “products” from the type of nodes, the query we will use is:
<span><span><?php </span></span><span><span>/** </span></span><span><span> * Implement hook_node_info() </span></span><span><span> */ </span></span><span><span>function entityquery_node_info() { </span></span><span> <span>return array( </span></span><span> <span>'product' => array( </span></span><span> <span>'name' => t('Product'), </span></span><span> <span>'base' => 'product', </span></span><span> <span>'description' => t('You can define new Products here'), </span></span><span> <span>'has_title' => TRUE, </span></span><span> <span>'title_label' => t('Product title') </span></span><span> <span>), </span></span><span> <span>'movies' => array( </span></span><span> <span>'name' => t('Movies'), </span></span><span> <span>'base' => 'movies', </span></span><span> <span>'description' => t('You can define new Movies here'), </span></span><span> <span>'has_title' => TRUE, </span></span><span> <span>'title_label' => t('Movie title') </span></span><span> <span>), </span></span><span> <span>'books' => array( </span></span><span> <span>'name' => t('Books'), </span></span><span> <span>'base' => 'Books', </span></span><span> <span>'description' => t('You can define new Books here'), </span></span><span> <span>'has_title' => TRUE, </span></span><span> <span>'title_label' => t('Books title') </span></span><span> <span>) </span></span><span> <span>); </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Implement hook_form() </span></span><span><span> */ </span></span><span><span>function product_form($node, $form_state) { </span></span><span> <span>return node_content_form($node, $form_state); </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Implement hook_form() </span></span><span><span> */ </span></span><span><span>function movies_form($node, $form_state) { </span></span><span> <span>return node_content_form($node, $form_state); </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Implement hook_form() </span></span><span><span> */ </span></span><span><span>function books_form($node, $form_state) { </span></span><span> <span>return node_content_form($node, $form_state); </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Implement hook_block_info(). </span></span><span><span> */ </span></span><span><span>function entityquery_block_info() { </span></span><span> <span>$blocks = array(); </span></span><span> </span><span> <span>$blocks['entityqueryblock'] = array( </span></span><span> <span>'info' => t('A block to display results from entityquery'), </span></span><span> <span>); </span></span><span> </span><span> <span>return $blocks; </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Implement hook_block_view(). </span></span><span><span> */ </span></span><span><span>function entityquery_block_view($block_name = '') { </span></span><span> <span>if ($block_name == 'entityqueryblock') { </span></span><span> <span>$content =''; </span></span><span> <span>$block = array( </span></span><span> <span>'subject' => t('A block to display results from entityquery'), </span></span><span> <span>'content' => $content, </span></span><span> <span>); </span></span><span> <span>return $block; </span></span><span> <span>} </span></span><span><span>}</span></span>
Now if we check our block it will display only products:
We can even specify an array of node types to fetch multiple types of nodes using entityCondition. To fetch all products and movies from your database:
<span>$query = new EntityFieldQuery(); </span><span>$query->entityCondition('entity_type', 'node');</span>
Adding property conditions to EntityFieldQuery
We can even add property conditions to the query. These would depend on the entity type you are querying for. In most cases, the property condition will be on the fields of the entity type you are querying for. You can, for example, query for nodes which are published, or are written by a particular user etc.
The query to show only published nodes using propertyCondition is as follows
<span>$entityquery = new EntityFieldQuery(); </span><span>/// Set some conditions </span><span>$result = $query->execute ();</span>
Adding field conditions to EntityFieldQuery and ordering
The field conditions are specific to the fields which are present on the entity. So suppose we want to find all the products which have the word discount in their body – we can do it using the field condition. We can even order the results using the propertyOrderBy function.
If we want the products and movies which have “discount” in their body, arranged in descending order of their creation, the query will be as follows:
name <span>= entityquery </span>description <span>= Shows how to use entity query to fetch data from drupal </span>package <span>= Entity Query Example </span>core <span>= 7.x</span>
The output of this query will be as follows
Extending the EntityFieldQuery class
Sometimes, you might have to build the same query in many places. A good way to abstract that would be to extend the EntityFieldQuery class and create your own child class.
Suppose you want to build a query to get all active users in ascending order of their creation date:
<span><span><?php </span></span><span><span>/** </span></span><span><span> * Implement hook_install(). </span></span><span><span> */ </span></span><span><span>function entityquery_install() { </span></span><span> <span>node_types_rebuild(); </span></span><span> <span>$types = node_type_get_types(); </span></span><span> <span>node_add_body_field($types['product']); </span></span><span> <span>node_add_body_field($types['movies']); </span></span><span> <span>node_add_body_field($types['books']); </span></span><span><span>}</span></span>
Now you can use this query anywhere like so:
<span><span><?php </span></span><span><span>/** </span></span><span><span> * Implement hook_node_info() </span></span><span><span> */ </span></span><span><span>function entityquery_node_info() { </span></span><span> <span>return array( </span></span><span> <span>'product' => array( </span></span><span> <span>'name' => t('Product'), </span></span><span> <span>'base' => 'product', </span></span><span> <span>'description' => t('You can define new Products here'), </span></span><span> <span>'has_title' => TRUE, </span></span><span> <span>'title_label' => t('Product title') </span></span><span> <span>), </span></span><span> <span>'movies' => array( </span></span><span> <span>'name' => t('Movies'), </span></span><span> <span>'base' => 'movies', </span></span><span> <span>'description' => t('You can define new Movies here'), </span></span><span> <span>'has_title' => TRUE, </span></span><span> <span>'title_label' => t('Movie title') </span></span><span> <span>), </span></span><span> <span>'books' => array( </span></span><span> <span>'name' => t('Books'), </span></span><span> <span>'base' => 'Books', </span></span><span> <span>'description' => t('You can define new Books here'), </span></span><span> <span>'has_title' => TRUE, </span></span><span> <span>'title_label' => t('Books title') </span></span><span> <span>) </span></span><span> <span>); </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Implement hook_form() </span></span><span><span> */ </span></span><span><span>function product_form($node, $form_state) { </span></span><span> <span>return node_content_form($node, $form_state); </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Implement hook_form() </span></span><span><span> */ </span></span><span><span>function movies_form($node, $form_state) { </span></span><span> <span>return node_content_form($node, $form_state); </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Implement hook_form() </span></span><span><span> */ </span></span><span><span>function books_form($node, $form_state) { </span></span><span> <span>return node_content_form($node, $form_state); </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Implement hook_block_info(). </span></span><span><span> */ </span></span><span><span>function entityquery_block_info() { </span></span><span> <span>$blocks = array(); </span></span><span> </span><span> <span>$blocks['entityqueryblock'] = array( </span></span><span> <span>'info' => t('A block to display results from entityquery'), </span></span><span> <span>); </span></span><span> </span><span> <span>return $blocks; </span></span><span><span>} </span></span><span> </span><span><span>/** </span></span><span><span> * Implement hook_block_view(). </span></span><span><span> */ </span></span><span><span>function entityquery_block_view($block_name = '') { </span></span><span> <span>if ($block_name == 'entityqueryblock') { </span></span><span> <span>$content =''; </span></span><span> <span>$block = array( </span></span><span> <span>'subject' => t('A block to display results from entityquery'), </span></span><span> <span>'content' => $content, </span></span><span> <span>); </span></span><span> <span>return $block; </span></span><span> <span>} </span></span><span><span>}</span></span>
Conclusion
Many modules in Drupal will need you to fetch entity content from the database. One can directly use the Drupal database layer, but for that you have to have at least a working knowledge of SQL and it could be more prone to errors. The EntityFieldQuery class is a part of Drupal’s core and you can easily use it without dependency on other modules. Have fun creating your next Drupal module!
Frequently Asked Questions (FAQs) about Drupal’s EntityFieldQuery
What is the main purpose of EntityFieldQuery in Drupal?
EntityFieldQuery is a class in Drupal that allows you to fetch information about entities from the database without writing SQL queries. It provides a simple and efficient way to handle complex queries, making it easier to retrieve, filter, and sort data. It’s particularly useful when you need to fetch data from multiple tables or when you want to apply complex conditions to your queries.
How can I use EntityFieldQuery to fetch data from a specific entity type?
To fetch data from a specific entity type, you can use the ‘entityCondition’ method of the EntityFieldQuery class. This method accepts two parameters: the condition type (which should be ‘entity_type’ for this case) and the entity type you want to fetch data from. Here’s an example:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$result = $query->execute();
Can I use EntityFieldQuery to fetch data from multiple entity types at once?
No, EntityFieldQuery only supports fetching data from one entity type at a time. If you need to fetch data from multiple entity types, you’ll need to run separate queries for each type.
How can I sort the results of an EntityFieldQuery?
You can use the ‘fieldOrderBy’ method to sort the results of an EntityFieldQuery. This method accepts three parameters: the field name, the column to sort by, and the sort direction (either ‘ASC’ for ascending or ‘DESC’ for descending). Here’s an example:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->fieldOrderBy('field_name', 'value', 'DESC');
$result = $query->execute();
Can I use EntityFieldQuery to fetch data from custom fields?
Yes, you can use the ‘fieldCondition’ method to fetch data from custom fields. This method accepts three parameters: the field name, the column to filter by, and the value to filter with. Here’s an example:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->fieldCondition('field_custom', 'value', 'custom value');
$result = $query->execute();
How can I limit the number of results returned by an EntityFieldQuery?
You can use the ‘range’ method to limit the number of results returned by an EntityFieldQuery. This method accepts two parameters: the offset (the number of results to skip) and the limit (the maximum number of results to return). Here’s an example:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->range(0, 10);
$result = $query->execute();
Can I use EntityFieldQuery to fetch data from entities that have a specific status?
Yes, you can use the ‘entityCondition’ method with the ‘status’ condition type to fetch data from entities that have a specific status. Here’s an example:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('status', 1);
$result = $query->execute();
How can I fetch data from entities that have a specific bundle using EntityFieldQuery?
You can use the ‘entityCondition’ method with the ‘bundle’ condition type to fetch data from entities that have a specific bundle. Here’s an example:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'article');
$result = $query->execute();
Can I use EntityFieldQuery to fetch data from entities that were created or updated at a specific time?
Yes, you can use the ‘propertyCondition’ method to fetch data from entities that were created or updated at a specific time. This method accepts three parameters: the property name, the value to filter with, and the operator to use for the comparison. Here’s an example:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->propertyCondition('created', strtotime('-1 day'), '>=');
$result = $query->execute();
How can I fetch data from entities that have a specific value in a multi-value field using EntityFieldQuery?
You can use the ‘fieldCondition’ method with the ‘delta’ column to fetch data from entities that have a specific value in a multi-value field. Here’s an example:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->fieldCondition('field_multi_value', 'value', 'specific value', '=', 1);
$result = $query->execute();
The above is the detailed content of Understanding Drupal's EntityFieldQuery. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
