2

What I'm trying to do is ->

 $fields = [];
  $fields = $entity->getFieldDefinitions();  
  foreach ($fields as $field) {
    if ($field->field_type == 'type') {
      $test = $field->field_type;
    }
  }

Unfortunately I couldn't find a neat method to select my fields by type, so I thought unless Drupal won't give me one I write my own. But Drupal restrict me on that also with this -> Fatal error: Cannot access protected property

Fatal error: Cannot access protected property Drupal\field\Entity\FieldConfig::$field_type

2 Answers 2

3

You code is OK, only that you are trying to read the protected property field_type. Instead use the method:

$field->getType()

Reference: public function FieldDefinitionInterface::getType()

0
3

Here is a quick rundown how I retrieved this information:

  • Opened up FieldConfig (core/modules/field/src/Entity/FieldConfig.php)
  • Searched for $field_type
  • Nothing useful
  • Went to the base class FieldConfigBase (core/lib/Drupal/Core/Field/FieldConfigBase.php)
  • Search results:

    • First one: protected $field_type; (okay protected, as expected. This is why it doesn't work)
    • Second result public function getType() { return $this->field_type; }

      This seems to be what we want.

    • Let's see which interface defines this method: My IDE tells me: \Drupal\Core\Field\FieldDefinitionInterface::getType

For a little bit nicer code, here is a function which returns all field definitions (note: this are not the fields actually having the values) by field type:

function getFieldDefinitionsByType(FieldableEntityInterface $entity, $field_type) {
  $fields = $entity->getFieldDefinitions();
  $fields_by_type = array_filter($fields, function (FieldDefinitionInterface $field_definition) use ($field_type) {
    return $field_definition->getType() == $field_type;
  });
  return $fields_by_type;
}
0

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.