0

Supposed I added a custom Boolean field, whose cardinality is 1, to a content type. I create a node of that content type, enter a value for that field (for example, TRUE), and save the node.

When I get the field value with $value = node->get('field_custom')->getValue(); $value contains the following array.

0 => array (1)
  value => string (1) "1"

Is there an way to get the field value that reflects the field type, Boolean in this case?

0 => array (1)
  value => boolean true

I manually cast the value, for example with code similar to the following one.

// Boolean
$value = (boolean) $value;

// Integer
$value = intval($value);

I also tried get('x')->value and using __get().

Drupal knows the field type, which is returned from $field->getFieldDefinition()->getType(). I take there is a way to correctly cast the field value.

2
  • Values are not cast on return by Drupal.
    – Kevin
    Jul 31, 2021 at 17:26
  • You could cast as $value = (boolean) $value;
    – Kevin
    Jul 31, 2021 at 18:06

1 Answer 1

3

Normally type casting doesn't matter: https://softwareengineering.stackexchange.com/questions/24378/type-casting-variables-in-php-what-is-the-practical-reason-for-doing-this.

So retrieving an entity field value doesn't need to be type casted:

$node->field_bool->value

returns a string '0'/'1' or NULL if the field is empty. All three possible values work as expected in PHP. '1' results in logical true and the other two values in logical false. This reflects how it is visible in UI where a checkbox can only have two states. Empty is unchecked, checked is saved as '1' and when unchecked again it is saved as '0'.

However, the Drupal entity system is built on typed data and if you want to write OOP code with type casting, you can:

$node->field_bool->first()->get('value')->getCastedValue()

returns FALSE/TRUE.

Caveat: This doesn't work on field level. You need to get a field item to get the boolean typed data and you have to catch an empty field to avoid get() on NULL.

2
  • Thank you very much for ur answer, I totally agree, especially with the "normally". So for my case this is very helpful and works good for primitive like integer, float boolean and string wont cast a datetime
    – john Smith
    Aug 1, 2021 at 19:30
  • 1
    To cast a date object replace getCastedValue() with DateTimeIso8601::getDateTime().
    – 4uk4
    Aug 2, 2021 at 6:29

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.