I get this error, which makes the module pretty unusable for me:

Error: Using $this when not in object context in Drupal\ingredient\Plugin\Field\FieldType\IngredientItem::generateSampleValue() (line 174 of modules/contrib/recipe/modules/ingredient/src/Plugin/Field/FieldType/IngredientItem.php).

Error seems simple enough, this is a static function trying to call this from a trait.

  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();

    // Get the ingredient unit keys.
    $unit_keys = array_keys($this->getConfiguredUnits());
    $random_unit_key = mt_rand(0, count($unit_keys) - 1);

    // Generate an ingredient entity.
    $ingredient = \Drupal::entityTypeManager()->getStorage('ingredient')->create(['name' => $random->name(10, TRUE)]);
    $values = [
      'target_id' => $ingredient->id(),
      'quantity' => mt_rand(1, 5),
      'unit_key' => $unit_keys[$random_unit_key],
      'note' => $random->word(15),
    ];
    return $values;
  }

Seems like getConfiguredUnits doesn't need access to this, so should be made a public static function and references to it replaced with static calls.

trait IngredientUnitTrait {

  /**
   * Returns an array of units from configuration.
   *
   * @param string[] $sets_to_get
   *   An array of set id strings.
   *
   * @return string[]
   *   An array of units.
   */
  protected function getConfiguredUnits(array $sets_to_get = []) {

Patch attached.

Comments

camerongreen created an issue. See original summary.

camerongreen’s picture

StatusFileSize
new4.17 KB
dcam’s picture

StatusFileSize
new14.39 KB

Sorry I didn't check this issue sooner. Just know that it came back to bite me because I encountered the same problem last week when trying to use Layout Builder with a Recipe node. I appreciate the patch and I'll give you credit for it, but I'm actually much more of a fan of using services these days for dependency injection. So I replaced the whole trait.

  • dcam committed 8c8113a on 8.x-2.x
    Issue #3084458 by camerongreen, dcam: IngredientItem using this in...
dcam’s picture

Status: Active » Fixed

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.