1

I have to remove leading and trailing spaces from address postcodes.

The following script does the task:

<?php
require('./app/Mage.php');
Mage::init();


$addresses = Mage::getModel('customer/address')->getCollection();

foreach( $addresses as $row ) {
    $address = Mage::getModel('customer/address')->load( $row->getId()   );

    $address->setData( 'postcode', trim( $address->getPostcode() ) ) //remove spaces
            ->getResource()
            ->saveAttribute( $address, 'postcode' );
}

Is there any better solution? Can/should it be done directly via MySQL database query?

2

Since Customer details are an EAV-based model, you are better off using the code you have entered.

However, if you really really want to edit MySQL directly, you can run this:

UPDATE customer_address_entity_varchar SET value = TRIM(value)
WHERE attribute_id=30;

BUT first you need to check whether the postcode's attribute ID is indeed 30 in customer_eav_attribute. The data model for the item with id 30 should be customer/attribute_data_postcode.

| improve this answer | |
  • Thanks for the information. In this case I will continue using my code. I was able to adapt your MySQL statement a little bit. Just in case someone is interested using a single query: UPDATE customer_address_entity_varchar SET value = TRIM(value) WHERE attribute_id = (SELECT attribute_id FROM customer_eav_attribute WHERE data_model = "customer/attribute_data_postcode"); – pbaldauf Nov 29 '16 at 9:23

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.