3

I want to retrieve a date value from a date field attached to a node with entity_metadata_wrapper.

So far:

$node_wrapper->field_tournament_date->value();

Provides an array. Not many other methods work. So, I have to do:

$date = $node_wrapper->field_tournament_date->value();
$start_date = format_date($date['value'], 'short');

Is there a cleaner way of getting the value of a date field without breaking it up like that?

4 Answers 4

5

In these situations with meta_data_wrapper you could put the array-value before the value function, like this:

$date = $node_wrapper->field_tournament_date->value->value();
2

If your server's running PHP 5.4 you could use:

$start_date = format_date($node_wrapper->field_tournament_date->value()['value'], 'short');

since function array dereferencing has been added.

Other than that I don't think there's a way of reducing your code to be honest. If you're manipulating date fields a lot you might consider creating a small helper function, something like

function MYMODULE_format_date_field($value, $column = 'value', $format = 'short') {
  return format_date($value[$column], $format);
}
$start_date = MYMODULE_format_date_field($node_wrapper->field_tournament_date->value());

or similar. It's not the best but it might save a bit of time.

1
  • Yeah, dereferencing is a no-go. Not 5.4. I wish. That would be ultra convenient. I just figured there was some native method of retrieving it from a date field, without loading up a date wrapper. No manipulating values, just going for quick custom display renderings with no fuss.
    – Kevin
    Commented Sep 7, 2012 at 0:01
0

I use the following approach:

foreach ($node_wrapper->field_tournament_date->getIterator() as $date_wrapper) {
  // dpm($date_wrapper->getPropertyInfo() // to see what properties you have
  $start_date = $date_wrapper->value->value();
  $end_date = $date_wrapper->value2->value();
  $duration = $date_wrapper->duration->value();
}
0

I used the following:

$entity->field_date->get( 0 )->value->value( );

The call to get is needed because date fields are lists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.