Topic: Magento

Magento Create custom Database Table with Module 0

Magento Create custom Database Table with Module

Today, We want to share with you Magento Create custom Database Table.
In this post we will show you create Magento custom modules, hear for How to create table in a custom module in magento we will give you demo and example for implement.In this post, we will learn about Create a module with custom database table in Magento 2 with an example.

Magento Create custom Database Table with Module

There are the Following The simple About Magento Create custom Database Table with Module Full Information With Example and source code.here simple company = Namespace as well as = defines. Here I have step by step explained all The main files required module structure module with custom database table in Magento.

/app/code/local///

	Block/
	controllers/
	etc/
	Model/
	Mysql4/
	/
	sql/
	_setup/

Activate Stock_exchange

/app/etc/stock_exchanges/_.xml

<?xml version=“1.0”?>
<config>
<stock_exchanges>
<[company]_[Stock_exchange]>
<active>true</active>
<codePool>local</codePool>
</[company]_[Stock_exchange]>
</stock_exchanges>
</config>

Make Controller

/app/code/local///controllers/IndexController.php

<?php
class __IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
}
}

Make Configuration XML

Magento Create custom Database Table Config files

/app/code/local///etc/config.xml

<?xml version=“1.0”?>
<config>
<stock_exchanges>
<[company]_[Stock_exchange]>
<version>0.1.0</version>
</[company]_[Stock_exchange]>
</stock_exchanges>
<frontend>
<routers>
<[stock_exchange]>
<use>standard</use>
<args>
<stock_exchange>[company]_[Stock_exchange]</stock_exchange>
<frontName>[stock_exchange]</frontName>
</args>
</[stock_exchange]>
</routers>
<layout>
<updates>
<[stock_exchange]>
<file>[stock_exchange].xml</file>
</[stock_exchange]>
</updates>
</layout>
</frontend>
<global>
<models>
<[stock_exchange]>
<class>[company]_[Stock_exchange]_Model</class>
<resourceModel>[stock_exchange]_mysql4</resourceModel>
</[stock_exchange]>
<[stock_exchange]_mysql4>
<class>[company]_[Stock_exchange]_Model_Mysql4</class>
<entities>
<[stock_exchange]>
<table>[stock_exchange]</table>
</[stock_exchange]>
</entities>
</[stock_exchange]_mysql4>
</models>
<resources>
<[stock_exchange]_setup>
<setup>
<stock_exchange>[company]_[Stock_exchange]</stock_exchange>
</setup>
<connection>
<use>core_setup</use>
</connection>
</[stock_exchange]_setup>
<[stock_exchange]_write>
<connection>
<use>core_write</use>
</connection>
</[stock_exchange]_write>
<[stock_exchange]_read>
<connection>
<use>core_read</use>
</connection>
</[stock_exchange]_read>
</resources>
<blocks>
<[stock_exchange]>
<class>[company]_[Stock_exchange]_Block</class>
</[stock_exchange]>
</blocks>
<helpers>
<[stock_exchange]>
<class>[company]_[Stock_exchange]_Helper</class>
</[stock_exchange]>
</helpers>
</global>
</config>

Make Helper

/app/code/local///Helper/Data.php

<?php
class __Helper_Data extends Mage_Core_Helper_Abstract
{
}

Make Models

/app/code/local///Model/.php

<?php
class <company>_<Stock_exchange>_Model_<Stock_exchange> extends Mage_Core_Model_Abstract
{
public function _construct()
{
parent::_construct();
$this->_init(‘<stock_exchange>/<stock_exchange>’);

/app/code/local///Model/Mysql4/.php

<?php
class <company>_<Stock_exchange>_Model_Mysql4_<Stock_exchange> extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init(‘<stock_exchange>/<stock_exchange>’, ‘<stock_exchange>_id’);
}
}

/app/code/local///Model/Mysql4//Collection.php

<?php
class <company>_<Stock_exchange>_Model_Mysql4_<Stock_exchange>_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
public function _construct()
{
//parent::__construct();
$this->_init(‘<stock_exchange>/<stock_exchange>’);
}
}

Magento Create custom Database Table Tutorials

SQL Setup

/app/code/local///sql/_setup/mysql4-install-0.1.0.php

simple Magento – Create Custom Module with Custom Database Table Step by step

<?php
$installer = $this;
$installer->startSetup();
$installer->run(“
— DROP TABLE IF EXISTS {$this->getTable(‘<stock_exchange>’)};
CREATE TABLE {$this->getTable(‘<stock_exchange>’)} (
`<stock_exchange>_id` int(11) unsigned NOT NULL auto_increment,
`title` varchar(255) NOT NULL default ”,
`content` text NOT NULL default ”,
`status` smallint(6) NOT NULL default ‘0’,
`created_time` datetime NULL,
`update_time` datetime NULL,
PRIMARY KEY (`<stock_exchange>_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
“);
$installer->endSetup();

Template Design

/app/design/frontend///layout/.xml

/layout/.xml

<?xml version=“1.0”?>
<layout version=“0.1.0”>
<[stock_exchange]_index_index>
<reference name=“content”>
<block type=“[stock_exchange]/[stock_exchange]” name=“[stock_exchange]” />
</reference>
</[stock_exchange]_index_index>
</layout>

/app/design/frontend///layout/.xml

<?xml version=“1.0”?>
<layout version=“0.1.0”>
<[stock_exchange]_index_index>
<reference name=“content”>
<block type=“core/template” name=“[stock_exchange]” template=“[stock_exchange]/[stock_exchange].phtml” />
</reference>
</[stock_exchange]_index_index>
</layout>

/app/design/frontend///template//.phtml

<h4><?php echo $this->__(‘Stock_exchange List’) ?></h4>
<?php
/*
$infoStock = Mage::getModel(‘<stock_exchange>/<stock_exchange>’)->load(1);
echo $infoStock->get<Stock_exchange>Id();
echo $infoStock->getTitle();
echo $infoStock->getContent();
echo $infoStock->getStatus();
*/

/*
$i = 0;
$datacollect = Mage::getModel(‘<stock_exchange>/<stock_exchange>’)->getCollection();
$datacollect->setPageSize(5);
$datacollect->setCurPage(2);
$size = $datacollect->getSize();
$cnt = count($datacollect);
foreach ($datacollect as $item) {
$i = $i+1;
$item->setTitle($i);
echo $item->getTitle();
}
$datacollect->walk(‘save’);
*/

/*
$dataObj = Mage::getModel(‘<stock_exchange>/<stock_exchange>’)->load(1);
$dataObj->setTitle(‘Welcome To Pakainfo.com’);
$dataObj->save();
*/

Directory Additions

/app/code/local///

	Block/
	Adminhtml/
	/
	Edit/
	Tab/
	controllers/
	Adminhtml/
	etc/
	Helper/
	Model/
	Mysql4/
	/
	sql/
	_setup/

Blocks

/app/code/local///Block/Adminhtml/.php

<?php
class <company>_<Stock_exchange>_Block_Adminhtml_<Stock_exchange> extends Mage_Adminhtml_Block_Widget_Grid_Container
{
public function __construct()
{
$this->_controller = ‘adminhtml_<stock_exchange>’;
$this->_blockGroup = ‘<stock_exchange>’;
$this->_headerText = Mage::helper(‘<stock_exchange>’)->__(‘Product Manager’);
$this->_addButtonLabel = Mage::helper(‘<stock_exchange>’)->__(‘Add Item’);
parent::__construct();
}
}

/app/code/local///Block/Adminhtml//Edit.php

<?php
class <company>_<Stock_exchange>_Block_Adminhtml_<Stock_exchange>_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
parent::__construct();
$this->_objectId = ‘id’;
$this->_blockGroup = ‘<stock_exchange>’;
$this->_controller = ‘adminhtml_<stock_exchange>’;
$this->_updateButton(‘save’, ‘label’, Mage::helper(‘<stock_exchange>’)->__(‘Save Item’));
$this->_updateButton(‘delete’, ‘label’, Mage::helper(‘<stock_exchange>’)->__(‘Delete Item’));
}
public function getHeaderText()
{
if( Mage::registry(‘<stock_exchange>_data’) && Mage::registry(‘<stock_exchange>_data’)->getId() ) {
return Mage::helper(‘<stock_exchange>’)->__(“Edit Item ‘%s'”, $this->htmlEscape(Mage::registry(‘<stock_exchange>_data’)->getTitle()));
} else {
return Mage::helper(‘<stock_exchange>’)->__(‘Add Item’);
}
}
}

/app/code/local///Block/Adminhtml//Grid.php

<?php
class <company>_<Stock_exchange>_Block_Adminhtml_<Stock_exchange>_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId(‘<stock_exchange>Grid’);
// This is the primary key of the database
$this->setDefaultSort(‘<stock_exchange>_id’);
$this->setDefaultDir(‘ASC’);
$this->setSaveParametersInSession(true);
}
protected function _prepareCollection()
{
$datacollect = Mage::getModel(‘<stock_exchange>/<stock_exchange>’)->getCollection();
$this->setCollection($datacollect);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn(‘<stock_exchange>_id’, array(
‘header’ => Mage::helper(‘<stock_exchange>’)->__(‘ID’),
‘align’ =>‘right’,
‘width’ => ’50px’,
‘index’ => ‘<stock_exchange>_id’,
));
$this->addColumn(‘title’, array(
‘header’ => Mage::helper(‘<stock_exchange>’)->__(‘Title’),
‘align’ =>‘left’,
‘index’ => ‘title’,
));
/*
$this->addColumn(‘content’, array(
‘header’ => Mage::helper(‘<stock_exchange>’)->__(‘Product Content’),
‘width’ => ‘150px’,
‘index’ => ‘content’,
));
*/
$this->addColumn(‘created_time’, array(
‘header’ => Mage::helper(‘<stock_exchange>’)->__(‘Creation Time’),
‘align’ => ‘left’,
‘width’ => ‘120px’,
‘type’ => ‘date’,
‘default’ => ‘–‘,
‘index’ => ‘created_time’,
));
$this->addColumn(‘update_time’, array(
‘header’ => Mage::helper(‘<stock_exchange>’)->__(‘Update Time’),
‘align’ => ‘left’,
‘width’ => ‘120px’,
‘type’ => ‘date’,
‘default’ => ‘–‘,
‘index’ => ‘update_time’,
));
$this->addColumn(‘status’, array(
‘header’ => Mage::helper(‘<stock_exchange>’)->__(‘Status’),
‘align’ => ‘left’,
‘width’ => ’80px’,
‘index’ => ‘status’,
‘type’ => ‘options’,
‘options’ => array(
1 => ‘Active’,
0 => ‘Inactive’,
),
));
return parent::_prepareColumns();
}
public function getRowUrl($row)
{
return $this->getUrl(‘*/*/edit’, array(‘id’ => $row->getId()));
}
}

/app/code/local///Block/Adminhtml//Edit/Form.php

<?php
class <company>_<Stock_exchange>_Block_Adminhtml_<Stock_exchange>_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset(‘<stock_exchange>_form’, array(‘legend’=>Mage::helper(‘<stock_exchange>’)->__(‘Product information’)));
$fieldset->addField(‘title’, ‘text’, array(
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Title’),
‘class’ => ‘required-entry’,
‘required’ => true,
‘name’ => ‘title’,
));
$fieldset->addField(‘status’, ‘select’, array(
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Status’),
‘name’ => ‘status’,
‘values’ => array(
array(
‘value’ => 1,
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Active’),
),
array(
‘value’ => 0,
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Inactive’),
),
),
));
$fieldset->addField(‘content’, ‘editor’, array(
‘name’ => ‘content’,
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Content’),
‘title’ => Mage::helper(‘<stock_exchange>’)->__(‘Content’),
‘style’ => ‘width:98%; height:400px;’,
‘wysiwyg’ => false,
‘required’ => true,
));
if ( Mage::getSingleton(‘adminhtml/session’)->get<Stock_exchange>Data() )
{
$form->setValues(Mage::getSingleton(‘adminhtml/session’)->get<Stock_exchange>Data());
Mage::getSingleton(‘adminhtml/session’)->set<Stock_exchange>Data(null);
} elseif ( Mage::registry(‘<stock_exchange>_data’) ) {
$form->setValues(Mage::registry(‘<stock_exchange>_data’)->getData());
}
return parent::_prepareForm();
}
}

/app/code/local///Block/Adminhtml//Edit/Tabs.php

<?php
class <company>_<Stock_exchange>_Block_Adminhtml_<Stock_exchange>_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
parent::__construct();
$this->setId(‘<stock_exchange>_tabs’);
$this->setDestElementId(‘edit_form’);
$this->setTitle(Mage::helper(‘<stock_exchange>’)->__(‘News Information’));
}
protected function _beforeToHtml()
{
$this->addTab(‘form_section’, array(
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Product Information’),
‘title’ => Mage::helper(‘<stock_exchange>’)->__(‘Product Information’),
‘content’ => $this->getLayout()->createBlock(‘<stock_exchange>/adminhtml_<stock_exchange>_edit_tab_form’)->toHtml(),
));
return parent::_beforeToHtml();
}
}

/app/code/local///Block/Adminhtml//Edit/Tab/Form.php

<?php
class <company>_<Stock_exchange>_Block_Adminhtml_<Stock_exchange>_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset(‘<stock_exchange>_form’, array(‘legend’=>Mage::helper(‘<stock_exchange>’)->__(‘Product information’)));
$fieldset->addField(‘title’, ‘text’, array(
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Title’),
‘class’ => ‘required-entry’,
‘required’ => true,
‘name’ => ‘title’,
));
$fieldset->addField(‘status’, ‘select’, array(
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Status’),
‘name’ => ‘status’,
‘values’ => array(
array(
‘value’ => 1,
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Active’),
),
array(
‘value’ => 0,
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Inactive’),
),
),
));
$fieldset->addField(‘content’, ‘editor’, array(
‘name’ => ‘content’,
‘label’ => Mage::helper(‘<stock_exchange>’)->__(‘Content’),
‘title’ => Mage::helper(‘<stock_exchange>’)->__(‘Content’),
‘style’ => ‘width:98%; height:400px;’,
‘wysiwyg’ => false,
‘required’ => true,
));
if ( Mage::getSingleton(‘adminhtml/session’)->get<Stock_exchange>Data() )
{
$form->setValues(Mage::getSingleton(‘adminhtml/session’)->get<Stock_exchange>Data());
Mage::getSingleton(‘adminhtml/session’)->set<Stock_exchange>Data(null);
} elseif ( Mage::registry(‘<stock_exchange>_data’) ) {
$form->setValues(Mage::registry(‘<stock_exchange>_data’)->getData());
}
return parent::_prepareForm();
}
}

Controller

simple Magento controller for Magento Create custom Database Table.

/app/code/local///controllers/Adminhtml/Controller.php

<?php
class <company>_<Stock_exchange>_Adminhtml_<Stock_exchange>Controller extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
$this->loadLayout()
->_setActiveMenu(‘<stock_exchange>/items’)
->_addBreadcrumb(Mage::helper(‘adminhtml’)->__(‘Items Manager’), Mage::helper(‘adminhtml’)->__(‘Product Manager’));
return $this;
}
public function indexAction() {
$this->_initAction();
$this->_addContent($this->getLayout()->createBlock(‘<stock_exchange>/adminhtml_<stock_exchange>’));
$this->renderLayout();
}
public function editAction()
{
$<stock_exchange>Id = $this->getRequest()->getParam(‘id’);
$<stock_exchange>Model = Mage::getModel(‘<stock_exchange>/<stock_exchange>’)->load($<stock_exchange>Id);
if ($<stock_exchange>Model->getId() || $<stock_exchange>Id == 0) {
Mage::register(‘<stock_exchange>_data’, $<stock_exchange>Model);
$this->loadLayout();
$this->_setActiveMenu(‘<stock_exchange>/items’);
$this->_addBreadcrumb(Mage::helper(‘adminhtml’)->__(‘Product Manager’), Mage::helper(‘adminhtml’)->__(‘Product Manager’));
$this->_addBreadcrumb(Mage::helper(‘adminhtml’)->__(‘Product News’), Mage::helper(‘adminhtml’)->__(‘Product News’));
$this->getLayout()->getBlock(‘head’)->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock(‘<stock_exchange>/adminhtml_<stock_exchange>_edit’))
->_addLeft($this->getLayout()->createBlock(‘<stock_exchange>/adminhtml_<stock_exchange>_edit_tabs’));
$this->renderLayout();
} else {
Mage::getSingleton(‘adminhtml/session’)->addError(Mage::helper(‘<stock_exchange>’)->__(‘Product does not exist’));
$this->_redirect(‘*/*/’);
}
}
public function newAction()
{
$this->_forward(‘edit’);
}
public function saveAction()
{
if ( $this->getRequest()->getPost() ) {
try {
$postData = $this->getRequest()->getPost();
$<stock_exchange>Model = Mage::getModel(‘<stock_exchange>/<stock_exchange>’);
$<stock_exchange>Model->setId($this->getRequest()->getParam(‘id’))
->setTitle($postData[‘title’])
->setContent($postData[‘content’])
->setStatus($postData[‘status’])
->save();
Mage::getSingleton(‘adminhtml/session’)->addSuccess(Mage::helper(‘adminhtml’)->__(‘Product was successfully saved’));
Mage::getSingleton(‘adminhtml/session’)->set<Stock_exchange>Data(false);
$this->_redirect(‘*/*/’);
return;
} catch (Exception $e) {
Mage::getSingleton(‘adminhtml/session’)->addError($e->getMessage());
Mage::getSingleton(‘adminhtml/session’)->set<Stock_exchange>Data($this->getRequest()->getPost());
$this->_redirect(‘*/*/edit’, array(‘id’ => $this->getRequest()->getParam(‘id’)));
return;
}
}
$this->_redirect(‘*/*/’);
}
public function deleteAction()
{
if( $this->getRequest()->getParam(‘id’) > 0 ) {
try {
$<stock_exchange>Model = Mage::getModel(‘<stock_exchange>/<stock_exchange>’);
$<stock_exchange>Model->setId($this->getRequest()->getParam(‘id’))
->delete();
Mage::getSingleton(‘adminhtml/session’)->addSuccess(Mage::helper(‘adminhtml’)->__(‘Product was successfully deleted’));
$this->_redirect(‘*/*/’);
} catch (Exception $e) {
Mage::getSingleton(‘adminhtml/session’)->addError($e->getMessage());
$this->_redirect(‘*/*/edit’, array(‘id’ => $this->getRequest()->getParam(‘id’)));
}
}
$this->_redirect(‘*/*/’);
}

public function gridAction()
{
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock(‘importedit/adminhtml_<stock_exchange>_grid’)->toHtml()
);
}
}

XML Configuration Changes

/app/code/local///etc/config.xml

<?xml version=“1.0”?>
<config>
<stock_exchanges>
<[company]_[Stock_exchange]>
<version>0.1.0</version>
</[company]_[Stock_exchange]>
</stock_exchanges>
<frontend>
<routers>
<[stock_exchange]>
<use>standard</use>
<args>
<stock_exchange>[company]_[Stock_exchange]</stock_exchange>
<frontName>[stock_exchange]</frontName>
</args>
</[stock_exchange]>
</routers>
<layout>
<updates>
<[stock_exchange]>
<file>[stock_exchange].xml</file>
</[stock_exchange]>
</updates>
</layout>
</frontend>
<admin>
<routers>
<[stock_exchange]>
<use>admin</use>
<args>
<stock_exchange>[company]_[Stock_exchange]</stock_exchange>
<frontName>[stock_exchange]</frontName>
</args>
</[stock_exchange]>
</routers>
</admin>
<adminhtml>
<menu>
<[stock_exchange] stock_exchange=“[stock_exchange]”>
<title>Magento Create custom Database Table -[Stock_exchange]</title>
<sort_order>71</sort_order>
<children>
<items stock_exchange=“[stock_exchange]”>
<title>Manage Items</title>
<sort_order>0</sort_order>
<action>[stock_exchange]/adminhtml_[stock_exchange]</action>
</items>
</children>
</[stock_exchange]>
</menu>
<acl>
<resources>
<all>
<title>Allow Everything</title>
</all>
<admin>
<children>
<[stock_exchange]>
<title>[Stock_exchange] Stock_exchange</title>
<sort_order>200</sort_order>
</[stock_exchange]>
</children>
</admin>
</resources>
</acl>
<layout>
<updates>
<[stock_exchange]>
<file>[stock_exchange].xml</file>
</[stock_exchange]>
</updates>
</layout>
</adminhtml>
<global>
<models>
<[stock_exchange]>
<class>[company]_[Stock_exchange]_Model</class>
<resourceModel>[stock_exchange]_mysql4</resourceModel>
</[stock_exchange]>
<[stock_exchange]_mysql4>
<class>[company]_[Stock_exchange]_Model_Mysql4</class>
<entities>
<[stock_exchange]>
<table>[stock_exchange]</table>
</[stock_exchange]>
</entities>
</[stock_exchange]_mysql4>
</models>
<resources>
<[stock_exchange]_setup>
<setup>
<stock_exchange>[company]_[Stock_exchange]</stock_exchange>
</setup>
<connection>
<use>core_setup</use>
</connection>
</[stock_exchange]_setup>
<[stock_exchange]_write>
<connection>
<use>core_write</use>
</connection>
</[stock_exchange]_write>
<[stock_exchange]_read>
<connection>
<use>core_read</use>
</connection>
</[stock_exchange]_read>
</resources>
<blocks>
<[stock_exchange]>
<class>[company]_[Stock_exchange]_Block</class>
</[stock_exchange]>
</blocks>
<helpers>
<[stock_exchange]>
<class>[company]_[Stock_exchange]_Helper</class>
</[stock_exchange]>
</helpers>
</global>
</config>

XML Layout

/app/design/adminhtml///layout/.xml

Last step for the Magento Create custom Database with Table full Source code.

<?xml version=“1.0”?>
<layout version=“0.1.0”>
<[stock_exchange]_adminhtml_[stock_exchange]_index>
<reference name=“content”>
<block type=“[stock_exchange]/adminhtml_[stock_exchange]” name=“[stock_exchange]” />
</reference>
</[stock_exchange]_adminhtml_[stock_exchange]_index>
</layout>

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Magento – Create Custom Module with Custom Database Table.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

How to Open URL in New Tab using Magento 0

How to Open URL in New Tab using Magento

Today, We want to share with you How to Open URL in New Tab using Magento.
In this post we will show you magento redirect with parameters, hear for magento redirect url in phtml we will give you demo and example for implement.In this post, we will learn about Magento Controllers in redirect with an example.

My Paka Knowledgeable Ideas, Tips and Tricks, Useful Content, Jobs, Technology, Earn Money, gmail creation, skype, yahoo and more useful things.

In Magento, Open new window when target=”_blank”

<Link to="/about" target="_blank">About Pakainfo.com</Link>

Magento Overview with Features

There are the Following the List of Features For Magento Pure PHP Latest Frameworks for Magento Product page open in new tab Target Blank.

  • Customer groups
  • Free shipping options
  • Landing page for categories
  • Minimum Advertised Price (MAP)
  • Multi-tier pricing for quantity discounts
  • New items promotional tool
  • Newsletter management
  • Persistent shopping cart
  • Polls
  • Product bundles
  • Recently viewed
  • Send wish lists by email
  • compared products

Magento redirect to a new tab

//custom theme
app/design/frontend/{your_namespace}/{your_theme_name}/template/catalog/product/list.phtml

//find the line
<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">

//changes custom
<a target="_blank" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">

Magento Redirects

Create URL redirect in Magento backend

1-> first of all Go to The Catalog > URL Rewrite Management

2-> Click Add URL Rewrite.

3-> Create URL rewrite for any products, any type of the categories, and more custom URLs here select dropdown list

4-> and Last URL Rewrite Information field will display up for We to simple fill in.

Magento Redirecting To External Domains

<img src"https://pakainfo.com/jaydeep_gondaliya.jpg" onclick="window.location.href='https://pakainfo.com/';"/>

Magento Controllers To Redirecting into External URLs

<?php $this->_redirect($path)

//insted of
//magento 2 redirect

<?php $this->_redirectUrl($url)

jQuery 15 Powerful Tips and Tricks for Developers and Web Designer

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about magento 2 redirect from observer.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Access Control Allow Origin http set Headers 0

Access Control Allow Origin http set Headers

Access Control Allow Origin http set Headers

Simple Include headers Uing CORS solution (Cross-origin resource sharing)

Welcome to the In Pakainfo.com website! You will Step By Step learn web programming, easy and very fun. This website allmost provides you with a complete web programming tutorial presented in an easy-to-follow manner. Each web programming tutorial has all the practical examples with web programming script and screenshots available.For Access Control Allow Origin http set Headers

Access-Control-Allow-Origin – Name of the each domain allowed access control all for cross domain requests. * (* means all domain allowed)indicates all domains are allowed.
Access-Control-Allow-Methods – List of (GET, PUT, POST, DELETE, OPTIONS)HTTP methods can be used here domains during request.
Access-Control-Allow-Headers – List of (GET, PUT, POST, DELETE, OPTIONS)HTTP headers can be used here domains during request.

In PHP : “no ‘access-control-allow-origin’ header is present on the requested resource web api”

The Soltution of the no ‘access-control-allow-origin’ header is present on the requested resource web api in PHP.

// here include this three statement
header('Access-Control-Allow-Origin: *');  //all the methods access code
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); // all the resource and request get
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

simple Below the sample code which handles Cross Domain AJAX POST requests: post.php

CORS works fine in all the latest browsers, but IE8 and IE9 don’t support this.

In order to use XDomainRequest in IE, request must be:
a). Only GET or POST
When Posting, the data will always be sent with a Content-Type of text/plain
b). Only HTTP or HTTPS
Protocol must be the same scheme as the calling page
c). Always asynchronous

Step 1). Add the script in

<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest.min.js"></script>

Step 2). You need to set contentType value text/plain in $.ajax request.

 var contentType ="application/x-www-form-urlencoded; charset=utf-8";
 
if(window.XDomainRequest) //for IE8,IE9
    contentType = "text/plain";
 
$.ajax({
     url:"https://pakainfo.com/php/post.php",
     data:"name=king&age=28",
     type:"POST",
     dataType:"json",   
     contentType:contentType,    
     success:function(result)
     {
        alert("here Display all the Data from Server"+JSON.stringify(result));
     },
     error:function(jqXHR,textStatus,errorThrown)
     {
        alert("Error display :You can not any data send Cross Domain AJAX simple requests: "+errorThrown);
     }
    });
	

Below is the sample code, works in all the browsers.

<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="jquery.min.js"></script>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest.min.js"></script>

</head>
<body>
 
<input id="get_methoddata" type="button"  value="Data Send X  -> Method GET"/>
<input id="post_methoddata" type="button" value="Data Send X -> Method POST" />
 
<script>
$(document).ready(function()
{
    var data_contentType ="application/x-www-form-urlencoded; charset=utf-8";
 
    if(window.XDomainRequest)
        data_contentType = "text/plain";
 
    $("#post_methoddata").click(function()
    {
        $.ajax({
         url:"https://pakainfo.com/php/post.php",
         data:"name=johan&age=28",
         type:"POST",
         dataType:"json",   
         contentType:data_contentType,    
         success:function(result)
         {
            alert("here Display all the Data from Server"+JSON.stringify(result));
         },
         error:function(jqXHR,textStatus,errorThrown)
         {
            alert("Error display :You can not any data send Cross Domain AJAX simple requests: "+errorThrown);
         }
        });
 
    });
 
    $("#get_methoddata").click(function()
    {
        $.ajax(
        {
         url:"https://pakainfo.com/php/get.php?name=johan&age=48",
         dataType:"json",
         contentType:contentType,
         success:function(result)
         {
            alert("all the Data from here display Server"+JSON.stringify(result));
         },
         error:function(jqXHR,textStatus,errorThrown)
         {
             alert("Error display :You can not any data send Cross Domain AJAX simple requests: "+errorThrown);
         }
        });
 
    });
 
});
</script>
</body>
</html>

post.php source code:

<?php
// here include this two statement
header('Access-Control-Allow-Origin: *'); 
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
 
 //check condition headers set or not
if(isset($HTTP_RAW_POST_DATA)) {
  parse_str($HTTP_RAW_POST_DATA,$arr); 
  $arr['data_extra']='task 1.your request POST Request from Pakainfo.com';
  echo json_encode($arr);
}
else
{
    $_POST['data_extra']='task 2.your request POST Request from Pakainfo.com';
    echo json_encode($_POST);
}
?>

Example

header set access-control-allow-origin multiple domains | cross domain ajax request,cross domain ajax request jquery | no access control allow origin header is present jquery ajax origin

Set Cookies Get Cookies Delete Cookies with PHP 0

Set Cookies Get Cookies Delete Cookies with PHP

Set Cookies Get Cookies Delete Cookies with PHP

In this Post We Will Explain About is Set Cookies Get Cookies Delete Cookies with PHP With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Set Cookies Get Cookies Delete Cookies with PHPExample

In this post we will show you Best way to implement How to Set, Get and Delete Cookies in PHP, hear for Set, get and delete data from cookie in PHPwith Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Uses of cookies

There are the following the list of Uses of Cookies
Store user simple preferences (Like as a color and font size and HTML element size and theme etc.)
Track simple progress (Like as a page number and percentage, etc.)
Store simple username or any numbers (to simple identify more user)

Set Cookie using PHP

$cooke_data_val = 'Chrome'; //simple variable
setcookie("mycokname", $cooke_data_val, time()+3600); //cookie name, value & time (1 hour)

setcookie(NAME, VALUE, EXPIRE, PATH, DOMAIN, SECURE, HTTPONLY)

$cooke_data_val = 'Chrome'; //simple variable
setcookie("mycokname", $cooke_data_val, time()+3600, '/', 'sanwebe.com', true, true);

Retrieve Cookie Value using PHP

echo 'Pakainfo.com - Your mycokname is ' . $_COOKIE['mycokname'];

if(isset($_COOKIE['mycokname'])) //check cookie exist
{
    echo 'Your mycokname is ' . $_COOKIE['mycokname'];
}

$cookie_value =  (isset($_COOKIE['mycokname']))? $_COOKIE['mycokname'] :'no cookie';
echo $cookie_value ;

Delete a Cookie using PHP

setcookie("mycokname", "", time()-3600); //expiration simple time set to latest one hour ago

Example

I hope you have Got What is How to Create, Read, Update and Delete a Cookie with PHP And how it works.I would Like to have FeadBack From My Blog(Pakainfo.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(Pakainfo.com) Are Most Always Welcome.

Magento2 Get Logged in Customer Data using Email 0

Magento2 Get Logged in Customer Data using Email

Magento2 Get Logged in Customer Data using Email

In this Post We Will Explain About is Magento2 Get Logged in Customer Data using Email With Example and Demo.

Welcome on Pakainfo.com – Examples ,The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Get Customer detail in magento2

In this post we will show you Best way to implement How to get Customer collection in magento2, hear for How to magento 2.0 – Get customer data from id – magento2 with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

How to get customer data from email id in magento 2

For Get Magento 2 Get Customer Details using Email Id

There are the Following the Two step include to get Magento 2 Get Customer all Details
Step 1 : If you have simple email id of customer and you need to get all the details of customer
Step 2 : This source code will return all the customer object details and fill detail

$mage_query_boot = Bootstrap::create(BP, $_SERVER);
$object_manager = $mage_query_boot->getObjectManager();
 
// add ustomer email
$set_cust_email = "[email protected]";
// echo $set_cust_email;
 
// Get simple object manager using magento 2 
$object_manager = \Magento\Framework\App\ObjectManager::getInstance();
 
 
$mage_url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $mage_url->get('\Magento\Store\Model\StoreManagerInterface');
$state_val = $object_manager->get('\Magento\Framework\App\State');
$state_val->setAreaCode('frontend');
 
//Pakainfo.com to Get website id
$get_web_id = $storeManager->getWebsite()->getWebsiteId();
 
$store = $storeManager->getStore();
// Get Store ID
$store_id = $store->getStoreId();
 
$customer_factory = $object_manager->get('\Magento\Customer\Model\CustomerFactory');
$all_cust_data = $customer_factory->create();
 
$all_cust_data->setWebsiteId($get_web_id);
$all_cust_data->loadByEmail($set_cust_email);
// load simple customer by email address
// pront simple customer basic id 
// simple step sto Magento 2 Get Customer name
echo $all_cust_data->getFirstname();
echo $all_cust_data->getLastname();
echo $all_cust_data->getEmail();
 
 
//$all_cust_data->load('1');
 
// load customer by email address
$data = $all_cust_data->getData();
 
$customer_id = $data['entity_id'];

echo "Check Here print to all the data display";
echo "<pre>";
print_r($data);
echo "</pre>";

Example

I hope you have Got Get all the customer details by email id In Magento And how it works.I would Like to have FeadBack From My Blog(Pakainfo.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(Pakainfo.com) Are Most Always Welcome.

Magento 2 How to solve one or more indexers with Reindexing using Command 0

Magento 2 How to solve one or more indexers with Reindexing using Command

Magento 2 How to solve one or more indexers with Reindexing using Command

In this Post We Will Explain About is Magento 2 How to solve one or more indexers with Reindexing using Command With Example and Demo.

Welcome on Pakainfo.com – Examples ,The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Magento 2 – How to solve one or more indexers are invalid by command line

In this post we will show you Best way to implement System messages One or more indexers are invalid, hear for How to How to fix one or more indexers are invalid error in Magento with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Magento 2 – System messages One or more indexers are invalid

Error: Magento 2 Reindexing One or More simple Indexes are Invalid Make simple Sure Your Magento need to Cron Job is Running
When we were starting to work on my simple magento project from steb by step to scratch, we installed successfully but when we added two or three or more Items but it were not displaying on static homepage or main sidebar menu category page. I though what will be same issue. after search we simple found it were issue large data because we require simple to reindex of Items. I again some found how to your page reindex, we though it simple re-index from magento admin panel, but we couldn’t any data find any option display to the main page in admin panel.

At Last we found we can solve “simple one or more indexers pages are invalid solved” some error from command line using cmd, we open my terminal cmd and go on root cd.. to get your directory. We run bellow php command on my root simple directory.

Re-index Command

php bin/magento indexer:reindex

and then fire above command all the Items reindex and we get Items on some category detail page and also solve one issue from admin panel.means one or more indexers are invalid.solution of the make sure your magento cron job is running windows

I hope This command can help you…

magento 2 reindex programmatically – Reindex Data

1) Login Magento to your admin panel as Administrator.
2) Pathr to Navigate to System > Index Management.

Example

I hope you have Got Magento 2 – How to solve one or more indexers are invalid by command line And how it works.I would Like to have FeadBack From My Blog(Pakainfo.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(Pakainfo.com) Are Most Always Welcome.

PHP extension “soap” must be loaded error in Magento xampp 0

PHP extension "soap" must be loaded error in Magento xampp

PHP extension “soap” must be loaded error in Magento xampp

In this Post We Will Explain About is PHP extension “soap” must be loaded error in Magento xampp With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to php extension soap must be loaded magento xamppExample

In this post we will show you Best way to implement php extension soap must be loaded error in Magento xampp, hear for PHP extension “soap” must be loaded to install Magentowith Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Magento install to simple error generated Like as a Error : PHP extension soap must be loaded in magento

Simply go steps to in php.ini file and simple changes Find this source code ;extension=php_soap.dll remove terminate sign like as a do it extension=php_soap.dll

magento . PHP extension “soap” must be loaded

Open your xampp server Or
I solved the problem simple way to by editing:

xampp\php\php.ini 

And then changing some comment this line from:

;extension=php_soap.dll 

simple to:

extension=php_soap.dll

And then restart the xampp serever.

PHP extension “curl” must be loaded.

If your any server does not have simple curl installed on it we can type simple one of the following some commands to install it:

sudo apt-get install php5-curl
sudo /etc/init.d/apache2 restart

Magento PHP extension “soap” must be loaded

Simply go and open to in php.ini simple xampp serevere file and Find this code ;extension=php_soap.dll comments remove terminate simple sign like do it changes like as a extension=php_soap.dll files.

$ php -i | grep -i soap

to simple ensure that it is simple the PHP like as a extension that is missing.

Example

I hope you have Got What is php extension soap must be loaded magento xampp And how it works.I would Like to have FeadBack From My Blog(Pakainfo.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(Pakainfo.com) Are Most Always Welcome.

WordPress Security Tricks to Secure WordPress Website 0

WordPress Security Tricks to Secure WordPress Website

WordPress Security Tricks to Secure WordPress Website

In this Post We Will Explain About is WordPress Security Tricks to Secure WordPress Website With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to WordPress Security Tutorial – How to Secure WordPress Example

In this post we will show you Best way to implement How To Secure Your WordPress Website , hear for The Ultimate WordPress Security Guide – Step by Stepwith Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

How to make Secure WordPress Site

Today Manyof the case as well as lots of wordpress some secure websites are developed and any person hacked due to lack of some security.

To Your secure wordpress website or blog follow the some given steps.

There are the following list of the make wordpress website secure

  • need to everyday see up-to-date wordpress
  • need to everyday see All the plugins and themes up-to-date
  • Don’t see any “admin”, or ”administrator”,as well as website name as username.
  • Don’t see password simple as like as a 1234,123456 etc.here need to everyday see password strong.
  • create proper file your permissions.
  • Disable all the file editing from php admin side.put the below code to wp-config.php
  • define(‘DISALLOW_FILE_EDIT’, true);
  • and then Use security plugins like as a iThemes Security and then All in One WP Security use this plugins.
  • need to everyday see your backup of your important files and MYSQL database.
  • Every day Monitor logs
  • wp-config.php

    You can simple easily do this by adding the some following sourcecode in your wp-config.php this file.

    // Disallow file edit
    define( 'DISALLOW_FILE_EDIT', true );
    

    Limit Login Attempts,
    Change WordPress Database Prefix,
    Password Protect WordPress Admin and Login Page,
    Disable Directory Indexing and Browsing,
    Disable XML-RPC in WordPress,
    Automatically log out Idle Users in WordPress,
    Add some Security Questions Login time to WordPress Login Screen,
    Keeping WordPress Updated,
    Strong Passwords and User Permissions,
    The Role of WordPress Hosting
    Best WordPress Security Plugin

    Example

    I hope you have Got What is How to make Secure WordPress Site And how it works.I would Like to have FeadBack From My Blog(Pakainfo.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(Pakainfo.com) Are Most Always Welcome.

Get Order List By Customer Id using Magento programmatically 0

Get Order List By Customer Id using Magento programmatically

Get Order List By Customer Id using Magento programmatically

In this Post We Will Explain About is Get Order List By Customer Id using Magento programmatically With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Get customer order count in Magento Example

In this post we will show you Best way to implement magento 2 get orders by customer id, hear for How to get order list for logged in customer in magento with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Magento Get Order List By Customer Id

Hear is the simple source code for Magento Get Order List simple display By Customer Id in Magento, You can use this root file out-side of PHP using magento(on first main root of magento).

<?php
// include mage file 
require_once 'app/Mage.php';
Mage::app('default');   
Mage::getSingleton("core/session", array("name" => "frontend")); 
 
// create functions 
function isCustomerHasOrders($id_Cust, $total_grand = null)
{
    $getgetorderCollection = $this->getCustomerOrder($id_Cust, $total_grand);
    return (bool)$getorderCollection->getSize();
}
 
function getCustomerOrder($id_Cust, $total_grand = null)
{   
    $getorderCollection = Mage::getResourceModel('sales/order_collection')
        ->addFieldToSelect('*')
        ->addFieldToFilter('id_Cust', $id_Cust)
        ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
        ->setOrder('created_at', 'desc');
    if ($total_grand && $total_grand > 0) 
    {
        $getorderCollection->addFieldToFilter('base_grand_total', array ('gteq' => $total_grand));
    }
    return $getorderCollection;
}
// first magento end function 
 
// start source code here
 
if (Mage::getSingleton('customer/session')->isLoggedIn()) 
{  
    $allcust_info = Mage::getSingleton('customer/session')->getCustomer();
    $id_Cust = $allcust_info->getId();
    $mycol_order = getCustomerOrder($id_Cust, $total_grand = null);
    $countorder = count($mycol_order);
    if($countorder > 0)
    {
        $i=0;
        foreach($mycol_order as $liveOrder_Value)
        {
            $liveOrder   = Mage::getModel('sales/order')->load($liveOrder_Value->getId());
            $orderid = $liveOrder_Value->getId();
 
            // Now we can show get order id or order number
            $ordernumber = $liveOrder->getIncrementId();
 
            $orderdate1 = $liveOrder->getCreatedAtStoreDate();
 
            $orderdate2 = str_replace(",","",$orderdate1);
            $orderdate = trim($orderdate2,'');
 
            //echo date(strtotime($liveOrder->getCreatedAtStoreDate()); 
 
            //Now we can show get liveOrder total value:
            $totalOrderVal = number_format ($liveOrder->getGrandTotal(), 2, '.' , $thousands_sep = '');
 
            $payment_method_code = $liveOrder->getPayment()->getMethodInstance()->getCode();
 
            $status= $liveOrder->getStatusLabel();
 
            $cust_fname = $liveOrder->getCustomerFirstname();
 
            $code_curr = Mage::app()->getStore()->getCurrentCurrencyCode(); 
            $cust_lname = $liveOrder->getCustomerLastname();
 
            // Now we can show liveItem list
            $orderItems = $liveOrder->getItemsCollection();
            $j = 0;
            foreach ($orderItems as $liveItem)
            {
                $productid    = $liveItem->product_id;
                $productsku   = $liveItem->sku;
                $productprice = $liveItem->getPrice();
                $productname  = $liveItem->getName();
                $productqty   = $liveItem->getData('qty_ordered');
                //echo $productsubtotal = $liveItem->getSubTotal();
                $productsubtotal = $productqty * $productprice;
 
                // Now we can show get product image 
                $productimg2 = Mage::getModel('catalog/product')->load($liveItem->product_id);
                $productMediaConfig = Mage::getModel('catalog/product_media_config');
                $prodimgthumbnailUrl = $productMediaConfig->getMediaUrl($productimg2->getThumbnail());
                $ItemInfo[$j] = array(
                        "productId" => $productid,   
                        "productName" => $productname,   
                        "productSku" => $productsku,
                        "productQty" => $productqty,
                        "productPrice" => $productprice,
                        "productSubTotal" => $productsubtotal,
                        "prodImgUrl" => $prodimgthumbnailUrl
                    );
                $j++; 
            }
            $listOf_order[$i] = array(
                    "orderId" => $orderid,   
                    "orderNumber" => $ordernumber,
                    "orderDate" => $orderdate,
                    "shipTo" => $cust_fname.''.$cust_lname,
                    "orderTotal" => $totalOrderVal,
                    "currency" => $code_curr,
                    "itemList" => $ItemInfo
                );
            $i++;
        }
        $data['responseCode'] = '1';
        $data['msg'] = 'successfull';
        $data['orderListResponse'] = $listOf_order;
    }
    else
    {
		//if countorder no so display
        $data['responseCode'] = '0';
        $data['msg'] = 'Sorry .....No Data Found';
    }
}
else
{
	//magento authentication error
    $data['responseCode'] = '0';
    $data['msg'] = 'First of all simple You must Login';
}

//display all the json_encode data
$result = json_encode($data);
echo $result;
?>

You are Most welcome in my youtube Channel Please subscribe my channel. and give me FeedBack.
More Details……
Angularjs Example

Example

I hope you have Got What is Logged In User Order List in magento programmatically And how it works.I would Like to have FeedBack From My Blog(Pakainfo.com) readers.Your Valuable FeedBack,Any Question,or any Comments about This Article(Pakainfo.com) Are Most Always Welcome.

Create Order and Invoice using Magento 0

Create Order and Invoice using Magento

Create Order and Invoice using Magento

In this Post We Will Explain About is Create Order and Invoice using Magento With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to create order invoice programmatically in Magento Example

In this post we will show you Best way to implement How To Create Transaction In Magento2 Programmatically, hear for create order programmatically customer as guest in magento with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Step 1 : set Store Id

1 First off all We need to set Store Id by changing the source code as below simple source code:

/* Set Store Id */
$dataStoreId = 2; // Here 2 is some Store Id
$infoStore = Mage::getModel('core/store')->load($dataStoreId);

Step 2 : user information / address

2 Set or assigned your user information / address and make user if not any user exist. Do this as the simple step to following source code:

// Set User Information /Address
$productId = 989825; // Magento Product Id
$user_email = “[email protected]”; // User Email Address
$user_fname = “jaydeep Gondaliya”; 
$user_lname = “Gondaliya”;
$street = “USA Rajkot 360002”;
$city = USA;
$region = “Region”;
$postcode = “123589”;
$mobile = “9898225074”;
$country_id = “+61”;
$user_ip =“121.202.192.168”;

// Check user by website id
$user = Mage::getModel("user/user");
$user->setWebsiteId($infoStore->getWebsiteId())->loadByEmail($user_email);

// If store some data of website not found,so here set admin store id
if(count($user->getData())<=0){ $user->setWebsiteId(Mage_Core_Model_App::ADMIN_STORE_ID)->loadByEmail($user_email);
}

if(count($user->getData())<=0){ $user->setGroupId(1);
    $user->setEmail($user_email);
    $user->setFirstname($user_fname);
    $user->setLastname($user_lname);
    $user->save();
}


Step 3: sales quote model to make sales order

here simple condition some sales dataQuote make model to make some sales order. display the some source code below:

$dataQuote = Mage::getModel('sales/dataQuote')->setStoreId($dataStoreId);

Step 4 : Assign customer to the quote

Assign user to the dataQuote as the following simple source code:

if(count($user->getData())>0){
    // For some Existing User
    $dataQuote->assignUser($user);
}else{
    // For Guest Orders Only
    $dataQuote->setUserEmail($user_email);


Step 5 : billing/shipping address,

Last and Most important step which will some magento execute the final orcer process. From this Last step We will get simple assigned crate new product, assigned simple way to billing/shipping address like as a below some code, assigned simple or best way to payment method, maked a simple data customer order and liveInvoice. Display the source code below:

// Get Product data from Id							
$_product = Mage::getModel('catalog/product')->setStoreId($dataStoreId)->load($productId);

if(count($_product->getData())>0){
    // Assign product(s) to qoute
    $infoBuy = array('qty'=>1,'product'=>$_product->getId());
    $dataQuote->addProduct($_product,new Varien_Object($infoBuy));
    
    /* Check simple region for country */
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');
    //Select Query
    $query = $write->query("SELECT * FROM `directory_country_region` WHERE `country_id`='".$country_id."'");
    while($contry_data=$query->fetch()){
        $has_country_region=true;
        break;
    }
    if($has_country_region){
        $addressData = array(
            'firstname' => $user_fname, //firstname
            'lastname' => $user_lname, //lastname
            'street' => $street,  //streetname
            'city' => $city,   //cityname
            'region_id' =>$region,
            'postcode' => $postcode, //69555
            'mobile' => $mobile,  //9898526522
            'country_id' => $country_id  //+1
        );
    }else{
        $addressData = array(
            'firstname' => $user_fname, //mayur
            'lastname' => $user_lname,  // dhameliya
            'street' => $street,
            'city' => $city, //city name
            'region' =>$region, // region name
            'postcode' => $postcode, // 360002
            'mobile' => $mobile,  //9898225052
            'country_id' => $country_id //+91
        );
    }
    
    // Add Billing Address to qoute
    $billingAddress = $dataQuote->getBillingAddress()->addData($addressData);
    
    // Assign payment method i.e Check or Money Order
    $dataQuote->getPayment()->importData(array('method' => 'checkmo'));
    // Save dataQuote data
    $dataQuote->collectTotals()->save();
    
    $service = Mage::getModel('sales/service_dataQuote', $dataQuote);
    $service->submitAll();
    $order = $service->getOrder();
    
    if($user_ip){
        //Now set newly entered order's remote IP.
        $order->setRemoteIp($user_ip);
        
        //Finally we save our order after setting it's IP.
        $order->save();
                
        if($order->getIncrementId()){							
            // Start Automatic Invoice Create								
            if(!$order->canInvoice()){
                Mage::throwException(Mage::helper('core')->__('Cannot create an liveInvoice.'));
            }
             
            $liveInvoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
             
            if (!$liveInvoice->getTotalQty()) {
                Mage::throwException(Mage::helper('core')->__('Cannot save Make an liveInvoice without products.'));
            }
             
            //$liveInvoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
            $liveInvoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
            $liveInvoice->register();
            $saveTransData = Mage::getModel('core/resource_transaction')
            ->addObject($liveInvoice)
            ->addObject($liveInvoice->getOrder());
             
            $saveTransData->save();
}

You are Most welcome in my youtube Channel Please subscribe my channel. and give me FeedBack.
More Details……
Angularjs Example

Example

I hope you have Got What is php – Create an Invoice after order is placed And how it works.I would Like to have Feed Back From My Blog(Pakainfo.com) readers.Your Valuable Feed Back,Any Question,or any Comments about This Article(Pakainfo.com) Are Most Always Welcome.