1

I'm trying to figure out if a node already exist, I'm using the following code

$query = new EntityFieldQuery;        
$result = $query
                      ->entityCondition('entity_type', 'node')
                      ->propertyCondition('type', 'item')
                      ->propertyCondition('title', $full_name)
                      ->execute();

       if (!empty($result['node'])) {
         // do something
       }

The problem is this, when a result is returned, the structure of the result is this

    Array
    (
        [node] => Array
            (
                [96] => stdClass Object
                    (
                        [nid] => 96
                        [vid] => 96
                        [type] => item
                    )

            )

)

I'm trying to get the nid, but I can't figure out how to access it $

result['node'][0]

does not work. How do I get the nid in this situation

1
  • Key is not 0, it's 96, you can't guess, then i recommend xandeadx answer. paul-m response is not false also but the first is better for me and for 1 item result. – khaled_webdev Nov 24 '17 at 13:36
2

Jimajamma is correct: The question you ask is a PHP one. You want array_keys($result['node']), since the EntityFieldQuery always returns entities as an array of types, with each type having an array of entities keyed by their unique ID.

However... This query won't tell you if the node already exists or not. It will only tell you that there's a node with that title. That might be adequate for your project, however.

1
  • That was the easiest way I could think of, the titles are generated from the taxonomies, I'm trying to make the a node reference if one exists with the same taxonomies, and also create it first if it does not exist, doing the query by title seems to be the simplest approach – user379468 Jan 11 '12 at 19:00
6
$nid = current($result['node'])->nid;
0

This appears to be a php question, as basically it looks like you are wanting the first item in your array regardless of its key. In this case that appears to be your nid, or 96. Regardless, you can accomplish this with either of the array_slice(0,1) or array_values() functions.

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.