stopshinal
stopshinal

Reputation: 1921

drupal 7 calculated field returns undefined index

Ok, struggling now after two hours - and I still cant get it.

I'm trying to average all of the fivestar ratings I have for a node using a computed field. But i'm struggling to simply access the other fields using entity!

In the body of the node, this works fine:

$test1 = $node->field_ae_stimclasswrk[und][0]['average'];

but in the computed field area, this doesn't work:

$entity_field[0]['value'] = $entity->field_ae_stimclasswrk[$entity->language]    [und][0]['average'];

Instead, when I save the node, I get this index error:

Notice: Undefined index: und in eval() (line 2 of...

It must be something syntax, but i'm completely out of ideas.

here is the field info:

   [field_ae_stimclasswrk] => Array
        (
            [und] => Array
                (
                    [0] => Array
                            (
                            [user] => 80
                            [average] => 80
                            [count] => 1
                        )

                )

       )

Upvotes: 1

Views: 3682

Answers (2)

Das123
Das123

Reputation: 865

I've had the same issue. It was actually caused by a non-existent index inside $entity->field_ref[$entity->language].

For me, $entity->field_ref[$entity->language] existed for all nodes but when you add an index inside that it causes a problem for any nodes that don't use the field.

$entity->field_ref[$entity->language][0] caused the issue (note the addition of the [0] index).

To solve your problem you could try:

$test1 = (isset($node->field_ae_stimclasswrk[$node->language][0]['average']))? $node->field_ae_stimclasswrk[$node->language][0]['average'] : NULL;

Or a little easier to read:

if (isset($node->field_ae_stimclasswrk[$node->language][0]['average'])){
  $test1 = $node->field_ae_stimclasswrk[$node->language][0]['average'];
} else {
  $test1 = NULL;
}

This way it will bypass any nodes that don't make use of the field.

Upvotes: 1

Clive
Clive

Reputation: 36956

Just a tiny error in your code:

$entity->field_ae_stimclasswrk[$entity->language][und][0]['average'];

If you look at that closely you're actually trying to access the language element of the field twice, once with $entity->language and once with und.

It would probably be best to keep the code contextual so I would remove the [und] item in the code:

$entity->field_ae_stimclasswrk[$entity->language][0]['average'];

Upvotes: 2

Related Questions