1

I'm using the module Commerce Stock Sources to manage different stock locations for my products.

When saving the Commerce stock sources form, on form submit, I want to update a field value on the Commerce product entity. The field is an Entity reference field.

The problem is that I can't get the field updated. No notice or error returning.

    //first I'm getting the values to be set; will have a simple array of IDs
    if (!empty($form_state['values']['plugins']['plugin_settings'])){
                $selected_sources = array_values(array_filter($form_state['values']['plugins']['plugin_settings']));
        }
    //next I'm loading the product entity; I have checked, the product is loading OK
    //and then the wrapper and the operations
    $product_entity = entity_load_single('commerce_product', $form_state['complete form']['#product']->product_id);
    $wrapper_product = entity_metadata_wrapper('commerce_product', $product_entity);
    if (!empty($selected_sources)) {
        $wrapper_product->field_product_location_store = $selected_sources;
        $wrapper_product->save();
    }

The field is not updated. I've checked to see if I can read values from product using entity_metadata_wrapper() and it works. When I try to update any field, it doesn't work.

I tried updating with field_attach_update(), but it doesn't work either.

        for($i=0; $i<count($selected_sources); $i++){
          $product_entity->field_product_location_store[LANGUAGE_NONE][$i]['target_id'] = $selected_sources[$i];
        }
        field_attach_update('commerce_product', $product_entity);
        entity_get_controller('commerce_product')->resetCache(array($product_entity->product_id)); 

Any thoughts?

0

1 Answer 1

0

It's seems that by using the product entity directly from $form_state['complete form']['#product']; the entity_metadata_wrapper() works as expected and it saves the values.

if (!empty($form_state['values']['plugins']['plugin_settings'])){
    $selected_sources = array_values(array_filter($form_state['values']['plugins']['plugin_settings']));
}
    //get directly the product, without entity_load_single() 
    $product_entity = $form_state['complete form']['#product']; 
    $wrapper_product = entity_metadata_wrapper('commerce_product', $product_entity);
    if (!empty($selected_sources)) {
        $wrapper_product->field_product_location_store = $selected_sources;
        $wrapper_product->save();
    }

Although the object loaded by entity_load_single() is identical with the object obtained by $product_entity = $form_state['complete form']['#product']; the entity_metadata_wrapper() works only for the second case, which seems more logical and is faster.

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.