I am trying to write some code to programmatically update a customer billing profile.

I do what i have done many times for many other types of entities:

  $order = entity_load_single('commerce_order', $oid);
  $cprofile = commerce_customer_profile_load($order->commerce_customer_billing['und'][0]['profile_id']);
  $cprofile->field_bekr_ftad['und'][0]['value'] = 'Ja';
  $result = entity_save('commerce_customer_profile', $cprofile);

Seems pretty trivial but field value is never being updated.

I banged my head on the wall for hours over this and then noticed that entity_save result was 1 (i.e. created NEW) instead of 2 (UPDATED) as it should be. Then looking in customer profile table i could see duplicate profiles were being created every time. Looking through issue queue i see a lot of posts somewhat related.

Does anyone know of a proper solution for this or should i simply write directly to the DB to get around whatever odd reason there is for this non-standard behavior?

Comments

liquidcms created an issue. See original summary.

liquidcms’s picture

I looked at the _presave entity function for customer profiles and seems there is no way to properly edit a profile; so i got around this by simply writing directly to the field tables.

rszrama’s picture

Category: Bug report » Support request
Status: Active » Closed (works as designed)

This issue is covered in the docs and elsewhere in the issue queue and is, as you've discovered, related to maintaining the integrity of historical order data. You can also look at the order module's hook_commerce_customer_profile_presave() implementation. If you really want to get around it, you can imitate what the order module does in commerce_order_field_attach_form(). I'm happy to expound on that further, but per the issue submission guidelines, we prefer support to happen at https://drupal.stackexchange.com where it can help more people.

bduell’s picture

This seemed to do the trick for me:

$profile = commerce_customer_profile_load(1);
$wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile);
$wrapper->field_referral_source = 'MySpace';
$profile->entity_context = array(
  'entity_type' => 'commerce_order',
  'entity_id' => 1,
);
commerce_customer_profile_save($profile);

As per http://ryanszrama.com/blog/04-12-2013/bypassing-drupal-commerce-customer...