1

I write a code to create a sql file to add a column to customer eav table. I want to check whether that field exist in customer table or not.

here is my code for creating that field >>

$setup = Mage::getModel('customer/entity_setup', 'core_setup');
$setup->addAttribute('customer', 'nationalcode', array(
    'type' => 'varchar',
    'input' => 'text',
    'label' => 'national code',
    'global' => 1,
    'visible' => 1,
    'required' => 0,
    'default' => '',
    'user_defined' => 1,
    'visible_on_front' => 1,
));

what should I add to this code to check the existence of the "nationalcode" field before creating it?

3
  • 1
    Minor note, won't matter in 99.999% of cases: the second argument for this setup class should be customer_setup.
    – benmarks
    Apr 16, 2014 at 10:11
  • tnx, but why is that? Apr 16, 2014 at 10:28
  • Your "default" connection info is set in app/etc/local.xml under the global/resources/default_setup/connection XPath, a.k.a. the default_setup connection. When EAV resource models are instantiated, they are told which adapters to use (ref customer_write in Mage_Customer_Model_Resource_Customer::__construct()). Internally this gets aliased to the core setup config - which aliased to the default setup config- if not explicitly set; ref Mage_Core_Model_Resource::getConnection().
    – benmarks
    Apr 16, 2014 at 15:27

1 Answer 1

6

You are pretty close to the answer already. Mage_Eav_Model_Entity_Setup::addAttribute() contains a check itself to determine whether the operation is an insert or an update:

public function addAttribute($entityTypeId, $code, array $attr)
{
    $entityTypeId = $this->getEntityTypeId($entityTypeId);
    $data = array_merge(
        array(
            'entity_type_id' => $entityTypeId,
            'attribute_code' => $code
        ),
        $this->_prepareValues($attr)
     );

    $this->_validateAttributeData($data);

    $sortOrder = isset($attr['sort_order']) ? $attr['sort_order'] : null;
    $attributeId = $this->getAttribute($entityTypeId, $code, 'attribute_id');
    if ($attributeId) {
        $this->updateAttribute($entityTypeId, $attributeId, $data, null, $sortOrder);
    } else {
        $this->_insertAttribute($data);
    }
    //snip...
}

As you can see, your installer class instance (Mage_Customer_Model_Entity_Setup) has the necessary method.

//Returns associative array if attribute exists, null if not
$installer->getAttribute('customer','nationalcode');

That said, you can see the importance of namespacing attribute codes. It's always good to check, but aamiri_nationalcode would be a "safer" choice.

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.