Add VAT rate programatically

Public

If you've added VAT module to existing commerce store you'll have to set correct vat rates to all products. This snippet will help you do that.

Get raw version
php
  1. // Configure VAT field, ex. commerce_no_vat
  2. $vat_field = 'commerce_no_vat';
  3. // Configure VAT rate.
  4. $vat_rate = 'no_standard';
  5.  
  6. // Search for products without vat rate.
  7. $query = db_select('commerce_product', 'cp');
  8. $query->leftJoin('field_data_' . $vat_field, 'vat', 'vat.entity_id = cp.product_id && vat.entity_type = :type', array(':type' => 'commerce_product'));
  9. $query->condition('vat.' . $vat_field . '_value', NULL);
  10. $query->addfield('cp', 'product_id', 'product_id');
  11. $results = $query->execute()->fetchCol();
  12.  
  13. foreach($results as $product_id) {
  14. $product = commerce_product_load($product_id);
  15. $wrapper = entity_metadata_wrapper('commerce_product', $product);
  16. if ($wrapper->__isset($vat_field)) {
  17. $wrapper->commerce_no_vat->set($vat_rate);
  18. $wrapper->save();
  19. }
  20. }