Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically getting nodes by title in Drupal 7

I have a module that programmatically adds a whole lot of nodes to my Drupal 7 site. To prevent duplicates I want to check whether the title of my newly created node doesn't already exist in the system. There will never be a case where two nodes have the same name. I've tried using node_load(), but that doesn't seem to allow me to load nodes based on a title.

I'm stumped on how to proceed, so I was wondering if somebody here could help me.

To summarize: How do I check whether a node with a certain title already exists?

Thanks.

like image 304
Eruonen Avatar asked Dec 03 '11 18:12

Eruonen


1 Answers

Node are entities, so you can use the EntityFieldQuery class to query for them. This way, you don't have to bother how the information is stored in the database. And, shall you need to add additional filters based on field values, code evolution will be easy.

$result = (new EntityFieldQuery())
  ->entityCondition('entity_type', 'node')
  ->propertyCondition('title', $title)
  ->execute();
$title_is_unique = empty($result['node']);
like image 141
Pierre Buyle Avatar answered Nov 14 '22 04:11

Pierre Buyle