0

I need to add a value to a table after an event. I made a observer to check if a custom boolean attribute of a product in a order is marked as "yes" and, if it is, I need to add the order's id to this table that I created.

I cant find a tutorial about this anywhere :(

DONE -- See edit in the end

my table

CREATE TABLE IF NOT EXISTS `allnations_orders` (
   `id` INT AUTO_INCREMENT,
   `order` int,
   PRIMARY KEY (ID) 
   )"
);

my observer (don't mind the comments in portuguese, they're just for my better understanding)

class Novapc_AllNations_Model_Observer extends Varien_Event_Observer 
/* not sure if should extend this? */

{
    public function checkOrder(Varien_Event_Observer $event)
    {
        // Carrega a order e o model pra interação com o banco
        $order = $event->getEvent()->getOrder();
        $model = Mage::getModel('novapc_allnations/order');
        $product = Mage::getModel('catalog/product');

        // Variavel pra controlar se vai salvar ou não no banco
        $save = 0;

        // Loop pra ler todos os produtos do pedido
        foreach ($order->getAllItems() as $item) {

            // Pega o ID do produto
            $product->load($this->getProduct($item)->getId());

            //  Verifica se o produto esta sincronizado com a All Nations
            if ($product->getData('allnations_sync') == 1) {
                $orderId = $order->getId();
                $save = 1;
            }
        }

        // Se algum dos  produtos for da All Nations, salvar o ID do pedido
        if ($save == 1) {
            $model->setOrder($orderId);
            $model->save();
        }
    }
}

my config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Novapc_Allnations>
            <version>0.1.0</version>
        </Novapc_Allnations>
    </modules>
    <global>
        <events>
            <sales_order_place_after>
                <observers>
                    <novapc_allnations>
                        <class>Novapc_Allnations_Model_Observer</class>
                        <method>checkOrder</method>
                        <type>singleton</type>
                    </novapc_allnations>
                </observers>
            </sales_order_place_after>
        </events>
        <models>
            <novapc_allnations>
                <class>Novapc_Allnations_Model</class>
                <resourceModel>novapc_allnations_resource</resourceModel>
            </novapc_allnations>
            <novapc_allnations_resource>
                <class>Novapc_Allnations_Model_Resource</class>
                <entities>
                    <order>
                        <table>allnations_orders</table>
                    </order>
                </entities>
            </novapc_allnations_resource>
        </models>
        <blocks>
            <novapc_allnations>
                <class>Novapc_Allnations_Block</class>
            </novapc_allnations>
        </blocks>
        <helpers>
            <novapc_allnations>
                <class>Novapc_Allnations_Helper</class>
            </novapc_allnations>
        </helpers>
        <resources>
            <novapc_allnations_setup>
                <setup>
                    <module>Novapc_Allnations</module>
                </setup>
                <connection>
                <use>core_setup</use>
                </connection>
            </novapc_allnations_setup>
            <novapc_allnations_setup>
                <connection>
                    <use>core_write</use>
                </connection>
            </novapc_allnations_setup>
            <novapc_allnations_setup>
                <connection>
                    <use>core_read</use>
                </connection>
            </novapc_allnations_setup>
        </resources>
    </global>
    <adminhtml>
        <acl>
            <resources>
                <all>
                    <title>Allow Everything</title>
                </all>
                <admin>
                    <children>
                        <system>
                            <children>
                                <config>
                                    <children>
                                        <inchoo>
                                            <title>Inchoo - All</title>
                                        </inchoo>
                                    </children>
                                </config>
                            </children>
                        </system>
                    </children>
                </admin>
            </resources>
        </acl>
    </adminhtml>
</config>

Edit -- Changed my Observer php to this and it worked:

class Novapc_AllNations_Model_Observer extends Varien_Event_Observer
{
    public function checkOrder(Varien_Event_Observer $event)
    {
        // Carrega a order e o model pra interação com o banco
        $order = $event->getEvent()->getOrder();

        // Variavel pra controlar se vai salvar ou não no banco
        $save = 0;

        $orderItemIds = array();
        foreach ($order->getAllItems() as $item) {
            $orderItemIds[] = $item->getProductId();
        }

        $productCollection = Mage::getModel('catalog/product')
            ->getCollection()
            ->addFieldToFilter('entity_id', array('in' => $orderItemIds))
            ->addFieldToFilter('allnations_sync', array('eq' => 1))
            ->addAttributeToSelect('*');

        // Loop pra ler todos os produtos do pedido
        if ($productCollection->getSize() >= 1) {
            $save = 1;
        }

    // Se algum dos  produtos for da All Nations, salvar o ID do pedido
        if ($save == 1) {
            $model = Mage::getModel('novapc_allnations/order');
            $orderId = $order->getId();
            $model->setOrder($orderId);
            $model->save();
        }
    }
}
  • Can you please share the code that you already have? – Tim Cieplowski Aug 10 '17 at 19:44
  • In which table you need to enter value? Is it magento default or your custom one? – Abhishek Panchal Aug 10 '17 at 19:50
  • Added my observer and config.xml and made my question clearer. I need to add to my custom table – Stordon Aug 10 '17 at 19:56
  • can you share your table structure – Murtuza Zabuawala Aug 14 '17 at 13:54
  • id INT AUTO_INCREMENT and order int – Stordon Aug 14 '17 at 14:08
1

@Stordon, do not load models in a loop ... this is n°1 performance killer ...

foreach ($order->getAllItems() as $item) {
    $product = Mage::getModel('catalog/product')->load($item->getProductId());
    ...
}

Better add the attributes you need before (see last question). For saving data to anther table, Abhishek Panchals 2nd way is the right one. Add your table to config - if it is a custom table, add a model for it and use $model->save() instead of a raw SQL query.


Edit: if you use a custom table you have to add it to config.xml, change

        <novapc_allnations_resource>
            <class>novapc_AllNations_Model_Resource</class>
        </novapc_allnations_resource>

to

        <novapc_allnations_resource>
            <class>novapc_AllNations_Model_Resource</class>
            <entities>
                <yourmodel>
                    <table>your_table_name</table>
                </yourmodel>
            </entities>
        </novapc_allnations_resource>

In your Model/Yourmodel.php

public function _construct()
{
    $this->_init('novapc_allnations/yourmodel');
}

In Model/Resource/Yourmodel.php

public function _construct()
{
    $this->_init('novapc_allnations/yourmodel', 'your_autoincrement_column');
}

In Model/Resource/Yourmodel/Collection.php

public function _construct()
{
    parent::_construct();
    $this->_init('novapc_allnations/yourmodel');
}

Now you should be able to get/set data from/to your custom table.

$model = Mage::getModel('novapc_allnations/yourmodel');
$model->setSomeValue(value);
$model->save();

Note: your class names should start with uppercase char (<class>novapc_AllNations_...</class>)

  • I see!! Thanks for the advice. But it isn't working... I think I'm just too dumb to work with Magento – Stordon Aug 11 '17 at 13:01
  • @Stordon updated, maybe it helps. – sv3n Aug 11 '17 at 13:20
  • Didn't work too, I think I'm doing something wrong in my config.xml or in my Observer – Stordon Aug 11 '17 at 16:41
  • @Stordon please post Obersver.php ... – sv3n Aug 13 '17 at 16:02
  • updated both my Observer.php and my config.xml... Now also when I click Place order in checkout page it doesn't load, it just keeps in that same page :( I'm using Models, and just like the ones you posted – Stordon Aug 14 '17 at 14:12
0

Try below code. Hope it helps :)

First way without model

$orderId = $order->getId();
$resource     = Mage::getSingleton('core/resource');
$writeAdapter   = $resource->getConnection('core_write');
$table        = $resource->getTableName('your_table_name');
$query        = "INSERT INTO {$table} (`order_id`) VALUES ($orderId);";
$writeAdapter->query($query);

Second way using model

$orderId = $order->getId();
$model = Mage::getModel('your_model_name'); //for eg. Mage::getModel('catalog/product');

try {
    $model->setOrderId($orderId);
    $model->save();
} catch (Exception $e) {
    echo $e->getMessage();
}
  • both ways didn't work :( – Stordon Aug 11 '17 at 13:02

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.