class EntityAffiliateCampaign extends Entity {
  public function __construct(array $values = array(), $entityType = NULL) {
    // Add default values, if they are not set.
    $values += array(
      'name' => '',
      'affiliate_uid' => 0,
      'is_default' => FALSE,
    );
    parent::__construct($values, 'affiliate_campaign');
  }
}

That's my entity class. It initializes some important values so that I don't get an empty object from entity_create().
However, this gives me a problem with entity_load, because the entity controller does this:

$result->setFetchMode(PDO::FETCH_CLASS, $this->entityInfo['entity class'], array(array(), $this->entityType));

What this line of code does is prefill an object from the database values, THEN calls it's constructor.
And the default entity class constructor does this:

// Set initial values.
    foreach ($values as $key => $value) {
      $this->$key = $value;
    }

Thus overwriting the already set values, and giving me an empty object.

Attaching a sensible patch.
This could also be a support request if you think I'm doing the whole defaults thing wrong :P

Comments

damien tournoud’s picture

Status: Needs review » Reviewed & tested by the community

This patch allows using the $values array to let the constructor set default values. It bends the original intend of $values, but it makes sense to me.

fago’s picture

Status: Reviewed & tested by the community » Needs work

I don't think we can do that, as this would break passing in values for existing implementations that use entity object properties with defined defaults. Any cause you aren't just defining a (public) object property with a default value? As PHP has already a solution for property defaults, I don't think we have to reinvent the wheel.

bojanz’s picture

As I said:

This could also be a support request if you think I'm doing the whole defaults thing wrong :P

The current approach made sense to me because we did the same in various controllers...
Should we "won't fix" this then, and document the preferred way somewhere?

fago’s picture

Title: The entity class should not (re)initialize values that are already filled in » Document how defaults for entity properties should be provided
Component: Code - misc » Documentation

Yep, let's document that. Maybe in the docblock of the Entity class?

bojanz’s picture

Status: Needs work » Needs review
StatusFileSize
new482 bytes

Maybe like this? Not sure how clear it is.
Definitely needed though, the same confusion popped up at http://drupal.org/project/model.

fago’s picture

StatusFileSize
new553 bytes

Thanks, I tried to further improve it. That should help I think?

bojanz’s picture

Status: Needs review » Reviewed & tested by the community

Yes, that's better.

fago’s picture

Status: Reviewed & tested by the community » Fixed

That was quick ;)
Thanks, committed.

Status: Fixed » Closed (fixed)

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