1

I have a text field that I am setting inside an entity bundle.

  protected function doSomethingAwesome(string $value): void {
    $this->set('field_text', $value);
    $this->field_text->format = 'special_format';
    $this->renderField();
  }

PHPStan complained about this: Access to an undefined property Drupal\Core\Field\FieldItemListInterface::$format.

So I tried using webmozarts/assert because it's already included with Drupal to assert the property:

  protected function doSomethingAwesome(string $value): void {
    Assert::propertyExists($this->field_text, 'format');
    $this->set('field_text', $value);
    $this->field_text->format = 'special_format';
    $this->renderField();
  }

This fixes the PHPStan error (after installing phpstan-webmozarts-assert), but the assert fails in production.

I know I could disable this rule, but I already fixed all the errors except this one related to format.

How can I tell PHPStan that drupal text field has a format property?

phpstan.neon

parameters:
    checkGenericClassInNonGenericObjectType: false
    level: 8
    paths:
        - web/modules/custom
        - web/themes/custom
    ignoreErrors:
      - '#no value type specified in iterable type array#'
      - '#Thrown exceptions in a catch block must bundle the previous exception#'
includes:
    - vendor/mglaman/phpstan-drupal/extension.neon
    - vendor/thecodingmachine/phpstan-strict-rules/phpstan-strict-rules.neon
    - vendor/phpstan/phpstan-webmozart-assert/extension.neon
    - vendor/phpstan/phpstan-deprecation-rules/rules.neon

I realize this question might also be a fit for Stack Overflow, but since this is specifically about handling of Drupal fields and PHPStan is now being used with core, I think it is a better fit here.

1 Answer 1

1

Actually, this was caused by having a bad type hint on hook_form_alter().

I had accidentally added FormStateInterface twice like this:

mymodule_form_alter(FormStateInterface &$form, FormStateInterface $form_state, string $form_id)

and it should be:

mymodule_form_alter(array &$form, FormStateInterface $form_state, string $form_id)

1
  • 1
    Just want to note, you can also set the value and format in one go with something like $this->field_text = ['format' => 'special_format','value' => 'text value']; Jun 28, 2022 at 5:36

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.