Magento – How to create and insert to a custom table in magento

magento-1.9

The question is clear from the title itself , what i need is creating a customer_token table and insert data to it upon registration ,

here is

what i have tried

in my_project/app/core/code/Mage/Customer/sql/mysql4-install-0.7.0

-- DROP TABLE IF EXISTS `{$this->getTable('customer_token')}`;
CREATE TABLE `{$this->getTable('customer_token')}` (
  `id` int(11) NOT NULL auto_increment,
  `customer_id` smallint(8) unsigned  default '0',
  `token` varchar(255)   default '0',
  `created_at` datetime NOT NULL default '0000-00-00 00:00:00',
  `expire_at` datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

In my_project/app/core/code/Mage/Customer/etc/config.xml

<entities>
     <customer_token>
        <table>customer_token</table>
    </customer_token>
</entities> 

In my_project/app/core/code/Mage/Customer/Resource/token.php

class Mage_Customer_Model_Resource_Token extends Mage_Eav_Model_Entity_Abstract
{


}

And in my_project/wrappers/customer_register.php

  $token = getToken(20);
        $data = array('customer_id' => 1, 'token' => $token);
        $model = Mage::getModel('customer/token')->setData($data);
        try {
            $insertId = $model->save()->getId();
            echo "Data successfully inserted. Insert ID: " . $insertId;
        } catch (Exception $e) {
            echo $e->getMessage();
        }

But it throws me a Resource is not set error . Any idea ??

UPDATE

I followed the blog specified in the answer and created a module as

customer_token . am sharing the main files below ,

 `my_project\app\code\community\Customer\Token\etc\config.xml`

1.0.0

Customer_Token_Model
customertoken_resource

Customer_Token_Model_Resource

customer_token

Customer_Token

core_setup

core_read

core_write

Customer_Token_Block

<!-- start of routers 
-->
<frontend>
    <routers>
        <customertoken>
            <use>standard</use>
            <args>
                <module>Customer_Token</module>
                <frontName>customertoken</frontName>
            </args>
        </customertoken>
    </routers>
    <layout>
        <updates>
            <customertoken>
                <file>customertoken.xml</file>
            </customertoken>
        </updates>
    </layout>
</frontend>

IN my_project\app\code\community\Customer\Token\Model\Customertoken.php

   class Cusotmer_Token_Model_Customertoken extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        $this->_init('customertoken/customertoken');
    }

}

And in my_project\app\etc\modules\Customer_Token.xml

    <config>
     <modules>
        <Customer_Token>
            <active>true</active>
            <codePool>community</codePool>
        </Customer_Token>
    </modules>
   </config>

And in my_project\app\code\community\Customer\Token\Resource\Collection.php

class Cusotmer_Token_Model_Resource_Customertoken_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract {

    protected function _constuct() {
        $this->_init('customertoken/customertoken');
    }

}

And in my_project\app\code\community\Customer\Token\Resource\Customertoken.php

class Customer_Token_Model_Resource_Customertoken extends Mage_Core_Model_Resource_Db_Abstract
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    public function _construct()
    {
        $this->_init('customertoken/customertoken', 'id');
    }
}

And in my_project\app\code\community\Customer\Token\sql\customertoken_setup\install-1.6.0.0.php

$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */
$installer->startSetup();

$installer->run("
-- DROP TABLE IF EXISTS `{$this->getTable('customer_token')}`;
CREATE TABLE `{$this->getTable('customer_token')}` (
  `id` int(11) NOT NULL auto_increment,
  `customer_id` smallint(8) unsigned  default '0',
  `token` varchar(255)   default '0',
  `created_at` datetime NOT NULL default '0000-00-00 00:00:00',
  `expire_at` datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    ");
$installer->endSetup();

And am calling it like this ,

$data = array('customer_id' => $customerId, 'token' => $token);
    $model = Mage::getModel('customer_token/custmertoken')->addData($data);
    try {
        $insertId = $model->save()->getId();
        echo "Data successfully inserted. Insert ID: " . $insertId;
    } catch (Exception $e) {
        echo $e->getMessage();
    }

I appreciate your help , thanks .

Best Answer

There are lot of issue in your module.

Don't create any custom table on Core_Module

It is too bad idea to create a model at Core Module(Mage_Customer) and it break magento standard.

I suggest you need to define model at a new custom module.

Please the blog how create Model of table.

Model and resource model class was not write properly

If you are using custom Module and using flat table format for that Model then

Model class inherit from Mage_Core_Model_Abstract.

Resource Model class inherit from Mage_Core_Model_Resource_Db_Abstract.

Collection Model class inherit from Mage_Core_Model_Resource_Db_Collection_Abstract.

Insert data;

As you have set multiple fields ,so you need to use addData() function.

Also you can $id value after model save data. Basically give the table primary key.

If you define custom module then it config.xml look like:

<?xml version="1.0" ?>
<config>
    <modules>
        <Amit_Custommodule>
            <version>1.0.0</version>
        </Amit_Custommodule>
    </modules>
    <global>
        <models>
    <!-- Model is define at here -->
            <custommodule> <!-- Model Prefix -->
                <class>Amit_Custommodule_Model</class>
                <resourceModel>custommodule_resource</resourceModel>
            </custommodule>
    <!--  Resource Model is define at here -->

            <custommodule_resource>
                <class>Amit_Custommodule_Model_Resource</class>
                <entities>
                    <token> <!-- define an new  entities for module -->
                        <table>customer_token</table> <!-- define table -->
                    </token>
                </entities>
            </custommodule_resource>
        </models>
        <resources>
            <custommodule_setup>
                <setup>
                    <module>Amit_Custommodule</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </custommodule_setup>
            <custommodule_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </custommodule_read>
            <custommodule_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </custommodule_write>
        </resources>
    </global>
</config> 

Model class is like : Model file Token.php path is app/code/community/Amit/Custommodule/Model

<?php
class Amit_Custommodule_Model_Token extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        $this->_init('custommodule/token');
    }

}

ResourceModel:

Resource class Token.php

app/code/community/Amit/Custommodule/Model/Resource/

<?php
class Amit_Custommodule_Model_Resource_Token extends Mage_Core_Model_Resource_Db_Abstract
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    public function _construct()
    {
        $this->_init('custommodule/token', 'id');
    }
}

Data save Like :

$token = getToken(20);
$data = array('customer_id' => 1, 'token' => $token);
$model = Mage::getModel('custommodule/token')->addData($data);
try {
$model->save(); //save data 
    $insertId = $model->getId();
    echo "Data successfully inserted. Insert ID: " . $insertId;
} catch (Exception $e) {
    echo $e->getMessage();
}
Related Topic