Magento уникальный атрибут TaxVat для каждого клиента - PullRequest
0 голосов
/ 22 февраля 2012

.Hi,Я пытаюсь сделать атрибут таксват уникальным для каждого клиента.(особенно для пользователей, которых я создаю из бэкэнда).т.е. без дубликатов.Как и в атрибуте электронной почты, если электронная почта уже используется, пользователь получает уведомление об использовании другой электронной почты.Я попытался из eav_attribute изменить "is_unique" на "1", но ничего не произошло ..Можете ли вы помочь мне, как этого добиться?Спасибо

Ответы [ 4 ]

1 голос
/ 15 апреля 2013

Я изменил то, что написал Карпа, чтобы сделать его лучше

if ($attribute->getIsUnique()) {
            $cid = $this->getEntity()->getData('entity_id'); //get current customer id
            $cli = Mage::getModel('customer/customer')
            ->getCollection()
            ->addAttributeToFilter($attribute->getAttributeCode(), $data[$attribute->getAttributeCode()])
            ->addFieldToFilter('entity_id',   array('neq' => $cid)); //exclude current user from results  //###### not working......
            if (count($cli)>0) {
                $label = $attribute->getStoreLabel();
                $errors = array_merge($errors, array(Mage::helper('customer')->__('"%s" already used!',$label)));
            }
1 голос
/ 06 марта 2012

хорошо, я нашел решение .. Найти файл /app/code/core/Mage/Customer/Model/Form.php (не забудьте переопределить вместо этого ..) в "публичной функции validateData (array $ data)"

добавить код внутри foreach ($ this-> getAttributes () как атрибут $)

foreach ($this->getAttributes() as $attribute) {
...
...
//## code to add
        if ($attribute->getIsUnique()) {
            $cid = $this->getEntity()->getData('entity_id'); //get current customer id
            $cli = Mage::getModel('customer/customer')
            ->getCollection()
            ->addAttributeToFilter($attribute->getAttributeCode(), $data[$attribute->getAttributeCode()]);
            //->addFieldToFilter('customer_id',   array('neq' => $cid)); //exclude current user from results  //###### not working......
            $flag=0;
            foreach ($cli as $customer) {
                 $dataid=$customer->getId();
                 if ($dataid != $cid) //if the value is from another customer_id
                    $flag |= 1;  //we found a dup value
            }

            if ($flag) {
                $label = $attribute->getStoreLabel();
                $errors = array_merge($errors, Mage::helper('customer')->__('"%s" already used!',$label));
            }
        }
//## End of code to add
}
0 голосов
/ 15 января 2018

Вы можете создать событие:

<customer_save_before>
                <observers>
                    <mymodule_customer_save_before>
                        <class>mymodule/observer</class>
                        <method>checkUniqueAttribute</method>
                    </mymodule_customer_save_before>
                </observers>
            </customer_save_before>

А у вашего наблюдателя:

/**
     * Check customer attribute which must be unique
     *
     * @param Varien_Event_Observer $observer
     * @return $this
     * @@see customer_save_before
     */
    public function checkUniqueAttribute(Varien_Event_Observer $observer)
    {
        /** @var Mage_Customer_Model_Customer $customer */
        $customer = $observer->getEvent()->getCustomer();
        foreach ($customer->getAttributes() as $attribute) {
            if ($attribute->getIsUnique()) {
                $collection = Mage::getModel('customer/customer')
                    ->getCollection()
                    ->addAttributeToFilter($attribute->getAttributeCode(), $customer->getData($attribute->getAttributeCode()))
                    ->addFieldToFilter('entity_id',   array('neq' => $customer->getId()));

                if ($collection->getSize()) {
                    Mage::throwException(sprintf(
                        'The value %s for %s is already used',
                        $customer->getData($attribute->getAttributeCode()),
                        $attribute->getStoreLabel()
                    ));
                }
            }
        }

        return $this;
0 голосов
/ 10 марта 2012

Я некоторое время искал это решение. Но я заметил, что файл form.php, на который вы ссылаетесь, является версией 1.5 magento. В версии 1.6 файл отличается ... Куда поместить этот код в версии 1.6? Спасибо.

Я нашел файл. Он находится в /app/code/core/Mage/Eav/Model/form.php. Но я поместил код и не работал здесь ... Я продолжаю пробовать решение.

...