1

In Drupal 7, we had hook_entity_property_info() and hook_entity_property_info_alter() which allowed us to add custom properties. (Not everything is a field.)

I can't find anything related to Drupal 8. The only thing I find is how to add it on a custom entity. How should I add properties to an existing entity/bundle?

1

I suppose you want hook_entity_base_field_info(). By using a computed field based on a class, you can get a behavior similar to properties.

function hook_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'node') {
    $fields = [];
    $fields['mymodule_text'] = BaseFieldDefinition::create('string')
      ->setLabel(t('The text'))
      ->setDescription(t('A text property added by mymodule.'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\EntityComputedText');

    return $fields;
  }
}

I have copied a snippet from Drupal commerce, where a payment gateway reference is appended to a commerce_order entity (commerce_payment module altering an entity from commerce_order module).

/**
 * Implements hook_entity_base_field_info().
 */
function commerce_payment_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'commerce_order') {
    $fields['payment_gateway'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Payment gateway'))
      ->setDescription(t('The payment gateway.'))
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_payment_gateway');

    $fields['payment_method'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Payment method'))
      ->setDescription(t('The payment method.'))
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_payment_method');

    return $fields;
  }
}

By using ->setReadOnly(TRUE); or ->setComputed(TRUE), you can probably hide them from regular forms, making them behave like properties.

-1

You might want to look at D8 - hook_entity_bundle_info_alter

  • The OP is talking of an entity properties, which are different from that. – kiamlaluno Jul 11 '17 at 16:05
  • They don't exist any more, it's just fields now – Clive Jul 11 '17 at 16:12
  • you are right, according to this see #3 it's has not be implemented yet – samer.ali Jul 11 '17 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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