Search This Blog

Tuesday, November 22, 2011

code to create virtual host, Setting Up A Virtual Host in Apache

Setting Up A Virtual Host in Apache

Setting up a virtual host in the Apache web server is not exactly a PHP topic, but many PHP developers use the Apache web server to test web pages on their development machine.

There is a lot of information around on how to do this, but the first time I tried it, I found the existing information to be more confusing than helpful. Hopefully, this page will simplify the process a bit. Please note that this information pertains to setting up a virtual host in Apache on a Windows machine for use as a local testing server. Setting up a virtual host for an actual production server is beyond the scope of this article and you should refer to the official Apache documentation for that.
Configuring Apache

The first file we'll need to edit is the Apache httpd.conf file. If you installed the Apache software using the download from the Apache web site, you should have a menu item that will open this file for editing. Click Start->Programs->Apache HTTP Server->Configure Apache Server->Edit the Apache httpd.conf Configuration File. If you don't have that start menu item, start your text editor and open the file. It will be in a sub-folder named conf of your Apache folder. For example, mine is here:

C:\Program Files\Apache Group\Apache\conf\httpd.conf
Notes for Apache Server Versions Since 2.2
Configuration

Note that Apache changed the preferred method for configuring the Apache server with the release of Apache 2.2. For versions beginning with 2.2, the peferred configuration is more modular. Setting up a virtual host as described here will still work with the newer versions, but to follow the modular approach, the editing of httpd.conf is only to uncomment (remove the # from the beginning of the following line:

#Include conf/extra/httpd-vhosts.conf

Everything else is entered in the file httpd-vhosts.conf, which will be located in the extra folder below the below the folder containing httpd.conf. As mentioned, the method described here will still work.
Security

Version 2.2 also changed some of the default security configuration parameters. To set things up the way you'll need them, you'll need to add the following block to either your httpd.conf file, just above the virtual hosts, or to your httpd-vhosts.conf file:


Order Deny,Allow
Allow from all


The above assumes you're using the directory structure described below. Adjust that as necessary to reflect your actual directory.

Now, for this example, we'll assume that you have your web sites located in a folder on your C drive called My Sites. Each web site has a sub-folder of its own under that folder, like this:

C:\My Sites\Site1
C:\My Sites\Site2

Say also, for this example, that the domains for the two sites are site1.com and site2.com. We're going to set up virtual hosts for those two sites using the domain names site1.local and site2.local. That way, you'll be able to tell at a glance whether you're looking at the live site, or your testing site.

In reality, you can call the domains anything you want. You could just as easily name them microsoft.monkeybutt and ibm.greentambourine. I choose to use the convention of using the same domain name along with the .local TLD to simplify and minimize the typing needed to switch between the live site and the testing site. The only important point, and it's really important, is that you NEVER use an actual, real, live domain name. If you used, for example, site1.com for the local virtual host, you would never be able to actually reach the live site. All requests for the live site would be re-directed to your local virtual host.

Go to the very bottom of your httpd.conf file in your text editor. You should see an example of a virtual host there. Each line of that example will begin with an octothorpe (#). The octothorpe character marks the line as a comment, so the example is not executed. Add the following lines below that example:

NameVirtualHost 127.0.0.1


DocumentRoot "C:\My Sites\Site1"
ServerName site1.local



DocumentRoot "C:\My Sites\Site2"
ServerName site2.local


That's all you need to do! Save and close the file. That will tell the Apache server everything it needs to know in order for it to serve the pages using the domain names site1.local and site2.local. One note is that, in the above example, we have a space in the path. Because of that, we put quotation marks around the document root directory. If the path does not have any spaces in it, do not quote the path. If the directory used for your sites were, for example MySites instead of My Sites, the document root line would look like this instead:

DocumentRoot C:\MySites\Site1

Resolving the DNS issue

Obviously, if you typed http://site1.local in your browser, it would not be found by your Internet provider's DNS server. We're next going to edit another file to work around that. The second file you need to edit is called hosts, with no file extension. It is a Windows system file and it will enable you to enter specific addresses for specific domains instead of using a DNS lookup. The normal location for this file is:

C:\WINNT\system32\drivers\etc\hosts

or

C:\Windows\system32\drivers\etc\hosts

If you don't find it there, do a search in your windows directory for the word hosts in the file name. The file you want is called hosts, with no file extension. The correct file will begin with the following lines:

# Copyright (c) 1993-1999 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.


Once again, in this file, the octothorpe character is a comment marker. Lines beginning with it are comments. In all likelihood, there will be nothing there, except for comments. If there are any other non-commented entries, leave them alone. Just go to the bottom of the file, below all the comments and any existing entries and add the following two lines:

127.0.0.1 site1.local
127.0.0.1 site2.local

That's all you need to do there. Save and close the hosts file.

You're almost done! The only remaining thing you need to do is to re-start the Apache server. You need to do this because Apache only reads the configuration file when it first starts up. Click Start->Programs->Apache HTTP Server->Control Apache Server->Restart. If you don't have that menu item, open a command prompt and change to the Apache directory, and type the following command and press the Enter key:

apache -w -n "Apache" -k restart

You should see a message like this:

The Apache service is restarting.
The Apache service has restarted.

That's it! You're done! Close the command window and start your web browser. In the browser's address bar, type http://site1.local and hit the Enter key. You should now see your local copy of your site1.

Okay, now I'll mention one very small, but possibly important, caveat. When you create the virtual hosts like this, the default http://localhost will no longer work. In many cases, that is unimportant. However, if you're using something like phpMyAdmin, you'll still need it. The solution to that is to create one additional virtual host called "localhost" that points to the original Apache htdocs folder. It might look something like this:


DocumentRoot C:\Apache\htdocs
ServerName localhost



Don't forget to include that additional virtual host when you edit the Windows hosts file.

Note that there are other optional settings you can use to configure the virtual host. The above uses only two lines and that's all that's really necessary. You can read about other options in the Apache documentation. Note that this link is to the Apache web site and it will open a new browser window.

I hope you found this more helpful than confusing. Good luck!

Link http://apptools.com/phptools/virtualhost.php


<VirtualHost *:80>
ServerAdmin iyer.shivakumar@gmail.com
DocumentRoot "d:\magento"
ServerName magento.localhost.com

Options Indexes FollowSymLinks
    <Directory "d:\magento">
        Order allow,deny
        Allow from all
        AllowOverride All
    </Directory>
</VirtualHost>

Saturday, November 12, 2011

magento

download magento, ecommerce magento, featured products magento, install magento, magento, magento alternative, magento blog, magento cms, magento community edition, magento community features, magento connect, magento customization, magento demo, magento design, magento designer, magento developers, magento download, magento ecommerce, magento expert, magento extension, magento feature, magento feature list, magento featured, magento featured product, magento featured products, magento featured products extension, magento go, magento help, magento install, magento mobile, magento module, magento modules, magento plugins, magento seo, magento shops, magento software, magento specialist, magento ssl, magento store, magento support, magento template, magento templates free, magento theme, magento themes, magento user guide, magento website, magentocommerce, premium magento themes, seo magento, templates magento

Sunday, November 6, 2011

Friday, October 28, 2011

Free one click cart checkout community edition

Free one click cart checkout community edition

Magento 2.0
http://connect20.magentocommerce.com/community/GoldenSpiralStudio_OneClickCartCheckout
Magento 1.0
magento-community/GoldenSpiralStudio_OneClickCartCheckout

refrence
http://www.magentocommerce.com/magento-connect/GoldenSpiralStd/extension/6971/goldenspiralstudio_oneclickcartcheckout

Tuesday, October 18, 2011

magento create customer custom attribute throuogh sql or code

$installer = $this;

$installer->startSetup();

$connection = $installer->getConnection();

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

$installer->removeAttribute('customer', 'name_goes_here');

$setup->addAttribute('customer', 'name_goes_here', array(
'input' => 'text',
'type' => 'varchar',
'label' => 'name_goes_here',
'backend' => '',
'visible' => 1,
'required' => 0,
'user_defined' => 1,
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));
$installer->endSetup();

$installer->installEntities();

use this in mysql4-upgrade-0.1.0-0.1.1.php or any latest sql folder script

Tuesday, September 20, 2011

How to Remove Product from cart on checkout page or by coding in magento

$session= Mage::getSingleton('checkout/session');
$quote = $session->getQuote();

$cart = Mage::getModel('checkout/cart');
$cartItems = $cart->getItems();
foreach ($cartItems as $item)
{
$quote->removeItem($item->getId())->save();
}

Wednesday, August 24, 2011

Magento display gift message in front end

$message = Mage::getModel('giftmessage/message');

/* Add Gift Message*/
$gift_message_id = $order->getOrder()->getGiftMessageId();
if(!is_null($gift_message_id)) {
$message->load((int)$gift_message_id);
$gift_sender = $message->getData('sender');
$gift_recipient = $message->getData('recipient');
echo $gift_message = $message->getData('message');
}
http://www.magentocommerce.com/boards/viewthread/11346/

Friday, August 12, 2011

best php export to csv without space or comma

$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// DB Connection here
$db = mysql_select_db("test",$con);

$result = mysql_query("SELECT * FROM test1");
csvToExcelDownloadFromResult($result);
function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
setExcelContentType();
setDownloadAsHeader($asFilename);
return csvFileFromResult('php://output', $result, $showColumnHeaders);
}

function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
$fp = fopen($filename, 'w');
$rc = csvFromResult($fp, $result, $showColumnHeaders);
fclose($fp);
return $rc;
}
function setExcelContentType() {
if(headers_sent())
return false;

header('Content-type: application/vnd.ms-excel');
return true;
}

function setDownloadAsHeader($filename) {
if(headers_sent())
return false;

header('Content-disposition: attachment; filename=' . $filename);
return true;
}
function csvFromResult($stream, $result, $showColumnHeaders = true) {
if($showColumnHeaders) {
$columnHeaders = array();
$nfields = mysql_num_fields($result);
for($i = 0; $i < $nfields; $i++) { $field = mysql_fetch_field($result, $i); $columnHeaders[] = $field->name;
}
fputcsv($stream, $columnHeaders);
}

$nrows = 0;
while($row = mysql_fetch_row($result)) {
fputcsv($stream, $row);
$nrows++;
}

return $nrows;
}

Monday, July 25, 2011

Using php to display visitor / user information such as their IP address

$ip = $_SERVER['REMOTE_ADDR'];
$hostaddress = gethostbyaddr($ip);
$browser = $_SERVER['HTTP_USER_AGENT'];
$referred = $_SERVER['HTTP_REFERER']; // a quirky spelling mistake that stuck in php

print "Display IP address:
\n";
print "$ip

\n";
print "More detailed host address:
\n";
print "$hostaddress

\n";
print "Display browser info:
\n";
print "$browser

\n";
print "Where you came from (if you clicked on a link to get here:
\n";
if ($referred == "") {
print "Page was directly requested";
}
else {
print "$referred";
}

magento how to use distinct or get unique records from collection

magento how to use distinct or get unique records from collection

$collection = Mage::getModel('catalog/product')->getCollection()
->distinct(true)
->addAttributeToSelect('color')
->load();

Sunday, July 17, 2011

Magento send mails like contact us form or forms or how to send mails in magento

if(!empty($post)) { $translate = Mage::getSingleton('core/translate');
$translate->setTranslateInline(false); try { $name = $_POST['name'];
$email = $_POST['email']; $to_admin =
Mage::getStoreConfig('trans_email/ident_general/email'); $name_admin =
Mage::getStoreConfig('trans_email/ident_general/name'); $subject =
'Contact Us'; /*$vars = array('Name'=>$name, 'Email Id' =>$email ); */

//const EMAIL_TEMPLATE_XML_PATH = 'customer/testemail/email_template';
//$templateId = Mage::getStoreConfig(EMAIL_TEMPLATE_XML_PATH);
$templateId=1; $sender = array('name' => $name,'email' => $email);

$translate=Mage::getModel('core/email_template')
->setTemplateSubject($subject) ->sendTransactional($templateId, $sender,
$to_admin, $name_admin, array('data' => $vars));
$translate->setTranslateInline(true);

Mage::getSingleton('core/session')->addSuccess(Mage::helper('customer')->__('Data
Sent Successfully')); $url = Mage::getUrl().'thanks';
Mage::app()->getFrontController()->getResponse()->setRedirect($url); }
catch (Exception $e) {
Mage::getSingleton('core/session')->addError(Mage::helper('customer')->__('Unable
to send email.')); $url = Mage::getUrl().'contactus';
Mage::app()->getFrontController()->getResponse()->setRedirect($url);
return; } }

Friday, July 15, 2011

admin store email magento general contacts email or Magento: Store Mail Addresses

//General contact
Mage::getStoreConfig('trans_email/ident_gerneral/name');
Mage::getStoreConfig('trans_email/ident_gerneral/email');

//Sales Representative
Mage::getStoreConfig('trans_email/ident_sales/name');
Mage::getStoreConfig('trans_email/ident_sales/email');

//Customer Support
Mage::getStoreConfig('trans_email/ident_support/name');
Mage::getStoreConfig('trans_email/ident_support/email');

//Custom email1
Mage::getStoreConfig('trans_email/ident_custom1/name');
Mage::getStoreConfig('trans_email/ident_custom1/email');

//Custom email2
Mage::getStoreConfig('trans_email/ident_custom2/name');
Mage::getStoreConfig('trans_email/ident_custom2/email');

Tuesday, July 12, 2011

Magento get path id or getpathids function to get parent category untill or upto root category

Magento get path id or getpathids function to get parent category untill or upto root category

getPathIds ()
Get array categories ids which are part of category path Result array contain id of current category because it is part of the path

Returns:
array

Definition at line 584 of file Category.php.

00585 {
00586 $ids = $this->getData('path_ids');
00587 if (is_null($ids)) {
00588 $ids = explode('/', $this->getPath());
00589 $this->setData('path_ids', $ids);
00590 }
00591 return $ids;
00592 }

magento reference doc or documents or docs

magento reference doc or documents or docs

http://freegento.com/doc/

Friday, July 8, 2011

Magento sql queries or queries or query in magento

getConnection('core_read');
//make connection
$qry = "select name FROM user_data WHERE id=1 LIMIT 1 "; //query
$res = $read->fetchRow($qry); //fetch row
$name = $res['name']; //outputs name

//other form
$qry = "select name FROM user_data WHERE namer LIKE '%a%' ";//query
$res = $read->fetchAll($qry); //get array

//Insert query
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$sql = "INSERT INTO user_data values (?,?)"; //insert query
$write->query($sql, array('name','pass')); //write to database

?>

Tuesday, July 5, 2011

Magento get root category id or magento getRootCategory or function to get root category id or magento getRootCategory()

Mage::app()->getWebsite(true)->getDefaultStore()->getRootCategoryId()

magento get parent category of or from current category

You can get current category from the following code:
$currentCategory = Mage::registry('current_category');

You can get the parent category from the following code:

/**
* You want the parent category of a sub-category
* Let the sub-category be $subCategory
*/

$parentCategory = Mage::getModel('catalog/category')->load($subCategory->getParentId());

Wednesday, June 1, 2011

Magento - How to run a SQL query against the database

$db = Mage::getResourceSingleton('core/resource')->getConnection('core_write');
$result = $db->query('SELECT 'entity_id' FROM 'catalog_product_entity');

if(!$result) {
return FALSE;
}

$rows = $result->fetch(PDO::FETCH_ASSOC);

if(!$rows) {
return FALSE;
}

print_r($rows);

Thursday, May 26, 2011

Magento admin redirect from a form

Class used  Mage_Core_Controller_Varien_Action class.

 Redirect to url
_redirectUrl($url)

Check url to be used as internal
_isUrlInternal($url)

Redirect to error page
_redirectError($defaultUrl)


 Redirect to path
_redirect($path, $arguments=array())



 Redirect to success page
_redirectSuccess($defaultUrl)

Identify referer url via all accepted methods (HTTP_REFERER, regular or base64-encoded request param)
_getRefererUrl()

 Set referer url for redirect in response
_redirectReferer($defaultUrl=null)


You can use the redirect functions in your controller class.: $url = "http://abc.com";

$this->_redirectUrl($url);


Redirect with path and arguments:-

Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl($path, $arguments));




Mage::app()->getFrontController()->getResponse()->setRedirect($url);

Wednesday, May 25, 2011

magento custom csv import module

The basic case you may wonder how to do, is import of data for your custom module. Let's do this by example. Imagine you need to display on you e-shop list of stores, you have created custom module, table in database and datamodel part, all you need now is to populate this table with data you have within csv file.

Read the file
First you have to read the file. As you already know (if you read Magento Dataflow - Default Adapters [Part 2]) you can use dataflow/convert_adapter_io adapter for this.


file
var/import





Parse the file content

Now that you have read the file content, you should parse it using dataflow/convert_parser_csv.





true

1



Process rows of data

Now the custom part of this process. Within your custom module you have to create custom adapter that will create row in database for each processed row of parsed file. Within your module root directory create file ./Model/Convert/Adapter/Store.php of this content:

class Baobaz_Offer_Model_Convert_Adapter_Offer
extends Mage_Dataflow_Model_Convert_Adapter_Abstract
{
protected $_storeModel;

public function load() {
// you have to create this method, enforced by Mage_Dataflow_Model_Convert_Adapter_Interface
}

public function save() {
// you have to create this method, enforced by Mage_Dataflow_Model_Convert_Adapter_Interface
}

public function getStoreModel()
{
if (is_null($this->_storeModel)) {
$storeModel = Mage::getModel('baobaz_store/store');
$this->_storeModel = Mage::objects()->save($storeModel);
}
return Mage::objects()->load($this->_storeModel);
}

public function saveRow(array $importData)
{
$store = $this->getStoreModel();

if (empty($importData['code'])) {
$message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'code');
Mage::throwException($message);
}
else
{
$store->load($importData['code'],'code');
}

$store->setCode($importData['code']);
$store->setName($importData['name']);

$store->save();

return true;

}
}
Now when you have this file created you can modify a little bit the declaration of parser adding adapter and method variables:





true

1

baobaz_store/convert_adapter_store
saveRow


Having this done you should have your xml definition of custom dataflow profile looking like that:


file
var/import






true

1

baobaz_store/convert_adapter_store
saveRow


Source http://blog.baobaz.com/en/blog/customizing-magento-dataflow-import-of-custom-data
http://www.ayasoftware.com/content/how-import-configurable-products-csv-file-magento-system

magento get simple products id from configurable products

magento get simple products id from configurable products
wherer $_product is the configurable product
$ids = $_product->getTypeInstance()->getUsedProductIds();
OR
$loader = Mage::getResourceModel( 'catalog/product_type_configurable' )->load($_product);

Tuesday, May 24, 2011

Remove or rename add new save continue delete button from magento admin

If you don’t want to show the ‘Add New’ button in the Grid. The Add New button is present in top right corner of Grid Page.

Rename ‘Add New’ button

Here are the steps to rename the ‘Add New’ text to anything you required (for example, ‘Add Report’):-

- Go to YourNamespace -> YourModule -> Block -> Adminhtml -> YourFile.php
- Add the following code in the constructor of this file:-

$this->_addButtonLabel = Mage::helper('yourmodulename')->__('Add Report');

Remove ‘Add New’ button

Here are the steps to remove the ‘Add New’ button:-

- Go to YourNamespace -> YourModule -> Block -> Adminhtml -> YourFile.php
- Add the following code in the constructor of this file (it should be just below the call to parent constructor):-

parent::__construct();
$this->_removeButton('add');


In edit.php
parent::__construct();
$this->_removeButton('delete');
$this->_removeButton('save');
$this->_removeButton('back');

in grid.php
parent::__construct();
$this->_removeButton('add');

Monday, May 16, 2011

magento get last added item from session or get cart items from session

How to get all cart items from cart session in magento

$productid=Mage::getSingleton('checkout/session')->getLastAddedProductId(true);

-----------OR----------------------------
$session= Mage::getSingleton('checkout/session');
foreach($session->getQuote()->getAllItems() as $item)
{
$productid = $item->getProductId();
$productsku = $item->getSku();
$productname = $item->getName();
$productqty = $item->getQty();
}

Wednesday, May 11, 2011

Magento query to check for product visible or visibility and enable or is_enable

Magento query to check for product visible or visibility and enable or is_enable

$visibility = array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG);
$prod= Mage::getModel('catalog/product')->getCollection();
->addAttributeToFilter('visibility', $visibility);
->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);

Wednesday, April 27, 2011

Magento get last product or recent product added to cart or shopping cart

Magento get last product or recent product added to cart or shopping cart


Mage::getSingleton('checkout/session')->getLastAddedProductId(true);

Tuesday, April 26, 2011

Add magento to wishlist code

a href="'.Mage::helper("wishlist")->getAddUrl($_product).'" class="link-cart">Add to Wishlist /a

or

if ($this->helper('wishlist')->isAllow()) :
a href="helper('wishlist')->getAddUrl($_product) ?>" class="link-cart">__('Add to Wishlist') ?> /a
endif;

Friday, April 22, 2011

Magento PHP Interview Questions And Answers

1) What are the different types of Errors in PHP?
Answer:
There are three basic types of runtime errors in PHP:
1. Notices: These are small, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although the default behavior can be changed.
2. Warnings: Warnings are more severe errors like attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
3. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.




2) Why Magento use EAV database model ?

Answer:

In EAV database model, data are stored in different smaller tables rather than storing in a single table.

product name is stored in catalog_product_entity_varchar table
product id is stored in catalog_product_entity_int table
product price is stored in catalog_product_entity_decimal table

Magento Use EAV database model for easy upgrade and development as this model gives more flexibility to play with data and attributes.


3) What is the difference between Mage::getSingletone() and Mage::getModel() in Magento
Answer:

Mage::getSingletone() always finds for an existing object if not then create that a new object but Mage::getModel() always creates a new object.

Get Product ID and Product Name in Magento

load($productid); //getting product object for particular product id

echo $_product->getShortDescription(); //product's short description
echo $_product->getDescription(); // product's long description
echo $_product->getName(); //product name
echo $_product->getPrice(); //product's regular Price
echo $_product->getSpecialPrice(); //product's special Price
echo $_product->getProductUrl(); //product url
echo $_product->getImageUrl(); //product's image url
echo $_product->getSmallImageUrl(); //product's small image url
echo $_product->getThumbnailUrl(); //product's thumbnail image url

?>
------OR------------
getCollection(); //products collection
foreach ($collection as $product) //loop for getting products
{

$model->load($product->getId());
$pname = $model->getName();
if(strcmp($pname,$product_name)==0)
{
$id = $product->getId();
}
}
echo 'Required ID->'.$id; //id of product
?>

Monday, April 11, 2011

Magento Collection Functions getSelect,getSize,getSelectSql,setOrder,distinct, getData,resetData,printLogQuery,getCurPage,getLastPageNumber,getPageSize,getSize,getFirstItem,getLastItem,getItems,clear


Here are some of the functions that you can use in your collection object:-


 Get Zend_Db_Select instance

$collection->getSelect();

 Add select order

$collection->getSelect()->setOrder($field, $direction);

 Get collection size : $collection->getSelect()->getSize(); : $collection->count()

 Retrieve collection all items count : $collection->getSelect()->getSize();

 Get sql select string or object

$collection->getSelect()->getSelectSql();


Field Filter to collection
 If $attribute is an array will add OR condition with following format:
 array(
 array('attribute'=>'email', 'like'=>'ramu@%'),
 array('attribute'=>'phone', 'like'=>'9759%'),
 )

$collection->getSelect()->setOrder($field, $condition);

 Get all data array for collection: $collection->getSelect()->getData();

 Set select distinct : $collection->getSelect()->distinct($flag);

 Print and/or log query : $collection->getSelect()->printLogQuery(true, true);

Reset loaded for collection data array : $collection->getSelect()->resetData();




Get current collection page : $collection->getSelect()->getCurPage();


 Retrieve collection last page number : $collection->getSelect()->getLastPageNumber();


 Retrieve collection page size :$collection->getSelect()->getPageSize();

 Clear collection : $collection->getSelect()->clear();

 Retrieve collection first item : $collection->getSelect()->getFirstItem();


 Retrieve collection last item : $collection->getSelect()->getLastItem();


 Retrieve collection items : $collection->getSelect()->getItems();



Monday, April 4, 2011

get skin url, get js url, get media url, get store url ,get base url in magneto

These are the following methods to get Magento Base Url, Magento Skin Url, Magento Media Url, Magento Js Url.to get all write the following code

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK); or you can write $this->getUrl();
e.g:- http://yoursite.com/index.php/

Get Magento Media Url
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
e.g:- http://yoursite.com/media/
Get Magento Skin Url

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN); or you can write $this->getSkinUrl();
e.g:- http://yoursite.com/skin/

Get Magento Store Url
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
e.g:- http://yoursite.com/

Get Magento Js Url
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
http://www.yoursite.com/js


Source http://xhtmlandcsshelp.blogspot.com/2010/11/magento-get-url-for-skin-media-js-store.html

Tuesday, March 22, 2011

Magento integrate editor Wysiwyg or magento what you see is what you get in form

In you Form.php integrate the code to get editor Wysiwyg

$fieldset->addField('field_name', 'editor', array(
'name' => 'field_name',
'label' => Mage::helper('Module_Helper_Name')->__('field_name'),
'title' => Mage::helper('Module_Helper_Name')->__('field_name'),
'style' => 'width:700px; height:500px;',
'wysiwyg' => true,
'config' => Mage::getSingleton('Module/wysiwyg_config')->getConfig(),

));

Now dont forget to add the WYSIWYG foder from the cms/model to your model folder

Sunday, March 20, 2011

How to create Configurable Products in Magento




Magento offers two options to create configurable products (products with options such as Size or Color):
  • Simple products with custom options (Recommended if you don’t plan to track inventory.)
  • Configurable products and associate simple products to it. (Recommended if you plan to track inventory.)
To create simple products log in your admin control panel select Catalogue => Manage Products => Create new product.
1. Simple products with custom options:
a) Create Simple Product
Magento
b) Fill out all required fields such as: General, Price, Meta Information, Description, Inventory, Websites and Categories.

Magento
c) Create Custom Option
Magento
d) Add a new option and add your own custom option. Our example is for Size.
Magento
e) Save the product and that is all. Your product must show your custom option on the front end.
Magento
2) Create a configurable product and associate simple products to it.
a) First you must create the attributes (make sure it can be used for configurable product)
To create an attribute log in your admin control panel select Catalogue => Manage Attributes => Create new attribute.
Magento
b) Our attribute code in this example is for Jacket Color.
Magento
c) Add label options and save the attribute.
Magento
d) Manage attribute set to default
To manage the attribute set log in your admin control panel select Catalogue => Manage Attributes => Manage Attribute Set.
Magento
e) Move the attribute created (in our case jacket color) to default attributes. You can easily move it, just drag and drop it, exactly where you want to display it.
Magento
f) Moved under default fields and save the attribute set.
Magento
g) Create the simple products and fill in the attribute. It is not required to add images, description. Set visibility to nowhere & save the product.
To create simple products log in your admin control panel select Catalogue => Manage Products => Create new product.
Magento
In our case we have our Jacket Color attribute in 4 colors: Red, Green, White, and Blue. We now have to create a simple product for each color. In total there will be 4 simple products. We can duplicate the products to make the process faster. (Just use a different Product name, Sku & Jacket Color.)
h) Once all simple products are done, we can create 1 configurable product for it.
Magento
i) In this example Configurable Product uses Jacket Color and therefore the box (for Jacket Color) is checked.
Magento
j) Create the configurable product and fill in all the dates required such as general, description, images, websites, and categories.
Magento
k) Under associated products category, the simple products created must be associated with the 4 simple products in our case & save the configurable product.
Magento
l) On the front end the drop down menu from Jacket Color will now be displayed.
Magento
Source 
http://webshop-conversion.com/2009/07/24/how-to-create-configurable-products-in-magento/

Tuesday, March 8, 2011

Magento form validation, text validation, url validation

Most important thing besides assigning class names to form in magento is that little piece of JavaScript below the form. Remember to pass form id into the new VarienForm object.

Basically that’s it. Constructing the form this way, automatically makes your form reuse already existing validation code, the one that the rest of the shop is using.

Below is a full list of validate class and its error message that I found in prototype lib.

    * validate-select

Please select an option.

    * required-entry

This is a required field.

    * validate-number

Please enter a valid number in this field.

    * validate-digits

Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.

    * validate-alpha

Please use letters only (a-z or A-Z) in this field.

    * validate-code

Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

    * validate-alphanum

Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed.

    * validate-street

Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field.

    * validate-phoneStrict

Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.

    * validate-phoneLax

Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.

    * validate-fax

Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890.

    * validate-date

Please enter a valid date.

    * validate-email

Please enter a valid email address. For example johndoe@domain.com.

    * validate-emailSender

Please use only letters (a-z or A-Z), numbers (0-9) , underscore(_) or spaces in this field.

    * validate-password

Please enter 6 or more characters. Leading or trailing spaces will be ignored.

    * validate-admin-password

Please enter 7 or more characters. Password should contain both numeric and alphabetic characters.

    * validate-cpassword

lease make sure your passwords match.

    * validate-url

Please enter a valid URL. http:// is required

    * validate-clean-url

Please enter a valid URL. For example http://www.example.com or www.example.com

    * validate-identifier

Please enter a valid Identifier. For example example-page, example-page.html or anotherlevel/example-page

    * validate-xml-identifier

Please enter a valid XML-identifier. For example something_1, block5, id-4

    * validate-ssn

Please enter a valid social security number. For example 123-45-6789.

    * validate-zip

Please enter a valid zip code. For example 90602 or 90602-1234.

    * validate-date-au

Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.

    * validate-currency-dollar

Please enter a valid $ amount. For example $100.00.

    * validate-one-required

Please select one of the above options.

    * validate-one-required-by-name

Please select one of the options.

    * validate-not-negative-number

Please enter a valid number in this field.

    * validate-state

Please select State/Province.

    * validate-new-password

Please enter 6 or more characters. Leading or trailing spaces will be ignored.

    * validate-greater-than-zero

Please enter a number greater than 0 in this field.

    * validate-zero-or-greater

Please enter a number 0 or greater in this field.

    * validate-cc-number

Please enter a valid credit card number.

    * validate-cc-type

Credit card number doesn\’t match credit card type

    * validate-cc-type-select

Card type doesn\’t match credit card number

    * validate-cc-exp

Incorrect credit card expiration date

    * validate-cc-cvn

Please enter a valid credit card verification number.

    * validate-data

Please use only letters (a-z or A-Z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

    * validate-css-length

Please input a valid CSS-length. For example 100px or 77pt or 20em or .5ex or 50%

    * validate-length

Maximum length exceeded.


http://www.magestore.com/blog/2010/04/09/form-validation-on-magento/



Sunday, March 6, 2011

Magento: How to select, insert, update, and delete data


CRUD (Create Read Update Delete)

Database table named ‘article‘

INSERT DATA

$data contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.
$data = array('title'=>'test1,'content'=>'test2.','status'=>0);
$model = Mage::getModel('myarticle/myarticle')->setData($data);
try {
        $insertId = $model->save()->getId();
        echo "Data successfully inserted. Insert ID: ".$insertId;
    } catch (Exception $e){
     echo $e->getMessage();
}

SELECT DATA

$item->getData() prints array of data from ‘article’ table.
$item->getTitle() prints the only the title field.
Similarly, to print content, we need to write $item->getContent().
$model = Mage::getModel('myarticle/myarticle');
$collection = $model->getCollection();
foreach($collection as $item){
    print_r($item->getData());
    print_r($item->getTitle());
}

UPDAT

$id is the database table row id to be updated.
$data contains array of data to be updated. The key of the array should be the database table’s field name and the value should be the value to be updated.
// $id = $this->getRequest()->getParam('id');
$id = 2;
$data = array('title'=>'erewr','content'=>'dsfsdf','status'=>1);
$model = Mage::getModel('myarticle/myarticle')->load($id)->addData($data);
try {
        $model->setId($id)->save();
        echo "Data updated successfully.";

    } catch (Exception $e){
        echo $e->getMessage();
}

DELET

$id is the database table row id to be deleted.
// $id = $this->getRequest()->getParam('id');
$id = 3;
$model = Mage::getModel('myarticle/myarticle');
try {
        $model->setId($id)->delete();
        echo "Data deleted successfully.";

    } catch (Exception $e){
        echo $e->getMessage();
}

Monday, February 28, 2011

To add a tab in the right side of admin module form

To add a tab in the right side of admin module form

app\code\local\Namespace\module\Block\Adminhtml\module\Edit \Tabs.php
in function _beforeToHtml
copy paste the addTab code and change the name

Sunday, February 27, 2011

Magento export porduct as text file with txt extension for feed or feeds

Hey there

Check the code below for Magento export porduct as text file with txt extension for feed or feeds

Magento - Export & Import Custom Product Options

The code

<?php
    // Load Magento
    require_once $_SERVER['DOCUMENT_ROOT'] . "/app/Mage.php";
    umask(0);
    Mage::app();
   
    // set Store ID
    $storeId         = Mage::app()->getStore()->getStoreId();
   
    // set loop start timer
    $starttime         = microtime();
    $startarray     = explode(" ", $starttime);
    $starttime         = $startarray[1] + $startarray[0];
   
    // get basic configuration
    $baseUrl         = Mage::app()->getStore($storeId)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
    $baseMediaUrl     = Mage::getSingleton('catalog/product_media_config')->getBaseMediaUrl();
    $storeCharset    = Mage::getStoreConfig('design/head/default_charset');
   
    // set report email sender
    $from_email        = Mage::getStoreConfig('trans_email/ident_general/email');    // sender: general contact email
    $from_name        = Mage::getStoreConfig('trans_email/ident_general/name');    // sender: general contact name
   
    // set report email recipient from backend user "admin"
    Mage::getSingleton('core/session', array('name' => 'adminhtml'));
    $admin             = Mage::getModel('admin/user')->load(1);                     // load first administrator
    $to_email        = $admin->getEmail();                                        // recipient: admin email
    $to_name        = $admin->getFirstname() . ' ' . $admin->getLastname();        // recipient: admin name
   
    // set Google Base feed filename and directory
    $_feed_dir        = '/media/feed/';                                            // Feed directory
    $feedDir         = $_SERVER['DOCUMENT_ROOT'] . $_feed_dir;                    // Path to feed directory
    $gbaseFeed        = 'google_base_feed.txt';                                    // Google base feed filename
    $tmpCounter        = 'counter.txt';                                            // Temporary counter file
    $timer            = 'timer.txt';                                                // Temporary timer file
   
    // set log filename and directory
    $logDir            = $_SERVER['DOCUMENT_ROOT'] . '/var/log/';                    // Log directory
    $logFile        = $logDir . date('Y-m') . '-gbase-feed.log';                // Google base log filename
   
    // define basic file constants
    define('SAVE_FEED_LOCATION',     $feedDir . $gbaseFeed);                        // google base file
    define('SAVE_FEED_RELOAD',         $feedDir . $tmpCounter);                    // counter file
    define('SAVE_FEED_TIMER',        $feedDir . $timer);                            // timer file
               
    // make sure we don't time out
    @ini_set('max_execution_time', '0');
    @ini_set('max_input_time', '0');
    @set_time_limit(0);
    @ignore_user_abort(true);
   
    // set headers to Magento character set
    header('Content-Type: text/html; charset=' . $storeCharset);
       
    try
    {
       
        // create FEED directory in case it doesn't exist yet
        if (!file_exists($feedDir))
        {
            mkdir($feedDir, 0777);
        }
       
        // basic setup
        $reload_line         = (file_exists(SAVE_FEED_RELOAD)) ? file_get_contents(SAVE_FEED_RELOAD) : 0;
        $timer_line         = (file_exists(SAVE_FEED_TIMER)) ? file_get_contents(SAVE_FEED_TIMER) : 0;
        $handle                = ($reload_line == 0) ? fopen(SAVE_FEED_LOCATION, 'w') : fopen(SAVE_FEED_LOCATION, 'a+');
        $handle_reload         = fopen(SAVE_FEED_RELOAD, 'w');
        $handle_timer         = fopen(SAVE_FEED_TIMER, 'w');
       
        if ($reload_line == 0)
        {
            $heading         = array('id','title','description','link','image_link','price','brand','product_type','condition', 'c:product_code');
            $feed_line        = implode("\t", $heading) . "\r\n";
            fwrite($handle, $feed_line);
        }
       
        //---------------------- GET THE PRODUCTS   
        $visibility         =     array (
                                    Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
                                    Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
                                );
       
        $products = Mage::getModel('catalog/product')->getCollection();
        $products->addAttributeToFilter('status', 1);                     //enabled
        $products->addAttributeToFilter('visibility', $visibility);
        $products->addAttributeToSelect('sku');
        $prodIds = $products->getAllIds();
       
        foreach($prodIds as $productId)
        {
           
            if (($productId>=$reload_line) & ($productId<$reload_line+100))
            {
               
                // load product object
                $product                             = Mage::getModel('catalog/product');
                $product->load($productId);
               
                // populate product data array
                $product_data                         = array();   
                $product_data['sku']                = $product->getSku();   
                $product_data['title']                = $product->getName();
                $product_data['description']        = trim(ereg_replace("^[ \t\r\n]+|[ \t\r\n]+", " ", strip_tags($product->getShortDescription())));
                $product_data['link']                = $baseUrl . $product->getUrlKey() . Mage::getStoreConfig('catalog/seo/product_url_suffix') . '?source=googleps';
                $product_data['image_link']            = $baseMediaUrl . $product->getImage();
                $product_data['price']                = $product->getFinalPrice();
                $product_data['brand']                = $product->getAttributeText('manufacturer');   
                $product_data['product_type']         = '';
                $product_data['condition']            = 'new';
                $product_data['c:product_code']        = $product->getSku();
                   
                //get the product categories                   
                foreach($product->getCategoryIds() as $_categoryId)
                {
                    $category                         = Mage::getModel('catalog/category')->load($_categoryId);
                    $product_data['product_type']    .= $category->getName().', ';
                }
                $product_data['product_type']        = rtrim($product_data['product_type'],', ');       
   
                //sanitize data   
                foreach($product_data as $k=>$val)
                {
                    $bad                            = array('"',"\r\n","\n","\r","\t");
                    $good                            = array(""," "," "," ","");
                    $product_data[$k]                 = '"'.str_replace($bad,$good,$val).'"';
                }

                $feed_line                             = implode("\t", $product_data)."\r\n";
                fwrite($handle, $feed_line);
                fflush($handle);
                       
            }
        }

        //---------------------- WRITE THE FEED   
        fclose($handle);
        $feed_line_reload     = $reload_line + 100;
        fwrite($handle_reload, $feed_line_reload);
        fclose($handle_reload);
       
        // end of loop time
        $looptime             = microtime();
        $looparray             = explode(" ", $looptime);
        $looptime             = $looparray[1] + $looparray[0];
        $tmptime             = $looptime - $starttime;
       
        // sum of all passed loop times
        $feed_line_timer     = $timer_line + $tmptime;
        fwrite($handle_timer, $feed_line_timer);
        fclose($handle_timer);
    }
    catch(Exception $e)
    {
        //---------------------- LOG THE EXCEPTION   
        if (!file_exists($logDir))
        {
            mkdir($logDir, 0777);
        }
       
        if (!file_exists($logFile))
        {
            touch($logFile);
           
            $logHandle = fopen($logFile, 'w+');
           
            fwrite(              
                   $logHandle,
                   date('Y-m-d  H:i:s') . "  |  GOOGLE BASE FEED GENERATION PROBLEM\n\n" .
                   $e->getMessage() . "\n\n" .
                   "-------------------------------------------------------------------------------------------------------------------\n\n"
            );
           
            fclose($logHandle);        
        }
        else
        {
           
            $ini_handle     = fopen($logFile, "r");
            $ini_contents     = fread($ini_handle, filesize($logFile));
            fclose($ini_handle);
           
            $logHandle         = fopen($logFile, 'w+');
            fwrite(
                   $logHandle,
                   date('Y-m-d  H:i:s') . "  |  GOOGLE BASE FEED PROBLEM\n\n" .
                   $e->getMessage() . "\n\n" .
                   "-------------------------------------------------------------------------------------------------------------------\n\n" .
                   $ini_contents
            );
            fclose($logHandle);
           
        }
       
        //---------------------- SEND THE EXCEPTION    TO the ADMIN'S EMAIL
        $mail = new Zend_Mail($storeCharset);
        $mail->setBodyText($e->getMessage(), $storeCharset);
        $mail->setFrom($from_email, $from_name);
        $mail->addTo($to_email, $to_name);
        $mail->setSubject(date('Y-m-d') . ': Google base problem');
        try
        {
            $mail->send();
        }       
        catch(Exception $ex)
        {
            Mage::getSingleton('core/session')->addError('Cann\'t send the email. Try it later, please ...');
        }
       
        header('Content-Type: text/html; charset=' . $storeCharset);
        die($e->getMessage());
    }
    if (end($prodIds) < $reload_line)
    {
        // final feed generation time
        $totaltime         = round($feed_line_timer, 2); 
       
        // remove counter file
        @unlink(SAVE_FEED_RELOAD);
        @unlink(SAVE_FEED_TIMER);
       
        //---------------------- LOG THE SUCCESS   
        if (!file_exists($logDir))
        {
            mkdir($logDir, 0777);
        }
       
        if (!file_exists($logFile))
        {
            touch($logFile);
           
            $logHandle = fopen($logFile, 'w+');
           
            fwrite(              
                   $logHandle,
                   date('Y-m-d  H:i:s', filemtime ( SAVE_FEED_LOCATION ) ) . "  |  " . $gbaseFeed . "  |  " . count($prodIds) . " products exported  |  time: " . $totaltime . " seconds  |  size: " . format_bytes ( filesize ( SAVE_FEED_LOCATION ) ). "\n" .
                   "-------------------------------------------------------------------------------------------------------------------\n\n"
            );
           
            fclose($logHandle);        
        }
        else
        {
           
            $ini_handle     = fopen($logFile, "r");
            $ini_contents     = fread($ini_handle, filesize($logFile));
            fclose($ini_handle);
           
            $logHandle         = fopen($logFile, 'w+');
            fwrite(
                   $logHandle,
                   date('Y-m-d  H:i:s', filemtime ( SAVE_FEED_LOCATION ) ) . "  |  " . $gbaseFeed . "  |  " . count($prodIds) . " products exported  |  time: " . $totaltime . " seconds  |  size: " . format_bytes ( filesize ( SAVE_FEED_LOCATION ) ). "\n" .
                   "-------------------------------------------------------------------------------------------------------------------\n\n" .
                   $ini_contents
            );
            fclose($logHandle);
           
        }
       
        $log_handle     = fopen($logFile, "r");
        $log_contents     = fread($log_handle, filesize($logFile));
        fclose($log_handle);
       
        //---------------------- SEND THE LOG FILE TO ADMIN EVERY LAST DAY OF MONTH   
        if( date('d') == find_last_day(date('Y-m-d')) )
        {
           
            $mail = new Zend_Mail($storeCharset);
            $mail->setBodyText($log_contents, $storeCharset);
            $mail->setFrom($from_email, $from_name);
            $mail->addTo($to_email, $to_name);
            $mail->setSubject('Google base log from ' . date('m/Y') . ' period');
            try
            {
                $mail->send();
            }       
            catch(Exception $ex)
            {
                Mage::getSingleton('core/session')->addError('Cann\'t send the email. Try it later, please ...');
            }
           
        }
    }
    else
    {
        //---------------------- REFRESH SCRIPT TILL THE WHOLE FEED IS GENERATED
       
        curl_file_get_contents('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']);

        // possible refresh variants

        //---------------------- script runs by web browser
        // header( 'refresh: 1; url=' . $_SERVER['PHP_SELF'] );
        // header('Location: '. $_SERVER['PHP_SELF']);
        // header("Location: http://$_SERVER[SERVER_NAME]" . substr($_SERVER["PHP_SELF"], 0, strrpos($_SERVER["PHP_SELF"], "/")) . "/");
        // echo '<META http-equiv="refresh" content="1; URL=' . $_SERVER['PHP_SELF'] . '">';
       
        //---------------------- script runs by cron
        // file_get_contents('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']);
        // curl_header_refresh('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']);
        // curl_file_get_contents('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']);
       
    }
   
    function format_bytes($bytes, $precision = 2)
    {
        $units                 = array('B', 'KB', 'MB', 'GB', 'TB');
        $bytes                 = max($bytes, 0);
        $pow                 = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow                 = min($pow, count($units) - 1);
        $bytes                 /= pow(1024, $pow);
        return round($bytes, $precision) . ' ' . $units[$pow];
    }
   
    function find_last_day($anyDate)
    {
        //$anyDate            = '2009-08-25';                            // date format should be yyyy-mm-dd
        list($yr,$mn,$dt)    = split('-',$anyDate);                   
        $timeStamp            = mktime(0,0,0,$mn,1,$yr);               
        list($y,$m,$t)        = split('-',date('Y-m-t',$timeStamp));   
        $lastDayTimeStamp    = mktime(0,0,0,$m,$t,$y);               
        $lastDay            = date('d',$lastDayTimeStamp);           
        return $lastDay;
    }
   
    function curl_header_refresh($url)
    {
        $curl_init            = curl_init();
        curl_setopt($curl_init, CURLOPT_URL, $url);
        curl_setopt($curl_init, CURLOPT_HEADER, 0);
        $contents             = curl_exec($curl_init);
        curl_close($curl_init);
        return $contents;
    }
   
    function curl_file_get_contents($url)
    {
        $curl_init            = curl_init();                                            
        curl_setopt($curl_init, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_init, CURLOPT_URL, $url);
        $contents             = curl_exec($curl_init);
        curl_close($curl_init);
        return $contents;
    }
   
?>


The Link
http://todd.be/notes/exporting-importing-magento-product-options
http://www.magentocommerce.com/boards/viewthread/153230/#t227283

Wednesday, February 23, 2011

Magento FConnect or magento facebook connect

Hear is the link for magento fconnect or magento facebook connect works gr8
smile
http://inchoo.net/ecommerce/magento/facebook-connect-magento-extension/

Php File upload for ckeditor 3.X

its good
http://download.cksource.com/CKFinder/CKFinder%20for%20PHP/2.0.2/ckfinder_php_2.0.2.zip

Magento insert update edit CRUD operations for dummies and beginers


Todo module for dummies: from the horse’s mouth :)

Some information  before we stare at the code:

Magento Path: phtmlàBlockàHelper->IndexControlleràphtml(updated)
Module naming: Modulename/Packagename e.g Shiva/Todo

Important  Folder info:

Adminhtml:contains config for admin menus like edit, grid, form, tab etc...

Block:contains front end outputs i.e the actions like getPostAction, editAction, prepareLayout etc..

Controllers:for interacting with the modules 

eg. indexcontroller : the action associated with the form like createAction, editAction, deleteAction

Adminhtml/XXXController : action for the backend like save edit,delete, massdelete etc... where XXX is your package name, here Todo

ETC contains the config directory
            config.xml default setting for module
            system.xml admininistration settings and admin form option ofr modules
Helper: helpers for module, covering areas such as translation e.g create, delete, edit functions are here Data.php

Model
Mysql4: (The top ORM model directory)---database related activity
 
Sql:mysql4-install-0.1.0.php contains database tables information required

Creating folder structure
To start with creating a Todo application in magento we need to build a module that becomes a part of the site that has its own URL. We will be creating our own module that will run on \todo URL structure.
Create the following folders in local directory [app\code\local\]
/Shiva
            /Todo
                        /Block
                        /etc
                        /Helper
/Model
/sql
/controllers
In etc/modules create Shiva_Todo.xml
etc/modules
- Shiva_Todo.xml
Tell magento that the new module is here
<?xml version="1.0"?>
<config>
    <modules>
        <Shiva_Todo>
            <active>true</active>
            <codePool>local</codePool>
        </Shiva_Todo>
    </modules>
</config>

Clear the cache and check in site->admin->system->Configuration->Advanced

Check if the module is “Enabled”.

For the frontend part

Your todo form is located in your theme
Path:-app\design\frontend\base_new\default\template\Todo\todo.phtml

Check the code in file
To view the formpage in address bar, check the form name front end by going to : Shiva/Todo/etc/config.xml and check the <frontend> tag

The form will be displayed as ‘todo’ as the name given in < frontName> tag

Some more file info…..

Helper class:

\Shiva\Todo\Helper

Helper:helpers for module, covering areas such as translation e.g create, delete, edit functions are here Data.php

Create a php file named Data.php

That file has a helper class named Shiva_Todo_Helper_Data in [Shiva/Todo/Helper/Data.php]

Check the code.

If you come across the code [‘todo/index/create’] it simply means in the todo module it has an Index controller and Create action [module / controller / action].

Check the necessary functions to get the id and perform respective actions for create, edit and delete.
Block class:
\Shiva\Todo\Block

Block: In Todo.php the class extend the template in the class and define the post Url actions
Grid.php
Location: \Adminhtml\Todo\Grid.php->define the display gird functions here

Edit.php
Location : \Adminhtml\Todo\ -> define the edit functions here
……..

Controllers:

IndexController.php
Location : \Shiva\Todo\controllers -> defines the actions here which are defined in Block and triggered from helper class
Admin side:
TodoController.php
Location : Shiva\Todo\controllers\Adminhtmlà for the admin actions like edit save etc….
Frontend part:
feedback.xml
Location: app\design\adminhtml\base_new\default\layout\Todo.xml
feedback.phtml
app\design\frontend\base_new\default\template\Todo\Todo.phtml
Do not forget to create a table name ‘todo’ in database
Form actions…………
To  create a record :
The flow

Magento Path: phtml-->Block-->Helper->IndexController-->phtml(updated)

Todo Path: todo.phtml---(on submit)--->(Todo.php)Block---$id-->Data.php)Helper->(indexcontroller.php)IndexController---redirect-->phtml(updated
)

Check the code in todo.phtml,Todo.php,Data.php,Indexcontroller.php
The screen shots:












Develop your custom module from the scratch with this demo and learn Magento
Download the source code here
The code shared is purely for education purpose only
# If you find any misleading info then tell us else tell others.