Posted by: james | September 24, 2009

Mage Search

Create Form_Search.xml in modules directory.

app/etc/modules/Form_Search
<?xml version=”1.0″ ?>
<config>
<modules>
<form_search>
<active>true</active>
<codePool>local</codePool>
</form_search>
</modules>
</config>

Now go to local and in that form and in that search and in that etc and create config.xml

app/code/local/form/search/etc/config.xml
<?xml version=”1.0″?>
<config>
<modules>
<form_search>

<version>0.1.0</version>        </form_search>
</modules>
<admin>
<routers>
<search>
<use>admin</use>
<args>
<module>form_search</module>                <frontName>search</frontName>

</args>
</search>
</routers>
</admin>
<global>
<blocks>
<search><class>form_search_Block</class>
</search>
<catalog>
<rewrite>
<product_view>form_search_Block_Product_View</product_view>
</rewrite>
</catalog>

</blocks>
<models>
<search>
<class>form_search_Model</class>
</search> </models>
<helpers>
<search><class>form_search_Helper</class></search>
</helpers>
</global> <adminhtml>
<acl>
<resources>
<admin>

<children>
<system>

<children>
<config>

<children>

<search translate=”title” module=”search”>                                        <title>search Section</title>                                    <sort_order>60</sort_order>

</search>
</children>

</config>
</children>
</system>
</children></admin>
</resources>
</acl>
</adminhtml>
</config>

now create system.xml in etc folder

local/Form/search/etc/system.xml

<?xml version=”1.0″?>
<config>
<sections>
<search translate=”label” module=”search”>
<class>separator-top</class>
<label>search</label>
<tab>catalog</tab>

<frontend_type>text</frontend_type>
<sort_order>45</sort_order>            <show_in_default>1</show_in_default>            <show_in_website>1</show_in_website>            <show_in_store>1</show_in_store>
<groups>
<frontend translate=”label”>
<label>Search Engine optimization</label>
<frontend_type>text</frontend_type>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<meta_title translate=”label”>
<label>Meta Title</label>
<frontend_type>text</frontend_type>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</meta_title>
<meta_title_check translate=”label”>
<label>Meta Title Enable</label>
<frontend_type>select</frontend_type>
<source_model>search/system_config_source_yesno</source_model>
<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</meta_title_check>
<meta_desc translate=”label”>
<label>Meta Description</label>
<frontend_type>text</frontend_type>
<sort_order>3</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</meta_desc>
<meta_desc_check translate=”label”>
<label>Meta Description Enable</label>
<frontend_type>select</frontend_type>
<source_model>search/system_config_source_yesno</source_model>
<sort_order>4</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</meta_desc_check>
<meta_keyword translate=”label”>
<label>Meta Keyword</label>
<frontend_type>text</frontend_type>
<sort_order>5</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</meta_keyword>
<meta_keyword_check translate=”label”>
<label>Meta Keyword Enable</label>
<frontend_type>select</frontend_type>
<source_model>search/system_config_source_yesno</source_model>
<sort_order>6</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</meta_keyword_check>
</fields>
</frontend>
</groups>
</search>
</sections>
</config>

now create data.php in helper directory..

local/form/search/helper/data.php
<?php
class form_search_Helper_Data extends Mage_Core_Helper_Abstract
{

}
?>

now create view.php in block and in product directory..

local/form/search/block/product/view.php
<?php

class  Form_search_Block_Product_View extends Mage_Catalog_Block_Product_View
{
protected function _prepareLayout()
{
parent::_prepareLayout();
if ($headBlock = $this->getLayout()->getBlock(‘head’)) {
if(Mage::getStoreConfig(‘search/frontend/meta_title_check’) == 1)
{
$title = Mage::getStoreConfig(‘search/frontend/meta_title’);
$pattern = ‘/\{([^\{\}]*)\}/’;
preg_match_all($pattern, $title, $matches);
$start = “”;
foreach($matches[1] as $match)
{
$type = Mage::registry(‘product’)->getResource()->getAttribute($match)->getFrontendInput();
if($type == “select” || $type == “multiselect”)
{
$value = Mage::registry(‘product’)->getAttributeText($match);
}
else
{
$value = Mage::registry(‘product’)->getData($match);
}
$replace = “{“.$match.”}”;
$title = str_replace($replace,$value,$title);
}
$headBlock->setTitle($title);
}

if(Mage::getStoreConfig(‘search/frontend/meta_desc_check’) == 1)
{
$title2 = Mage::getStoreConfig(‘search/frontend/meta_desc’);
$pattern = ‘/\{([^\{\}]*)\}/’;
preg_match_all($pattern, $title2, $matches);
$start = “”;
foreach($matches[1] as $match)
{
$type = Mage::registry(‘product’)->getResource()->getAttribute($match)->getFrontendInput();
if($type == “select” || $type == “multiselect”)
{
$value = Mage::registry(‘product’)->getAttributeText($match);
}
else
{
$value = Mage::registry(‘product’)->getData($match);
}
$replace = “{“.$match.”}”;
$title2 = str_replace($replace,$value,$title2);
}
$headBlock->setDescription($title2);
}

if(Mage::getStoreConfig(‘search/frontend/meta_keyword_check’) == 1)
{
$title1 = Mage::getStoreConfig(‘search/frontend/meta_keyword’);
$pattern = ‘/\{([^\{\}]*)\}/’;
preg_match_all($pattern, $title1, $matches);
$start = “”;
foreach($matches[1] as $match)
{
$type = Mage::registry(‘product’)->getResource()->getAttribute($match)->getFrontendInput();
if($type == “select” || $type == “multiselect”)
{
$value = Mage::registry(‘product’)->getAttributeText($match);
}
else
{
$value = Mage::registry(‘product’)->getData($match);
}
$replace = “{“.$match.”}”;
$title1 = str_replace($replace,$value,$title1);
}
$headBlock->setKeywords($title1);
}
}
}
}

now to create yesno.php in model in source, path is as under..

local/form/search/Model/system/config/source/yesno.php
<?php

class  Form_search_Model_System_Config_Source_Yesno extends Mage_Core_Model_Config_Data
{

public function toOptionArray()
{
return array(
array(‘value’=>1, ‘label’=>Mage::helper(‘adminhtml’)->__(‘Yes’)),
array(‘value’=>0, ‘label’=>Mage::helper(‘adminhtml’)->__(‘No’)),
);
}

}

Posted by: james | September 19, 2009

product_spec

First of all go to

app/etc/modules/form/productSpec.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<form_ProductSpec>
<active>true</active>
<codePool>local</codePool>
</form_ProductSpec>
</modules>
</config>

now go to Block folder and create element.php and write in that this code.

app/code/local/Form/ProductSpec/Block/element.php
<?php
// use here extend class as you have added attribute i have added attribute file so i use..
class form_ProductSpec_Block_Product_Element extends Varien_Data_Form_Element_File
{
public function getElementHtml()
{
$html = parent::getElementHtml();

$value = $this->getValue();

if($value == ‘checked’)
{
$val = ”;
}
else
{
$val = $value;
}

$collection = Mage::getModel(‘catalog/product’)->getCollection();
$collection->addAttributeToSelect(‘product_spec’);

foreach($collection as $product)
{
$res = $product->getId();
$data = Mage::getModel(‘catalog/product’)->load($res);

if($value)
{
if($data[‘product_spec’])
{
$htmlId =  $this->getHtmlId();
$html .= “<br>”;
$html .= ‘<input name=”product[product_spec]” id=”product[product_spec]” value=”checked”‘;
$html .= ‘class=”checkbox” type=”checkbox”/>’;

$html .= ‘<label for=”product[product_spec]”>’;
$html .= ‘Delete’;
$html .= ‘</label>’;

$html .= ‘&nbsp;&nbsp;&nbsp;’;

$html .= ‘<span id=”file”>’;
$html .= ‘<b>’. $val . ‘</b>’;
$html .= ‘</span>’;
}
}
else
{

}
}
return $html;
}
}

now to make configuration go to config.xml in etc folder and write this code.

app/code/local/Form/ProductSpec/etc/config.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<form_ProductSpec>
<version>0.1.0</version>
</form_ProductSpec>
</modules>
<global>
<models>
<productspec>
<class>form_ProductSpec_Model</class>
</productspec>
</models>
<resources>
<productspec_setup>
<setup>
<module>form_ProductSpec</module>
<class>Mage_Eav_Model_Entity_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</productspec_setup>
<productspec_write>
<connection>
<use>core_write</use>
</connection>
</productspec_write>
<productspec_read>
<connection>
<use>core_read</use>
</connection>
</productspec_read>
</resources>
<blocks>
<productspec>
<class>form_ProductSpec_Block</class>
</productspec>
</blocks>

<helpers>
<productspec>
<class>form_ProductSpec_Helper</class>
</productspec>
</helpers>
</global>

<frontend>
<routers>
<productspec>
<use>standard</use>
<args>
<module>form_ProductSpec</module>
<frontName>productspec</frontName>
</args>
</productspec>
</routers>
</frontend>
</config>

here we have create one custom attribute so for that we have create model

local/Form/ProductSpec/Model/Attribute/Backend.php
<?php
class form_ProductSpec_Model_Attribute_Backend extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
public function beforeSave($object)
{
if(isset($_POST[‘product’][‘product_spec’]))
{
$object->delete();
}
else
{
$attrCode = $this->getAttribute()->getAttributeCode();

$s = $_FILES[‘product’][‘tmp_name’];
$n = $_FILES[‘product’][‘name’];

$name = $n[‘product_spec’];
$src = $s[‘product_spec’];

$dst = Mage::getBaseDir(‘media’). DS .’product_spec’;
$dst_new = Mage::getBaseDir(‘media’). DS .’product_spec’. DS .$name;

if(!file_exists($dst))
{
mkdir($dst,0777);
}
else
{
if(!file_exists($dst_new))
{
copy($src,$dst_new);
$object->setData($attrCode,$name);
}
else
{
$randvalue = rand(1,10);
$file_new_name = $dst. DS .$randvalue.’_’.$name;
copy($src,$file_new_name);
//rename($dst_new,$file_new_name);
$object->setData($attrCode,$randvalue.’_’.$name);
}
}
}

//$v = $object->getProductSpec(); // to get file name

//         // here to get any attribute value you have to just use camel case letter and if you have underscore then also after
//         //under_score the name will be in upper case.
parent::beforeSave($object);
}
}

local/Form/ProductSpec/sql/productspec_setup/mysql4-install-0.1.0.php
<?php
$installer = $this;

$installer->startSetup();

$installer->addAttribute(‘catalog_product’, ‘product_spec’, array(
‘type’                    => ‘varchar’,
‘label’                   => ‘Upload File’,
‘visible’                 => true,
‘required’                => false,
‘input’                   => ‘file’,
‘class’                   => ”,
‘visible_on_front’        => true,
‘backend’                    => ‘productspec/attribute_backend’,
‘input_renderer’          => ‘productspec/product_element’,
‘user_defined’            => true,
));

$installer->endSetup();

Posted by: james | September 19, 2009

magento bookmarks..

http://activecodeline.com/retrieving-product-information-in-magento/

http://docs.jquery.com/Main_Page

http://www.webaim.org/techniques/forms/controls.php

http://stackoverflow.com/questions/1005394/magento-show-custom-attributes-in-grouped-product-table

http://stackoverflow.com/questions/996914/magento-api-uploaded-products-not-appearing-in-frontend-unless-they-are-re-save

http://stackoverflow.com/questions/224065/is-there-a-entity-attribute-value-eav-framework-out-there-for-php-mysql

http://stackoverflow.com/questions/1332742/magento-retrieve-products-with-a-specific-attribute-value

http://t.wits.sg/tag/magento/

Posted by: james | September 18, 2009

notes…

write about all the tabs of product…
and also search about all the data..
to see all attribute go to eav/Model/Entity/Setup.php
to use any data in block form controller do this..
require_once “Mage/Adminhtml/controllers/Catalog/ProductController.php”;
class Form_data_ProductController extends Mage_Adminhtml_Catalog_ProductController
{
public function newAction()
{
$this->_initProduct();
}}

to access any magento file in simple php file, menas outside of nagento..
require_once(‘path/Mage.php’);
Mage::app;

to add any custom element renderer in form in admin panel, menas if you have added one attribute for file

uploading and now you want to add one checkbox then it requrire custom renderer so for that you have to give

one new line in your script and it will be frontend_input_renderer so for that entity name is input_rendere

(to see all attribute name go to eav/Model/Entity/Setup.php) and in database also check it and give the same

version in config.xml as your script name and to see sny module setup go to core_resource..

good link for collection

..http://stackoverflow.com/questions/1332742/magento-retrieve-products-with-a-specific-attribute-value

to get product data on block page or to get any collection data on block page do this….
$collection = Mage::getModel(‘catalog/product’)->getCollection();
foreach($collection as $product)
{
$res = $product->getId();
$data = Mage::getModel(‘catalog/product’)->load($res);
}
now specify attribute which you want to get and also you can apply all the method for attribute on this

collection like….
$collection->addAttributeToSelect(‘attribute_code’) or addFieldToFilter(‘attribute_code’)…

in magento collection return means you get whole collection means query like select * from.. but if you want

to mkae collection for some condition then use addFilterToAttribute, in that you can pass condition as well

as any join.. and to get any particular attribute call addAttributeToSelect(‘attribute_code’)..

in admin panel to get value of any element for example you want to get value of any textblox or file then

just use getValue() function.  and if you have not element then call like this

$this->getElement->getValue();

Posted by: james | September 16, 2009

Check it..

for adding attribute means like form elemnt at admin panel…
additional image for category at admin panel..

go to app/etc/modules/Form_CategoryImage.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<Form_CategoryImage>
<active>true</active>
<codePool>local</codePool>
</Form_CategoryImage>
</modules>
</config>

go to app/code/local/Form/CategoryImage/etc/config.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<Form_CategoryImage>
<version>0.1.0</version>
</Form_CategoryImage>
</modules>
<global>
<models>
<categoryimage>
<class>Form_CategoryImage_Model</class>
</categoryimage>
</models>
<resources>
<categoryimage_setup>
<setup>
<module>Form_CategoryImage</module>
<class>Mage_Catalog_Model_Resource_Eav_Mysql4_Setup</class> // here use class which file contain

add attribute method means use

setup.php but its on different path for

different module.
</setup>
<connection>
<use>core_setup</use>
</connection>
</categoryimage_setup>
<categoryimage_write>
<connection>
<use>core_write</use>
</connection>
</categoryimage_write>
<categoryimage_read>
<connection>
<use>core_read</use>
</connection>
</categoryimage_read>
</resources>
<blocks>
<categoryimage>
<class>Form_CategoryImage_Block</class>
</categoryimage>
</blocks>

<helpers>
<categoryimage>
<class>Form_CategoryImage_Helper</class>
</categoryimage>
</helpers>
</global>

<frontend>
<routers>
<categoryimage>
<use>standard</use>
<args>
<module>Form_CategoryImage</module>
<frontName>categoryimage</frontName>
</args>
</categoryimage>
</routers>
</frontend>
</config>

go to app/code/local/Form/CategoryImage/sql/categoryimage_setup/mysql4-install-0.1.0.php

<?php
$installer = $this;

$installer->startSetup();

$installer->addAttribute(‘catalog_category’, ‘featured_image’, array(
‘type’              => ‘varchar’,
‘label’             => ‘Featured Image’,
‘visible’           => true,
‘required’          => false,
‘input’             => ‘image’,
‘global’            => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
‘class’             => ‘input-file’,
‘visible_on_front’  => true,
‘backend’           => ‘catalog/category_attribute_backend_image’,
));

$installer->endSetup();

now for adding custome attribute with custome backend model in i porting product, while importing product you can

also import any file like .txt,.doc,.pdf or any other…

go to app/etc/modules/Form_ProductSpec.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<Form_ProductSpec>
<active>true</active>
<codePool>local</codePool>
</Form_ProductSpec>
</modules>
</config>

now go to app/code/local/Form/ProductSpec/etc/config.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<Form_ProductSpec>
<version>0.1.0</version>
</Form_ProductSpec>
</modules>
<global>
<models>
<productspec>
<class>Form_ProductSpec_Model</class>
</productspec>
</models>
<resources>
<productspec_setup>
<setup>
<module>Form_ProductSpec</module>
<class>Mage_Eav_Model_Entity_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</productspec_setup>
<productspec_write>
<connection>
<use>core_write</use>
</connection>
</productspec_write>
<productspec_read>
<connection>
<use>core_read</use>
</connection>
</productspec_read>
</resources>
<blocks>
<productspec>
<class>Form_ProductSpec_Block</class>
</productspec>
</blocks>

<helpers>
<productspec>
<class>Form_ProductSpec_Helper</class>
</productspec>
</helpers>
</global>

<frontend>
<routers>
<productspec>
<use>standard</use>
<args>
<module>Form_ProductSpec</module>
<frontName>productspec</frontName>
</args>
</productspec>
</routers>
</frontend>
</config>

go to app/code/Form?ProductSpec/Model/Attribute/Backend.php

<?php
class Form_ProductSpec_Model_Attribute_Backend extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
public function beforeSave($object)
{
$attrCode = $this->getAttribute()->getAttributeCode();
//$value = $object->getData($attrCode);

$s = $_FILES[‘product’][‘tmp_name’];
$n = $_FILES[‘product’][‘name’];

$name = $n[‘product_spec’];
$src = $s[‘product_spec’];

$dst = Mage::getBaseDir(‘media’). DS .’product_spec’;
$dst_new = Mage::getBaseDir(‘media’). DS .’product_spec’. DS .$name;

if(!file_exists($dst))
{
mkdir($dst,0777);
}
else
{
if(!file_exists($dst_new))
{
copy($src,$dst_new);
}
else
{
$randvalue = rand(1,10);
$file_new_name = $dst. DS .$randvalue.’_’.$name;
rename($dst_new,$file_new_name);
}
}

$object->setData($attrCode,$name);

/*$uploader = new Varien_File_Uploader($this->getAttribute()->getName());
$uploader->setAllowedExtensions(array(‘txt’,’doc’,’pdf’));
$uploader->setAllowRenameFiles(true);
$uploader->save($dst_new);*/

/*$object->setData($this->getAttribute()->getName(), $dst_new);
$this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName());*/

parent::beforeSave($object);
//$value = $object->getData($this->getAttribute()->getName());
}
}

app/code/loacl/Form/ProductSpec/sql/productspec_setup/mysql4-install-0.1.0.php

<?php
$installer = $this;

$installer->startSetup();

$installer->addAttribute(‘catalog_product’, ‘product_spec’, array(
‘type’              => ‘varchar’,
‘label’             => ‘Upload File’,
‘visible’           => true,
‘required’          => false,
‘input’             => ‘file’,
‘class’             => ”,
‘visible_on_front’  => true,
‘backend’              => ‘productspec/attribute_backend’,
));

$installer->endSetup();

Posted by: james | September 14, 2009

new

yif you use entity..then you can get collection of prodcuts, customers and orders and all that.. and you can apply

function on that.. to see all the function go to app/code/core/Mage/Eav/Model/Entity/collection/Abstract.php

app/etc/modules/form_filteroutstock.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<form_FilterOutStock>
<active>true</active>
<codePool>local</codePool>
</form_FilterOutStock>
</modules>
</config>
app/code/local/form/filteroutstock/etc/config.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<form_FilterOutStock>
<version>0.1.0</version>
</form_FilterOutStock>
</modules>

<global>
<models>
<filteroutstock>
<class>form_FilterOutStock_Model</class>
</filteroutstock>
</models>
<resources>
<filteroutstock_setup>
<setup>
<module>form_FilterOutStock</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</filteroutstock_setup>
<filteroutstock_write>
<connection>
<use>core_write</use>
</connection>
</filteroutstock_write>
<filteroutstock_read>
<connection>
<use>core_read</use>
</connection>
</filteroutstock_read>
</resources>
<blocks>
<filteroutstock>
<class>form_FilterOutStock_Block</class>
</filteroutstock>
</blocks>

<helpers>
<filteroutstock>
<class>form_FilterOutStock_Helper</class>
</filteroutstock>
</helpers>
</global>

<frontend>
<events>
<catalog_product_collection_load_before>
<observers>
<filteroutstock>
<type>singleton</type>
<class>filteroutstock/observer</class>
<method>processBeforeLoadEvent</method>
</filteroutstock>
</observers>
</catalog_product_collection_load_before>
</events>
<routers>
<filteroutstock>
<use>standard</use>
<args>
<module>form_FilterOutStock</module>
<frontName>filteroutstock</frontName>
</args>
</filteroutstock>
</routers>
</frontend>
</config>

app/code/local/form/fileroutstock/model/Observer.php
<?php
class form_FilterOutStock_Model_Observer extends Mage_Core_Model_Abstract
{
public function processBeforeLoadEvent(Varien_Event_Observer $observer)
{
$collection = $observer->getEvent()->getCollection();
$collection->joinField(
‘stock_status’,
‘cataloginventory/stock_status’,
‘stock_status’,
‘product_id=entity_id’, array(
‘stock_status’ =>

Mage_CatalogInventory_Model_Stock_Status::STATUS_IN_STOCK,
‘website_id’ => Mage::app()->getWebsite()->getWebsiteId(),
)
);
}
}

Posted by: james | September 14, 2009

search module..

app/etc/modules/serach_new.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<Search_New>
<active>true</active>
<codePool>local</codePool>
</Search_New>
</modules>
</config>

app/design/frontend/default/new/layout/new.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<layout version=”0.1.0″>
<catalog_category_layered>
<reference name=”catalog.leftnav”>
<block type=”catalog/layer_view” name=”catalog.leftnav” after=”currency” template=”new/first.phtml”/>
<action

method=”setToolbarBlockName”><name>product_list_toolbar</name><block>catalog/product_list_toolbar</block><template>new/first.phtml</template>

</action>
</reference>
</catalog_category_layered>
</layout>

<!–<?xml version=”1.0″ encoding=”UTF-8″?>
<layout version=”0.1.0″>
<catalog_category_layered>
<reference name=”product_list_toolbar”>
<block type=”catalog/product_list_toolbar” name=”product_list_toolbar” template=”new/first.phtml”>
</block>
<action

method=”setToolbarBlockName”><name>product_list_toolbar</name><block>catalog/product_list_toolbar</block><template>new/first.phtml</template>

</action>
</reference>
</catalog_category_layered>
</layout>

–>

app/design/frontend/default/new/template/new/first.phtml
<?php
echo “sdf”; exit;

now go to admin panel and selsect english from drop down and and sellect design form configuration and write new in package name and run..

nowe go to app/code/local/search/new/etc/config.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<Search_New>
<version>1.0</version>
</Search_New>
</modules>
<global>
<models>
<new>
<class>Search_New_Model</class>
</new>
</models>
<blocks>
<new>
<class>Search_New_Block</class>
</new>
<catalog>
<rewrite>
<layer_view>Search_New_Block_First</layer_view>
</rewrite>
</catalog>
</blocks>
<helpers>
<new>
<class>Search_New_Helper</class>
</new>
</helpers>
</global>
<frontend>
<routers>
<new>
<use>standard</use>
<args>
<module>Search_New</module>
<frontName>new</frontName>
</args>
</new>
</routers>
<layout>
<updates>
<new>
<file>new.xml</file>
</new>
</updates>
</layout>
</frontend>
</config>

app/code/local/search/new/block/first.php
<?php
class Search_New_Block_First extends Mage_Catalog_Block_Layer_View
{

}

Posted by: james | September 12, 2009

query..

DATABASE NAME:  testing
TABLE NAMES:  area , category , subcat
VIEW NAME: currentc

FOR STORED PROCEDURE DATABASE NAME: proc
FOR TRIGGER DATABASE NAME: trig

INSERT QUERY:
insert into test1 values (6,’sd’,’cd’,11);

insert into category values (1,52,12,10)

SELECT QUERY:
select * from category

select count(*) as number from table_name where field = ‘value’;
// it will return number of rows..

select sum(value) from subcat;

SELECT DISTINCT QUERY:
select distinct name from subcat

WHERE CLAUSE:
select * from subcat where cost1 > 80
select * from subcat where name = ‘c2’

AND CLAUSE:
select * from subcat where name = ‘c2’ and cost1 = 85

OR CLAUSE:
select * from subcat where name = ‘c2’ or cost1 = 85

ORDER BY:
select * from subcat order by cost1
select * from subcat order by cost1 desc

UPDATE QUERY:
update subcat set cost1 = 52, name = ‘c4’ where id2 = 3

DELETE QUERY:
delete from subcat where cost1 = 52

delete from category; delete all the data

LIMIT QUERY:
select * from area limit 2     ; to display records in limited range   ; always use wildcard with limit query

LIKE QUERY:     like query is an alias for where
select  *from area where lname like ‘ v% ‘;   select all with starting with v
select  *from area where lname like ‘ %v’      select all with ending v

select * from area where fname like ‘_a’  // start with any character followed by a  // _ use for any character

select * from area where fname like ‘[as]%’  // for character set

IN CLAUSE:
select * from area where fname in (‘s’,’sa’);

BETWEEN QUERY:
select  * from area where lname between ‘v’ and ‘vo’   // for character
select * from area where age between 21 and 26   // for number

ALIASES:
select a.lname, c.cost from area as a, category as c where a.id = 2    // use for shortname of tables using as

UNION:
select name from category union select name from subcat // u can use with different coiumn name also
select name from category union all select name from subcat

SELECT INTO:
select * into table ssubcat from subcat; // to create another same copy of table
select * into table ssubcat in ‘newdb.mdb’ from subcat // to create another same copy of table in new db

ALTER QUERY
alter table `testing`.`category` add column’  ‘name’  VARCHAR(45)  after ‘quantity’;

alter table area drop index gender

ALTER TABLE `testing`.`subcat` ADD COLUMN `name` VARCHAR(50)  AFTER `value`;
nsert into subcat values (4,95,55,’cat4′)
rename table test1 to area;

CRREATE QUERY:
create database testing

create table ‘testing’ , ‘category’ (
‘id1’ int auto_increment,
‘cost’  varchar(45),
‘value’ varchar(45),
‘quantity’ varchar(45),
primary key(‘id1’)
)
unique key can be more then 1
primary key can’t  be more then 1
foriegn key use to link b/w to tables // in  one table pk will be foreign key for another table

INDEX:
create index sn on subcat (name)  // u can’t see index just useful for fast searching

DROP QUERY:
drop table area; // u can also use drop for dropping database and also for index

VIEW:  // its one kind of virtual table use to store data
to create:
create view Currentc as select cost1,name from subcat where id2 = 2

to display:
select * from Currentc

to drop:
drop view Currentc

DATE : format is (yy or yyyy- mm – day)
select datediff(‘2008-11-20′,’2008-11-15’) as diffate   // O/P = 5 //

JOIN QUERY: // to use it one column must common b/w to tables and use on keyword instead of where.  // first table will be left and second will be right
select category.cost, subcat.cost1 from category join subcat on category.name=subcat.name;  // join will work same as inner join // most time use with on keyword

select category.cost, subcat.cost1 from category left join subcat on category.name=subcat.name;

select category.cost, subcat.cost1 from category right join subcat on category.name=subcat.name;

AGGREGATE FUNCTIONS:
select avg(value) from subcat // to calculate average
select first(name)  from subcat  // return first
select last(name)  from subcat
select max(cost1)  from subcat
select min(cost1)  from subcat
select sum(cost1)  from subcat

GROUP BY QUERY:
select cost1,sum(cost1) from subcat group by name;

TRIGGERS:
//to use define or then to use it anywhere use @  keyword // @ this keyword is used for accessing variable
create table account (acct_num INT, amount DECIMAL(10,2)); // for creating table

create trigger  ins_sum before insert on account for each row set @sum = @sum + NEW.amount; // mysql doesnt support multiple triggers

after creting trigger for checking it do……………
set @sum = 0;
insert into account values(138,16.98),(148,2937.50),(98,-200.00);
select @sum as ‘Total amount inserted’;

//for dropping:
drop trigger test.ins_sum;

//for getting list of triggers
Show Triggers From databse_name

STORED PROCEDURE:

//to declaer,display,set  any variable…
DECLARE var1 varchar(15);
select count(*) into var1 from test1;
select @var1;

//to declaer,display,set  any variable.
SET @a = 10;
SELECT @a;

//how to pass table name and column name as argument see here
CREATE PROCEDURE varstm(IN test1 CHAR(64), IN age CHAR(64)
BEGIN

SET @s = CONCAT(‘SELECT AVG(‘ , age , ‘) FROM ‘ , test1);
#select @s;
PREPARE stmt FROM @s;
EXECUTE stmt;

//we use cursor for sql query statment with stored procedure and also we can save that value to particular variable

DELIMITER $$

DROP PROCEDURE IF EXISTS `proc`.`curs` $$
CREATE PROCEDURE `proc`.`curs` (in id int , out var varchar(10))  //here id is work as input variable and var work as output variable
BEGIN

DECLARE cur1 CURSOR FOR SELECT stu_name from stu_table where stu_id =id;

OPEN cur1;

Fetch cur1 into var;

close cur1;

//to call cursor and display value we use

call curdemo(2, name);
select  @name;

//to create it

create procedure p1

Posted by: james | September 12, 2009

note..

first of all that etc/configx.xml file…
create table.. whenever you create any table or upgrade it, always make that script and put that in folder…of sql..
create config.xml…. from this you can define controller , admin menu and child menu for admin panel…
create helper
create controller which u have defined in xml file..
now to render that block create block and in that folders.. now to mke grid create folder in block and in that create

grid.php to display all..
now go to model and create provider.php and session.php…
now create new folder Mysql4 and in that create Provider.php
now create new folder provider inmysql4 and in that create  collection.php for getting grid values..
before slash first is maodule name and after that its a file name, but if its with _(underscore) then in that it will

be another folder and in that its file name will be with .php

$category = Mage::getModel(‘catalog/category’) here catalog is module name.. and category.php file is there in that..
Mage::getSingleton(‘catalog/session’)->setLastVisitedCategoryId($category->getId()); here getSingleton is used to

create object of session and you can set any id in that..

$category = Mage::getHelper(‘catalog/category_flat.php’); here catalog is module and category is folder in helper and

flat.php in that folder..

thus you can create also block,model etc..
ex.             this->loadLayout()
->_addContent($this->getLayout()->createBlock(‘provider/contact’))
->renderLayout(); // its used to create block..here provider is module and contact.php

file is in block folder..

generally to set template there is one function in magento setTemplate(‘modulename/filename.phtml’), now in desing in

template there will be one folder whose name is same as modulenmae and in that this file wiil be located. but if you

want to do same as at admin panel then you can;t use this for that you have to make everything in block folder and in

that make one .php file and in that write all.. pls see whole extension..

to use any value in session do this..
in controller..
$form = Mage::getModel(‘warranty/warranty’)
->setData($this->getRequest()->getPost());
Mage::getSingleton(‘warranty/session’)->setData(‘last_saved_warranty’,$form); warranty-module name and session is

file in model folder… like sales… and then redirect ti to block,, not necessary.. u can redirect as you wish..
$this->_redirect(‘warranty/thanks/’); // warranty module and thanks is .php filie in block folder so in

block/thanks.php

and now to access that value use like this..
return Mage::getSingleton(‘warranty/session’)->getData(‘last_saved_warranty’,true); // it will return last saved

warranty id which is stored in session…

if in controller there is somoething like createBlock() and then path is there, so it will come directly form block

folder,, but if there is $this->loadLayout() then that block will come from xml.. so go to xml of that module and and

from that find data about block…

in xml file if you find that <reference name=”content”> then it will come for middle part and if you find  <reference

name=”left”> then it will take left part.. thus for right part..
use mysql4 in giving name of attribute..
in customer all come from xml and in that whole form come from enetinty relationship.. means just call one function

addAttribute and with that provide all the details and also it will call one script setup.php so it will get whole

form..

always put dhyan to giving name…

never overwrite controller… no need to overwrite helper… block can be overwrite..and model can aslo be

overwrite.. and use observer for overwrite model action.. see catalogindex whole module..if you have any event and

after that event or before that event you want to call some action or something from model then use observer and all

that..pls refer catalogindex module,…

Posted by: james | September 12, 2009

new one..

local/form/company/block/name.php
<?php
class Form_Company_Block_Name extends Mage_Adminhtml_Block_Widget_Grid
{

public function __construct()
{
parent::__construct();
$this->setId(‘customerGrid’);
$this->setUseAjax(true);
$this->setDefaultSort(‘entity_id’);
}

protected function _prepareCollection()
{
$collection = Mage::getResourceModel(‘customer/customer_collection’)
->addNameToSelect()
->addAttributeToSelect(’email’)
->addAttributeToSelect(‘customer_code’)
->addAttributeToSelect(‘created_at’)
->addAttributeToSelect(‘group_id’)
->joinAttribute(‘billing_postcode’, ‘customer_address/postcode’, ‘default_billing’, null, ‘left’)
->joinAttribute(‘billing_city’, ‘customer_address/city’, ‘default_billing’, null, ‘left’)
->joinAttribute(‘billing_telephone’, ‘customer_address/telephone’, ‘default_billing’, null, ‘left’)
->joinAttribute(‘company’, ‘customer_address/company’,’default_billing’,null,’left’)
->joinAttribute(‘billing_region’, ‘customer_address/region’, ‘default_billing’, null, ‘left’)
->joinAttribute(‘billing_country_id’, ‘customer_address/country_id’, ‘default_billing’, null, ‘left’);

$this->setCollection($collection);

return parent::_prepareCollection();
}

protected function _prepareColumns()
{
$this->addColumn(‘entity_id’, array(
‘header’    => Mage::helper(‘customer’)->__(‘ID’),
‘width’     => ’50px’,
‘index’     => ‘entity_id’,
‘type’  => ‘number’,
));
/*$this->addColumn(‘firstname’, array(
‘header’    => Mage::helper(‘customer’)->__(‘First Name’),
‘index’     => ‘firstname’
));
$this->addColumn(‘lastname’, array(
‘header’    => Mage::helper(‘customer’)->__(‘Last Name’),
‘index’     => ‘lastname’
));*/
$this->addColumn(‘name’, array(
‘header’    => Mage::helper(‘customer’)->__(‘Name’),
‘index’     => ‘name’
));
$this->addColumn(’email’, array(
‘header’    => Mage::helper(‘customer’)->__(‘Email’),
‘width’     => ‘150’,
‘index’     => ’email’
));

$this->addColumn(‘Company’, array(
‘header’    => Mage::helper(‘customer’)->__(‘Company Name’),
‘width’     => ‘150’,
‘index’     => ‘company’
));

$this->addColumn(‘customer_code’, array(
‘header’    => Mage::helper(‘customer’)->__(‘Customer Code’),
‘width’     => ‘150’,
‘index’     => ‘customer_code’
));

$groups = Mage::getResourceModel(‘customer/group_collection’)
->addFieldToFilter(‘customer_group_id’, array(‘gt’=> 0))
->load()
->toOptionHash();

$this->addColumn(‘group’, array(
‘header’    =>  Mage::helper(‘customer’)->__(‘Group’),
‘width’     =>  ‘100’,
‘index’     =>  ‘group_id’,
‘type’      =>  ‘options’,
‘options’   =>  $groups,
));

$this->addColumn(‘Telephone’, array(
‘header’    => Mage::helper(‘customer’)->__(‘Telephone’),
‘width’     => ‘100’,
‘index’     => ‘billing_telephone’
));

$this->addColumn(‘billing_postcode’, array(
‘header’    => Mage::helper(‘customer’)->__(‘ZIP’),
‘width’     => ’90’,
‘index’     => ‘billing_postcode’,
));

$this->addColumn(‘billing_country_id’, array(
‘header’    => Mage::helper(‘customer’)->__(‘Country’),
‘width’     => ‘100’,
‘type’      => ‘country’,
‘index’     => ‘billing_country_id’,
));

$this->addColumn(‘billing_region’, array(
‘header’    => Mage::helper(‘customer’)->__(‘State/Province’),
‘width’     => ‘100’,
‘index’     => ‘billing_region’,
));

$this->addColumn(‘customer_since’, array(
‘header’    => Mage::helper(‘customer’)->__(‘Customer Since’),
‘type’      => ‘datetime’,
‘align’     => ‘center’,
‘index’     => ‘created_at’,
‘gmtoffset’ => true
));

if (!Mage::app()->isSingleStoreMode()) {
$this->addColumn(‘website_id’, array(
‘header’    => Mage::helper(‘customer’)->__(‘Website’),
‘align’     => ‘center’,
‘width’     => ’80px’,
‘type’      => ‘options’,
‘options’   => Mage::getSingleton(‘adminhtml/system_store’)->getWebsiteOptionHash(true),
‘index’     => ‘website_id’,
));
}

$this->addColumn(‘action’,
array(
‘header’    =>  Mage::helper(‘customer’)->__(‘Action’),
‘width’     => ‘100’,
‘type’      => ‘action’,
‘getter’    => ‘getId’,
‘actions’   => array(
array(
‘caption’   => Mage::helper(‘customer’)->__(‘Edit’),
‘url’       => array(‘base’=> ‘*/*/edit’),
‘field’     => ‘id’
)
),
‘filter’    => false,
‘sortable’  => false,
‘index’     => ‘stores’,
‘is_system’ => true,
));

$this->addExportType(‘*/*/exportCsv’, Mage::helper(‘customer’)->__(‘CSV’));
$this->addExportType(‘*/*/exportXml’, Mage::helper(‘customer’)->__(‘XML’));
return parent::_prepareColumns();
}

protected function _prepareMassaction()
{
$this->setMassactionIdField(‘entity_id’);
$this->getMassactionBlock()->setFormFieldName(‘customer’);

$this->getMassactionBlock()->addItem(‘delete’, array(
‘label’    => Mage::helper(‘customer’)->__(‘Delete’),
‘url’      => $this->getUrl(‘*/*/massDelete’),
‘confirm’  => Mage::helper(‘customer’)->__(‘Are you sure?’)
));

$this->getMassactionBlock()->addItem(‘newsletter_subscribe’, array(
‘label’    => Mage::helper(‘customer’)->__(‘Subscribe to newsletter’),
‘url’      => $this->getUrl(‘*/*/massSubscribe’)
));

$this->getMassactionBlock()->addItem(‘newsletter_unsubscribe’, array(
‘label’    => Mage::helper(‘customer’)->__(‘Unsubscribe from newsletter’),
‘url’      => $this->getUrl(‘*/*/massUnsubscribe’)
));

$groups = $this->helper(‘customer’)->getGroups()->toOptionArray();

array_unshift($groups, array(‘label’=> ”, ‘value’=> ”));
$this->getMassactionBlock()->addItem(‘assign_group’, array(
‘label’        => Mage::helper(‘customer’)->__(‘Assign a customer group’),
‘url’          => $this->getUrl(‘*/*/massAssignGroup’),
‘additional’   => array(
‘visibility’    => array(
‘name’     => ‘group’,
‘type’     => ‘select’,
‘class’    => ‘required-entry’,
‘label’    => Mage::helper(‘customer’)->__(‘Group’),
‘values’   => $groups
)
)
));

return $this;
}

public function getGridUrl()
{
return $this->getUrl(‘*/*/grid’, array(‘_current’=> true));
}

public function getRowUrl($row)
{
return $this->getUrl(‘*/*/edit’, array(‘id’=>$row->getId()));
}
}

local/formcompany/etc/config.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<Form_Company>
<version>0.1.0</version>
</Form_Company>
</modules>
<admin>
<routers>
<company>
<use>admin</use>
<args>
<module>Form_Company</module>
<frontName>company</frontName>
</args>
</company>
</routers>
</admin>
<global>
<blocks>
<adminhtml>
<rewrite>
<customer_grid>Form_Company_Block_Name</customer_grid>
</rewrite>
</adminhtml>
<company>
<class>Form_Company_Block</class>
</company>
</blocks>
<models>
<company>
<class>Form_Company_Model</class>
<resourceModel>company_mysql4</resourceModel>
</company>
</models>

<resources>
<company_setup>
<setup>
<module>Form_Company</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</company_setup>
<company_write>
<connection>
<use>core_write</use>
</connection>
</company_write>
<company_read>
<connection>
<use>core_read</use>
</connection>
</company_read>
</resources>
<blocks>
<company>
<class>Form_company_Block</class>
</company>
</blocks>

<helpers>
<company>
<class>Form_Company_Helper</class>
</company>
</helpers>
</global>

<frontend>
<routers>
<company>
<use>standard</use>
<args>
<module>Form_Company</module>
<frontName>company</frontName>
</args>
</company>
</routers>
</frontend>
</config>

local/form/Customercode/block/Name.php
<?php
class Form_Customercode_Block_Name extends Mage_Adminhtml_Block_Widget_Form
{
public function __construct()
{
parent::__construct();
}

public function initForm()
{
$form = new Varien_Data_Form();
$form->setHtmlIdPrefix(‘_account’);
$form->setFieldNameSuffix(‘account’);

$customer = Mage::registry(‘current_customer’);

$fieldset = $form->addFieldset(‘base_fieldset’,
array(‘legend’=>Mage::helper(‘customer’)->__(‘Account Information’))
);

$this->_setFieldset($customer->getAttributes(), $fieldset);

if ($customer->getId()) {
$form->getElement(‘website_id’)->setDisabled(‘disabled’);
$form->getElement(‘created_in’)->setDisabled(‘disabled’);
} else {
$fieldset->removeField(‘created_in’);
}

$form->getElement(’email’)->addClass(‘validate-email’);
//$form->getElement(‘customer_code’)->addClass(‘validate-email’);

/*$new_field = $fieldset->addField(‘customer_code’,’text’,
array(
‘title’ => Mage::helper(‘customer’)->__(‘Enter Customer Code’),
‘label’ => Mage::helper(‘customer’)->__(‘Enter Customer Code’),
‘legend’ => Mage::helper(‘customer’)->__(‘Enter Customer Code’),
‘name’ => ‘customer_code’,
)
);*/

if ($customer->getId()) {
if (!$customer->isReadonly()) {
// add password management fieldset
$newFieldset = $form->addFieldset(
‘password_fieldset’,
array(‘legend’=>Mage::helper(‘customer’)->__(‘Password Management’))
);
// New customer password
$field = $newFieldset->addField(‘new_password’, ‘text’,
array(
‘label’ => Mage::helper(‘customer’)->__(‘New Password’),
‘name’  => ‘new_password’,
‘class’ => ‘validate-new-password’
)
);
$field->setRenderer($this->getLayout()->createBlock(‘adminhtml/customer_edit_renderer_newpass’));

// prepare customer confirmation control (only for existing customers)
$confirmationKey = $customer->getConfirmation();
if ($confirmationKey || $customer->isConfirmationRequired()) {
$confirmationAttribute = $customer->getAttribute(‘confirmation’);
if (!$confirmationKey) {
$confirmationKey = $customer->getRandomConfirmationKey();
}
$element = $fieldset->addField(‘confirmation’, ‘select’, array(
‘name’  => ‘confirmation’,
‘label’ => Mage::helper(‘customer’)->__($confirmationAttribute->getFrontendLabel()),
))->setEntityAttribute($confirmationAttribute)
->setValues(array(” => ‘Confirmed’, $confirmationKey => ‘Not confirmed’));

// prepare send welcome email checkbox, if customer is not confirmed
// no need to add it, if website id is empty
if ($customer->getConfirmation() && $customer->getWebsiteId()) {
$fieldset->addField(‘sendemail’, ‘checkbox’, array(
‘name’  => ‘sendemail’,
‘label’ => Mage::helper(‘customer’)->__(‘Send Welcome Email after Confirmation’)
));
}
}
}
}
else {
$newFieldset = $form->addFieldset(
‘password_fieldset’,
array(‘legend’=>Mage::helper(‘customer’)->__(‘Password Management’))
);
$field = $newFieldset->addField(‘password’, ‘text’,
array(
‘label’ => Mage::helper(‘customer’)->__(‘Password’),
‘class’ => ‘input-text required-entry validate-password’,
‘name’  => ‘password’,
‘required’ => true
)
);
$field->setRenderer($this->getLayout()->createBlock(‘adminhtml/customer_edit_renderer_newpass’));

// prepare send welcome email checkbox
$fieldset->addField(‘sendemail’, ‘checkbox’, array(
‘label’ => Mage::helper(‘customer’)->__(‘Send welcome email’),
‘name’  => ‘sendemail’,
‘id’    => ‘sendemail’,
));
}

// make sendemail disabled, if website_id has empty value
if ($sendemail = $form->getElement(‘sendemail’)) {
$prefix = $form->getHtmlIdPrefix();
$sendemail->setAfterElementHtml(
‘<script type=”text/javascript”>’
. ”
$(‘{$prefix}website_id’).disableSendemail = function() {
$(‘{$prefix}sendemail’).disabled = (” == this.value || ‘0’ == this.value);
}.bind($(‘{$prefix}website_id’));
Event.observe(‘{$prefix}website_id’, ‘click’, $(‘{$prefix}website_id’).disableSendemail);
$(‘{$prefix}website_id’).disableSendemail();

. ‘</script>’
);
}

if ($customer->isReadonly()) {
foreach ($customer->getAttributes() as $attribute) {
$element = $form->getElement($attribute->getAttributeCode());
if ($element) {
$element->setReadonly(true, true);
}
}
}

$form->setValues($customer->getData());
$this->setForm($form);
return $this;
}

}
local/form/Customercode/etc/config.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<modules>
<Form_Customercode>
<version>0.1.0</version>
</Form_Customercode>
</modules>
<admin>
<routers>
<customercode>
<use>admin</use>
<args>
<module>Form_Customercode</module>
<frontName>customercode</frontName>
</args>
</customercode>
</routers>
</admin>
<global>
<blocks>
<adminhtml>
<rewrite>
<customer_edit_tab_account>Form_Customercode_Block_Name</customer_edit_tab_account>>
</rewrite>
</adminhtml>
<customercode>
<class>Form_Customercode_Block</class>
</customercode>
</blocks>
<models>
<customer>
<rewrite>
<entity_customer>Form_Customercode_Model_Mysql4_Code</entity_customer>
</rewrite>
</customer>
<customercode>
<class>Form_Customercode_Model</class>
<resourceModel>customercode_entity</resourceModel>
</customercode>
<customercode_entity>
<class>Form_Customercode_Model_Entity</class>
</customercode_entity>
</models>

<resources>
<customercode_setup>
<setup>
<module>Form_Customercode</module>
<class>Mage_Customer_Model_Entity_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</customercode_setup>
<customercode_write>
<connection>
<use>core_write</use>
</connection>
</customercode_write>
<customercode_read>
<connection>
<use>core_read</use>
</connection>
</customercode_read>
</resources>
<blocks>
<customercode>
<class>Form_Customercode_Block</class>
</customercode>
</blocks>

<helpers>
<customercode>
<class>Form_Customercode_Helper</class>
</customercode>
</helpers>

<events>
<controller_action_postdispatch_adminhtml_customer_validate>
<observers>
<customercode>
<type>singleton</type>
<class>customercode/observer</class>
<method>processAfterSaveEvent</method>
</customercode>
</observers>
</controller_action_postdispatch_adminhtml_customer_validate>
</events>
</global>

<frontend>
<routers>
<customercode>
<use>standard</use>
<args>
<module>Form_Customercode</module>
<frontName>customercode</frontName>
</args>
</customercode>
</routers>
</frontend>
</config>
local/form/customercode/model/observer.php
<?php
class Form_Customercode_Model_Observer extends Mage_Core_Model_Abstract
{
public function processAfterSaveEvent(Varien_Event_Observer $observer)
{
$controller = $observer->getEvent()->getControllerAction();
$response = new Varien_Object(Zend_Json::decode($controller->getResponse()->getBody()));

$data = $controller->getRequest()->getPost(‘account’);
if(!$data[‘customer_code’])
{
$response->setError(1);
Mage::getSingleton(‘adminhtml/session’)->addError(Mage::helper(‘adminhtml’)->__(“Please Fill Customer Code Field”));
$controller->_initLayoutMessages(‘adminhtml/session’);
$response->setMessage($this->getLayout()->getMessagesBlock->getGroupedHtml());
}
else
{
$checkCustomer = Mage::getModel(‘customercode/customercode’);
//->setWebsiteId($websiteId);

$i = $checkCustomer->loadByCustomercode($data[‘customer_code’]);
if($i[‘entity_id’]){
//if( $checkCustomer->getId() && ($checkCustomer->getId() != $customer->getId()) ) {
$response->setError(1);
Mage::getSingleton(‘adminhtml/session’)->addError(Mage::helper(‘adminhtml’)->__(‘Customer with the same Customer code already

exists.’));
//$this->_initLayoutMessages(‘adminhtml/session’);
//$response->setMessage($this->getLayout()->getMessagesBlock()->getGroupedHtml());
}
}
$controller->getResponse()->setBody($response->toJson());
}

}

local/form/customercode/model/customercode.php
<?php
// Mage_Core_Model_Abstract
class Form_Customercode_Model_Customercode extends Mage_Customer_Model_Customer
{
public function _construct()
{
$this->_init(‘customercode/customercode’);
}
public function loadByCustomercode($customerCode)
{
$this->_getResource()->loadByCustomercode($this,$customerCode);
return $this;
}
}

local/form/customercode/model/Entity/customercode.php

<?php
//Mage_Core_Model_Mysql4_Abstract
class Form_Customercode_Model_Entity_Customercode extends Mage_Eav_Model_Entity_Abstract
{
public function __construct()
{
$resource = Mage::getSingleton(‘core/resource’);
$this->setType(‘customer’);
$this->setConnection(
$resource->getConnection(‘customer_read’),
$resource->getConnection(‘customer_write’)
);
}
public function loadByCustomercode(Mage_Customer_Model_Customer $customer,$customerCode)
{
$select = $this->_getReadAdapter()->select()
->from($this->getEntityTable(), array($this->getEntityIdField()))
->where(‘customer_code=:’.$customerCode);

$select = $this->_getReadAdapter()->select()
->from($this->getTable(‘customer_entity_varchar’),’entity_id’)
->where(‘value=’.$customerCode);

//SELECT entity_id FROM customer_entity_varchar where attribute_id = 524;

if ($id = $this->_getReadAdapter()->fetchOne($select, array(‘customer_code’ => $customerCode))) {
$this->load($customer, $id);
}
else {
$customer->setData(array());
}
return $this;
}

/*public function loadByEmail(Mage_Customer_Model_Customer $customer, $email, $testOnly = false)
{
$select = $this->_getReadAdapter()->select()
->from($this->getEntityTable(), array($this->getEntityIdField()))
//->where(’email=?’, $email);
->where(’email=:customer_email’);
if ($customer->getSharingConfig()->isWebsiteScope()) {
if (!$customer->hasData(‘website_id’)) {
Mage::throwException(Mage::helper(‘customer’)->__(‘Customer website id must be specified, when using website scope.’));
}
$select->where(‘website_id=?’, (int)$customer->getWebsiteId());
}

if ($id = $this->_getReadAdapter()->fetchOne($select, array(‘customer_email’ => $email))) {
$this->load($customer, $id);
}
else {
$customer->setData(array());
}
return $this;
}*/
}

locla/form/Customercode/sql/customercode_setup/mysql4-install-0.1.0.php

<?php

$installer = $this;

/* @var $installer Mage_Customer_Model_Entity_Setup */
$installer->startSetup();

$installer->addAttribute(‘customer’, ‘customer_code’, array(
‘label’        => ‘Customer Code’,
‘visible’      => 1,
‘position’     => 1,
‘required’     => true,
‘searchable’   => true,
‘unique’       => 1,
));

$installer->endSetup();

important notes::

local/practice/provider/block/contact.php
<?php
class Practice_Provider_Block_Contact extends Mage_Adminhtml_Block_Widget_Grid_Container
{
protected $_blockGroup = ‘provider’;
public function __construct()
{
$this->_controller = ‘contact’;
$this->_headerText = Mage::helper(‘provider’)->__(‘Providers’);
$this->_addButtonLabel = Mage::helper(‘provider’)->__(‘Create New Provider’);
parent::__construct();
if (!Mage::getSingleton(‘admin/session’)->isAllowed(‘warranty/contact/actions/create’)) {
$this->_removeButton(‘add’);
}
}

public function getCreateUrl()
{
return $this->getUrl(‘*/create/start’);
}
}

local/practice/provider/block/create.php
<?php
class Practice_Provider_Block_Create extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$providerObject = new Varien_Object();
$providerModel  = Mage::getSingleton(‘provider/provider’);
$providerObject->setData($providerModel->getData());
$form = new Varien_Data_Form();
$fieldset = $form->addFieldset(‘new_provider’, array(‘legend’ => Mage::helper(‘provider’)->__(‘Provider Details’)));
$fieldset->addField(‘name’, ‘text’, array(
‘name’      => ‘name’,
‘title’     => Mage::helper(‘provider’)->__(‘Name’),
‘label’     => Mage::helper(‘provider’)->__(‘Name’),
‘maxlength’ => ’50’,
‘required’  => true,
));
$fieldset->addField(‘contact_detail’, ‘text’, array(
‘name’      => ‘contact_detail’,
‘title’     => Mage::helper(‘provider’)->__(‘Contact Detail’),
‘label’     => Mage::helper(‘provider’)->__(‘Contact Detail’),
‘maxlength’ => ‘255’,
‘required’  => true,
));
$fieldset->addField(‘ordering_method’, ‘text’, array(
‘name’      => ‘ordering_method’,
‘title’     => Mage::helper(‘provider’)->__(‘Ordering Method’),
‘label’     => Mage::helper(‘provider’)->__(‘Ordering Method’),
‘maxlength’ => ‘255’,
‘required’  => true,
));
$fieldset->addField(‘submit’, ‘submit’, array(
‘name’      => ‘submit’,
‘title’     => Mage::helper(‘provider’)->__(‘Submit’),
‘maxlength’ => ‘255’,
‘required’  => true,
‘value’     => ‘Submit’
));
$form->setMethod(‘post’);
$form->setUseContainer(true);
$form->setId(‘edit_form’);
$form->setEnctype(‘multipart/form-data’);
$form->setAction($this->getUrl(‘*/*/post’));
$this->setForm($form);
}
}
local/practice/provider/block/edit.php
<?php
class Practice_Provider_Block_Edit extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$providerObject = new Varien_Object();
$providerModel  = Mage::getSingleton(‘provider/provider’);
$providerObject->setData(providerModel->getData());
$form = new Varien_Data_Form(array(
‘id’        => ‘edit_form’,
‘action’    => $this->getUrl(‘*/*/save’, array(‘id’ => $this->getRequest()->getParam(‘id’))),
‘method’    => ‘post’,
‘enctype’   => ‘multipart/form-data’
));
$fieldset = $form->addFieldset(‘edit_provider’, array(‘legend’ => Mage::helper(‘provider’)->__(‘Provider Details’)));
$fieldset->addField(‘name’, ‘text’, array(
‘name’      => ‘name’,
‘title’     => Mage::helper(‘provider’)->__(‘Name’),
‘label’     => Mage::helper(‘provider’)->__(‘Name’),
‘maxlength’ => ’50’,
‘required’  => true,
));
$fieldset->addField(‘contact_detail’, ‘text’, array(
‘name’      => ‘contact_detail’,
‘title’     => Mage::helper(‘provider’)->__(‘Contact Detail’),
‘label’     => Mage::helper(‘provider’)->__(‘Contact Detail’),
‘maxlength’ => ‘255’,
‘required’  => true,
));
$fieldset->addField(‘ordering_method’, ‘text’, array(
‘name’      => ‘ordering_method’,
‘title’     => Mage::helper(‘provider’)->__(‘Ordering Method’),
‘label’     => Mage::helper(‘provider’)->__(‘Ordering Method’),
‘maxlength’ => ‘255’,
‘required’  => true,
));
$form->setUseContainer(true);
$form->setValues(Mage::registry(‘frozen_provider’)->getData());
$this->setForm($form);
return parent::_prepareForm();
}

}
local/p/p/block/grid.php
<?php
class Practice_Provider_Block_Contact_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

public function __construct()
{
parent::__construct();
$this->setId(‘contact_grid’);
$this->setUseAjax(true);
$this->setDefaultSort(‘created_at’);
$this->setDefaultDir(‘DESC’);
$this->setSaveParametersInSession(true);
}

protected function _prepareCollection()
{
//$model = Mage::getModel(‘warranty/warranty’);
//$collection = $model->getCollection();
$collection = Mage::getResourceModel(‘provider/provider_collection’);
//$collection->addExpressionFieldToSelect(‘contact_name’,’CONCAT(title, ” “, fname, ” “, lname)’);
//$collection->addExpressionFieldToSelect(‘date’,’CONCAT(day, “/”, month, “/”, year)’);

//$collection->addExpressionAttributeToSelect(‘name’,
//            ‘CONCAT({{title}}, ” “, {{fname}}, ” “, {{lname}})’,
//            array(‘title’, ‘fname’, ‘lname’));
$this->setCollection($collection);
return parent::_prepareCollection();
}

protected function _prepareColumns()
{

$this->addColumn(‘id’, array(
‘header’        => Mage::helper(‘provider’)->__(‘ID’),
‘align’         => ‘right’,
‘width’         => ’20px’,
‘index’         => ‘id’,
));

$this->addColumn(‘name’, array(
‘header’        => Mage::helper(‘provider’)->__(‘Name’),
‘align’         => ‘left’,
‘width’         => ‘150px’,
‘index’         => ‘name’,
‘type’          => ‘text’,
‘truncate’      => 50,
‘escape’        => true,
));

$this->addColumn(‘contact_detail’, array(
‘header’        => Mage::helper(‘provider’)->__(‘Contact Detail’),
‘align’         => ‘left’,
‘index’         => ‘contact_detail’,
‘type’          => ‘text’,
‘escape’        => false,
));

$this->addColumn(‘ordering_method’, array(
‘header’        => Mage::helper(‘provider’)->__(‘Ordering Method’),
‘align’         => ‘left’,
‘index’             => ‘daytime’,
‘type’              => ‘text’,
‘escape’        => true,
‘index’         => ‘ordering_method’,
));

$this->addColumn(‘action’,
array(
‘header’    => Mage::helper(‘provider’)->__(‘Action’),
‘width’     => ’50px’,
‘type’      => ‘action’,
‘getter’     => ‘getId’,
‘actions’   => array(
array(
‘caption’ => Mage::helper(‘provider’)->__(‘Edit’),
‘url’     => array(‘base’=>’*/*/view’),
‘field’   => ‘id’
)
),
‘filter’    => false,
‘sortable’  => false,
));
return parent::_prepareColumns();
}

public function getRowUrl($row)
{
if (Mage::getSingleton(‘admin/session’)->isAllowed(‘provider/provider/actions/edit’)) {
return $this->getUrl(‘*/*/view’, array(‘id’ => $row->getId()));
}
return false;
}
//
//    public function getGridUrl()
//    {
//        return $this->getUrl(‘*/*/grid’, array(‘_current’=>true));
//    }

}

local/p/p/controllers/Contactcontroller.php
<?php
class Practice_Provider_ContactController extends Mage_Adminhtml_Controller_Action
{
public function indexAction()
{
$this->loadLayout()
->_addContent($this->getLayout()->createBlock(‘provider/contact’))
->renderLayout();
}

public function viewAction()
{
$this->loadLayout()
->_addContent($this->getLayout()->createBlock(‘provider/edit’))
->renderLayout();
}

public function saveAction()
{

}
}

local/p/p/controllers/Createcontroller.php
<?php
class Practice_Provider_CreateController extends Mage_Adminhtml_Controller_Action
{
public function indexAction()
{

}
public function startAction()
{
$this->loadLayout()
->_addContent($this->getLayout()->createBlock(‘provider/create’))
->renderLayout();
}

public function postAction()
{
$form = Mage::getModel(‘provider/provider’)
->setData($this->getRequest()->getPost());

//if you want to set any field to array element then use array..

$form->save();
$this->_redirect(‘/contact/index/’);
}
}
etc/config.xml
<?xml version=”1.0″?>
<config>
<modules>
<Practice_Provider>
<version>0.1.0</version>
</Practice_Provider>
</modules>
<admin>
<routers>
<provider>
<use>admin</use>
<args>
<module>Practice_Provider</module>
<frontName>provider</frontName>
</args>
</provider>
</routers>
</admin>
<global>
<models>
<provider>
<class>Practice_Provider_Model</class>
<resourceModel>provider_mysql4</resourceModel>
</provider>
<provider_mysql4>
<class>Practice_Provider_Model_Mysql4</class>
<entities>
<provider>
<table>provider</table>
</provider>
</entities>
</provider_mysql4>
</models>

<resources>
<provider_setup>
<setup>
<module>Practice_Provider</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</provider_setup>
<provider_write>
<connection>
<use>core_write</use>
</connection>
</provider_write>
<provider_read>
<connection>
<use>core_read</use>
</connection>
</provider_read>
</resources>
<blocks>
<provider>
<class>Practice_Provider_Block</class>
</provider>
</blocks>

<helpers>
<provider>
<class>Practice_Provider_Helper</class>
</provider>
</helpers>
</global>

<adminhtml>
<menu>
<provider translate=”title” module=”provider”>
<title>Provider</title>
<sort_order>200</sort_order>
<action>provider/contact</action>
</provider>
</menu>
</adminhtml>

<frontend>
<routers>
<warranty>
<use>standard</use>
<args>
<module>Practice_Provider</module>
<frontName>provider</frontName>
</args>
</warranty>
</routers>

</frontend>

</config>

local/p/pmodel/provider.php
<?php
class Practice_Provider_Model_Provider extends Mage_Core_Model_Abstract
{
protected function _construct()
{
$this->_init(‘provider/provider’);
}
}
local/p/pmodel/session.php
<?php
class Practice_Provider_Model_Session extends Mage_Core_Model_Session_Abstract
{
public function __construct()
{
$this->init(‘provider’);
}

}
local/p/p/model/provider.php

<?php
class Practice_Provider_Model_Mysql4_Provider extends Mage_Core_Model_Mysql4_Abstract
{
protected function _construct()
{
$this->_init(‘provider/provider’, ‘id’);
}
}

local/p/p/model/mysql/provider/collection.php

<?php
class Practice_Provider_Model_Mysql4_Provider_Collection  extends  Mage_Core_Model_Mysql4_Collection_Abstract
{
protected function _construct()
{
$this->_init(‘provider/provider’);
}

public function addExpressionFieldToSelect($alias,$fullExpression)
{
$this->getSelect()->from(null, array($alias=>$fullExpression));

$this->_joinFields[$alias] = array(
‘table’ => true,
‘field’ => $fullExpression
);
return $this;

}
}

« Newer Posts - Older Posts »

Categories