CakePHP
XML Views in CakePHP
In this article, we are going to discuss about how to return XML response to views in CakePHP. CakePHP is an open source web application framework. It follows the Model-View-Controller (MVC) approach and is written in PHP, modeled after the concepts of Ruby on Rails, and distributed under the MIT License.CakePHP uses well-known software engineering concepts and software design patterns, such as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.
Step 1:
Open the file "app\Config\routes.php" and added the following line:
/**
* Parse XML Routes
*/
Router::parseExtensions('xml');
This enables your Controller actions to start accepting the .xml postfix e.g. http://cakephp_app/controller/action.xml
Step 2:
Enable the RequestHandler component in your Controller like this:
public $components = array('RequestHandler');
Step 3:
Once that's done, you have a few more methods at your disposal to start dealing with XML requests. First create a beforeFilter method in your Controller and add the following:
public function beforeFilter() {
parent::beforeFilter();
// Set XML
if ($this->RequestHandler->isXml()) {
$this->RequestHandler->setContent('xml');
}
}
Step 4:
Once that's done, create the action that you want to use and be sure to add in the respondAs & renderAs methods as the official documentation is a bit flakey with their use:
public function related() {
// Only allow XML requests
if (!$this->RequestHandler->isXml()) {
throw new MethodNotAllowedException();
}
// Set response as XML
$this->RequestHandler->respondAs('xml');
$this->RequestHandler->renderAs($this, 'xml');
}
Step 5:
Using those 2 methods as I was then able to create an xml folder in the corresponding View folder and inside that create my view file e.g. app\View\Uploads\xml\related.ctp
<?xml version="1.0"?>
<people>
<person>
<name>James</name>
</person>
</people>
Now if you visited the page in your browser you should see your XML output as per your View e.g. http://cakephp_app/uploads/related.xml
Wrapping Up
Further to this if you wanted to pass in some parameters to make the Controller action dynamic you can do by using the following e.g. http://cakephp_app/uploads/related/videos/1.xml
The "videos" parameter and the "1" ID will be available in the Controller like this:
// Get passed params
$uploadType = $this->request->params['pass'][0];
$uploadId = $this->request->params['pass'][1];
Step 1:
Open the file "app\Config\routes.php" and added the following line:
/**
* Parse XML Routes
*/
Router::parseExtensions('xml');
This enables your Controller actions to start accepting the .xml postfix e.g. http://cakephp_app/controller/action.xml
Step 2:
Enable the RequestHandler component in your Controller like this:
public $components = array('RequestHandler');
Step 3:
Once that's done, you have a few more methods at your disposal to start dealing with XML requests. First create a beforeFilter method in your Controller and add the following:
public function beforeFilter() {
parent::beforeFilter();
// Set XML
if ($this->RequestHandler->isXml()) {
$this->RequestHandler->setContent('xml');
}
}
Step 4:
Once that's done, create the action that you want to use and be sure to add in the respondAs & renderAs methods as the official documentation is a bit flakey with their use:
public function related() {
// Only allow XML requests
if (!$this->RequestHandler->isXml()) {
throw new MethodNotAllowedException();
}
// Set response as XML
$this->RequestHandler->respondAs('xml');
$this->RequestHandler->renderAs($this, 'xml');
}
Step 5:
Using those 2 methods as I was then able to create an xml folder in the corresponding View folder and inside that create my view file e.g. app\View\Uploads\xml\related.ctp
<?xml version="1.0"?>
<people>
<person>
<name>James</name>
</person>
</people>
Now if you visited the page in your browser you should see your XML output as per your View e.g. http://cakephp_app/uploads/related.xml
Wrapping Up
Further to this if you wanted to pass in some parameters to make the Controller action dynamic you can do by using the following e.g. http://cakephp_app/uploads/related/videos/1.xml
The "videos" parameter and the "1" ID will be available in the Controller like this:
// Get passed params
$uploadType = $this->request->params['pass'][0];
$uploadId = $this->request->params['pass'][1];
PHP CMS Frameworks
October 14, 2015
Read more →
Wordpress
Automatically Create a Bit.ly URL for WordPress Posts
In this article, we are going to discuss about How to create Bit.ly URL for WordPress posts automatically. Bit.ly is currently the most popular URL shorting service out there and for a good reason too. With bit.ly you can track your shortened URLs and much more. In this article I'm going to show you how to use bit.ly's api create bit.ly urls automatically for WordPress posts.
In order to make use of Bit.ly's API, you'll need to:
Now that you have a login and API key, open your WordPress theme's functions.php (just create one if you don't have one) and paste the following code at the top of the document:
//create bit.ly url
function bitly()
{
//login information
$url = get_permalink(); //generates wordpress' permalink
$login = 'imjp'; //your bit.ly login
$apikey = 'R_11882237eac772b5d6126e895a06c43f'; //bit.ly apikey
$format = 'json'; //choose between json or xml
$version = '2.0.1';
//create the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
//get the url
//could also use cURL here
$response = file_get_contents($bitly);
//parse depending on desired format
if(strtolower($format) == 'json')
{
$json = @json_decode($response,true);
echo $json['results'][$url]['shortUrl'];
}
else //xml
{
$xml = simplexml_load_string($response);
echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}
The code above is pretty much self explanatory.
Don't forget to change the login and apikey strings to match yours.
I hope you guys found this article useful.
In order to make use of Bit.ly's API, you'll need to:
Now that you have a login and API key, open your WordPress theme's functions.php (just create one if you don't have one) and paste the following code at the top of the document:
//create bit.ly url
function bitly()
{
//login information
$url = get_permalink(); //generates wordpress' permalink
$login = 'imjp'; //your bit.ly login
$apikey = 'R_11882237eac772b5d6126e895a06c43f'; //bit.ly apikey
$format = 'json'; //choose between json or xml
$version = '2.0.1';
//create the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
//get the url
//could also use cURL here
$response = file_get_contents($bitly);
//parse depending on desired format
if(strtolower($format) == 'json')
{
$json = @json_decode($response,true);
echo $json['results'][$url]['shortUrl'];
}
else //xml
{
$xml = simplexml_load_string($response);
echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}
The code above is pretty much self explanatory.
Don't forget to change the login and apikey strings to match yours.
I hope you guys found this article useful.
PHP CMS Frameworks
September 23, 2015
Read more →
Joomla
TZ Portfolio - A joomla portpolio component / Module / Plugin download
TZ Portfolio works on database of comcontent, sothat you do not have to worry about importing or exporting data from your system (which already works with comcontent). TZ Portfolio inherits all current functions of com_content, in addition, we develop two new data interfaces: Portfolio and Timeline view. TZ Portfolio is strongly supported by Group Extra field system, you can create multi-portfolio system in your website. In addition, it supply 3 functions , these are video display, gallery or representative photo displayed for each article.
We also upgrade tag and authority information management function, along with photo smart resize and crop. With TZ Portfolio you can own a smart blog, a flexible portfolio, and more than a complete content management system.
Extension Name: TZ Portfolio
Price: Free
More info and reviews: TZ Portfolio on JED
For Demo - Click Here
To download the component - Click Here
For Documentation - Click Here
For Support - Click Here
We also upgrade tag and authority information management function, along with photo smart resize and crop. With TZ Portfolio you can own a smart blog, a flexible portfolio, and more than a complete content management system.
Extension Name: TZ Portfolio
Price: Free
More info and reviews: TZ Portfolio on JED
For Demo - Click Here
To download the component - Click Here
For Documentation - Click Here
For Support - Click Here
PHP CMS Frameworks
September 02, 2015
Read more →
Magento
Create Helloworld module in Magento
In this article, we are going to discuss about How to create a Helloworld custom module in Magento. Magento is an open-source content management system for e-commerce web sites. Magento employs the MySQL relational database management system, the PHP programming language, and elements of the Zend Framework. It applies the conventions of object-oriented programming and model-view-controller architecture. Magento also uses the entity–attribute–value model to store data.
Step 1: Module Declaration
Note : PCF (PHPCmsFramework)
Create app/etc/modules/PCF_HelloWorld.xml and write below code
<?xml version="1.0"?>
<config>
<modules>
<PCF_HelloWorld>
<active>true</active>
<codePool>local</codePool>
</PCF_HelloWorld>
</modules>
</config>
Step 2: Module Configuration
2.1) Create a controller class app/code/local/PCF/HelloWorld/controllers/IndexController.php
class PCF_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout(array('default'));
$this->renderLayout();
}
}
2.2) Create a Block class app/code/local/PCF/HelloWorld/Block/HelloWorld.php
class PCF_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
{
// necessary methods
}
2.3) create configuration xml in app/code/local/PCF/HelloWorld/etc/config.xml
<?xml version="1.0"?>
<config>
<global>
<modules>
<PCF_helloworld>
<version>0.1.0</version>
</PCF_helloworld>
</modules>
<blocks>
<helloworld>
<rewrite>
<helloworld>PCF_HelloWorld_Block_HelloWorld</helloworld>
</rewrite>
</helloworld>
</blocks>
</global>
<frontend>
<routers>
<helloworld>
<use>standard</use>
<args>
<module>PCF_HelloWorld</module>
<frontName>helloworld</frontName>
</args>
</helloworld>
</routers>
<layout>
<updates>
<helloworld>
<file>helloworld.xml</file>
</helloworld>
</updates>
</layout>
</frontend>
</config>
Define Frontend Template :
1. Define page layout in app/design/frontend/PCF/default/layout/helloworld.xml
N.B: Use default instead of PCF as template location if you use default design packages. Means create file in app/design/frontend/default/default/layout/helloworld.xml
<?xml version="1.0"?>
<layout version="0.1.0">
<helloworld_index_index>
<reference name="root">
<action method="setTemplate"><template>page/1column.phtml</template></action>
</reference>
<reference name="content">
<block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
</reference>
</helloworld_index_index>
</layout>
2. Create template file app/design/frontend/PCF/default/template/helloworld/helloworld.phtml and write down
N.B: Use default instead of PCF as template location if you use default design packages. Means create file in app/design/frontend/default/default/template/helloworld/helloworld.phtml
Hello World ! I am a Magento Guy..
Hey, new module is ready to run and hit browser with url
http://127.0.0.1/projectname/index.php/helloworld/
and see result.
That's it……..
Step 1: Module Declaration
Note : PCF (PHPCmsFramework)
Create app/etc/modules/PCF_HelloWorld.xml and write below code
<?xml version="1.0"?>
<config>
<modules>
<PCF_HelloWorld>
<active>true</active>
<codePool>local</codePool>
</PCF_HelloWorld>
</modules>
</config>
Step 2: Module Configuration
2.1) Create a controller class app/code/local/PCF/HelloWorld/controllers/IndexController.php
class PCF_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout(array('default'));
$this->renderLayout();
}
}
2.2) Create a Block class app/code/local/PCF/HelloWorld/Block/HelloWorld.php
class PCF_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
{
// necessary methods
}
2.3) create configuration xml in app/code/local/PCF/HelloWorld/etc/config.xml
<?xml version="1.0"?>
<config>
<global>
<modules>
<PCF_helloworld>
<version>0.1.0</version>
</PCF_helloworld>
</modules>
<blocks>
<helloworld>
<rewrite>
<helloworld>PCF_HelloWorld_Block_HelloWorld</helloworld>
</rewrite>
</helloworld>
</blocks>
</global>
<frontend>
<routers>
<helloworld>
<use>standard</use>
<args>
<module>PCF_HelloWorld</module>
<frontName>helloworld</frontName>
</args>
</helloworld>
</routers>
<layout>
<updates>
<helloworld>
<file>helloworld.xml</file>
</helloworld>
</updates>
</layout>
</frontend>
</config>
Define Frontend Template :
1. Define page layout in app/design/frontend/PCF/default/layout/helloworld.xml
N.B: Use default instead of PCF as template location if you use default design packages. Means create file in app/design/frontend/default/default/layout/helloworld.xml
<?xml version="1.0"?>
<layout version="0.1.0">
<helloworld_index_index>
<reference name="root">
<action method="setTemplate"><template>page/1column.phtml</template></action>
</reference>
<reference name="content">
<block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
</reference>
</helloworld_index_index>
</layout>
2. Create template file app/design/frontend/PCF/default/template/helloworld/helloworld.phtml and write down
N.B: Use default instead of PCF as template location if you use default design packages. Means create file in app/design/frontend/default/default/template/helloworld/helloworld.phtml
Hello World ! I am a Magento Guy..
Hey, new module is ready to run and hit browser with url
http://127.0.0.1/projectname/index.php/helloworld/
and see result.
That's it……..
PHP CMS Frameworks
August 03, 2015
Read more →
Magento
Magento – Ajax Add to Cart from Product Page Using jQuery
In this article, we are going to discuss about How to create an Ajax based Add to Cart from Product Page Using jQuery in Magento. This is just going to be a quick snippet. One thing I get asked a lot is how to add a product to the cart using ajax and its actually quite easy to do. Now I'm not going to go over how to use jQuery with Magento because there are plenty of tutorials on how to do that. I am going to assume you have jQuery setup in Magento.
<script type="text/javascript">
(function($)
{
$(document).ready(function()
{
// Setup the click event
$('#product_addtocart_form').submit(addToCart);
});
function addToCart(e)
{
e.preventDefault();
// Here You Should Validate Your Information.
// For example if you have options that need to be selected like shirt size
// Now get the forms data
var formData = $('#product_addtocart_form').serialize();
// Now because we are adding the cart through ajax you need to add this so the controller knows that it is ajax and can pass back json if there is an error
formData += '&isAjax=1';
// Send the form data over
$.ajax({
url:$('#product_addtocart_form').attr('action'),
type:'POST',
data:formData,
dataType:'json',
success:function(data)
{
// Do what you want. You have added a product to your cart
// I Like to show my persistant cart popup here
}
});
}
})(jQuery);
</script>
<script type="text/javascript">
(function($)
{
$(document).ready(function()
{
// Setup the click event
$('#product_addtocart_form').submit(addToCart);
});
function addToCart(e)
{
e.preventDefault();
// Here You Should Validate Your Information.
// For example if you have options that need to be selected like shirt size
// Now get the forms data
var formData = $('#product_addtocart_form').serialize();
// Now because we are adding the cart through ajax you need to add this so the controller knows that it is ajax and can pass back json if there is an error
formData += '&isAjax=1';
// Send the form data over
$.ajax({
url:$('#product_addtocart_form').attr('action'),
type:'POST',
data:formData,
dataType:'json',
success:function(data)
{
// Do what you want. You have added a product to your cart
// I Like to show my persistant cart popup here
}
});
}
})(jQuery);
</script>
PHP CMS Frameworks
July 22, 2015
Read more →
Magento
Create an Ajax Coupon / Discount Code Box in Magento
In this article, we are going to discuss about How to create an Ajax Coupon / Discount code box in Magento. Basically this will set you up with the new extension you are going to create. The only thing in the tutorial that you do not need to do is putting any information in the controller file. I am going to assume you have followed the tutorial and you are ready to edit your CartController.php. To start off your file is going to look like this.
<?php
require_once 'Mage/Checkout/controllers/CartController.php';
class YourNameSpace_YourModule_CartController extends Mage_Checkout_CartController
{
}
This is our basic controller file. With this any functions we write that have the same name as the Mage Cart Controller will now be overwritten. this is great if you ever need to make changes like adding ajax functionality to any other parts of magento. Next we add the following code and our file should look like this.
<?php
require_once 'Mage/Checkout/controllers/CartController.php';
class YourNameSpace_YourModule_CartController extends Mage_Checkout_CartController
{
function couponPostAction()
{
// if not ajax have parent deal with result
if(!isset($_POST['ajax']))
{
parent::couponPostAction();
return;
}
$msg = '';
$couponCode = (string) $this->getRequest()->getParam('coupon_code');
if ($this->getRequest()->getParam('remove') == 1) {
$couponCode = '';
}
$oldCouponCode = $this->_getQuote()->getCouponCode();
if (!strlen($couponCode) && !strlen($oldCouponCode)) {
$this->_goBack();
return;
}
try {
$this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
$this->_getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '')
->collectTotals()
->save();
if ($couponCode) {
if ($couponCode == $this->_getQuote()->getCouponCode()) {
$this->_getSession()->addSuccess(
$this->__('Coupon code "%s" was applied.', Mage::helper('core')->htmlEscape($couponCode))
);
}
else {
$msg = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode));
}
} else {
$this->_getSession()->addSuccess($this->__('Coupon code was canceled.'));
}
} catch (Mage_Core_Exception $e) {
$msg = $e->getMessage();
} catch (Exception $e) {
$msg = $this->__('Cannot apply the coupon code.');
Mage::logException($e);
}
echo $msg;
}
}
So basically what we do is check for a POST variable called ajax. If this does not exist then we know not to use our ajax code so let the regular code run or the parents code if you will. If it is available then we continue. The code is essentially the same as it's parent except instead of putting any errors into a session variable and send the browser back a page, we are echoing out any error messages. If the $msg variable is empty then we know there were no errors.
Now we can move on to our form and javascript. Our form should look something like the following
<div class="box">
<strong class="ttl">DISCOUNT CODE</strong>
<p>Enter your coupon code if you have one</p>
<form id="discountcode-form" action="<?= $this->getUrl('checkout/cart/couponPost') ?>" name="discountcode-form" method="post">
<div class="text discount-code"><input type="text" name="coupon_code" value="SUBMIT YOUR CODE" /></div>
<input type="submit" class="btn-apply" value="APPLY"/>
</form>
</div>
This is just your basic discount code form. You can make any design modifications as you want the only things that are important are the form tags and the input box. Once you have your form you will want to create the following javascript
$('#discountcode-form').submit(function(e)
{
e.preventDefault();
$.ajax({
url:$('#discountcode-form').attr('action'),
type:'POST',
data:'ajax=true&'+$('#discountcode-form').serialize(),
success:function(data)
{
if(data != '')
{
// Display error message however you would like
}
}
});
});
What this script does is takes the action url from the form and passes all of the forms data to our php script using the jQuery ajax function. It then listens for a response. If it getts something other then null you can take that message and display it however you like.
If you have any questions please let me know and as always leave your feedback...
<?php
require_once 'Mage/Checkout/controllers/CartController.php';
class YourNameSpace_YourModule_CartController extends Mage_Checkout_CartController
{
}
This is our basic controller file. With this any functions we write that have the same name as the Mage Cart Controller will now be overwritten. this is great if you ever need to make changes like adding ajax functionality to any other parts of magento. Next we add the following code and our file should look like this.
<?php
require_once 'Mage/Checkout/controllers/CartController.php';
class YourNameSpace_YourModule_CartController extends Mage_Checkout_CartController
{
function couponPostAction()
{
// if not ajax have parent deal with result
if(!isset($_POST['ajax']))
{
parent::couponPostAction();
return;
}
$msg = '';
$couponCode = (string) $this->getRequest()->getParam('coupon_code');
if ($this->getRequest()->getParam('remove') == 1) {
$couponCode = '';
}
$oldCouponCode = $this->_getQuote()->getCouponCode();
if (!strlen($couponCode) && !strlen($oldCouponCode)) {
$this->_goBack();
return;
}
try {
$this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
$this->_getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '')
->collectTotals()
->save();
if ($couponCode) {
if ($couponCode == $this->_getQuote()->getCouponCode()) {
$this->_getSession()->addSuccess(
$this->__('Coupon code "%s" was applied.', Mage::helper('core')->htmlEscape($couponCode))
);
}
else {
$msg = $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode));
}
} else {
$this->_getSession()->addSuccess($this->__('Coupon code was canceled.'));
}
} catch (Mage_Core_Exception $e) {
$msg = $e->getMessage();
} catch (Exception $e) {
$msg = $this->__('Cannot apply the coupon code.');
Mage::logException($e);
}
echo $msg;
}
}
So basically what we do is check for a POST variable called ajax. If this does not exist then we know not to use our ajax code so let the regular code run or the parents code if you will. If it is available then we continue. The code is essentially the same as it's parent except instead of putting any errors into a session variable and send the browser back a page, we are echoing out any error messages. If the $msg variable is empty then we know there were no errors.
Now we can move on to our form and javascript. Our form should look something like the following
<div class="box">
<strong class="ttl">DISCOUNT CODE</strong>
<p>Enter your coupon code if you have one</p>
<form id="discountcode-form" action="<?= $this->getUrl('checkout/cart/couponPost') ?>" name="discountcode-form" method="post">
<div class="text discount-code"><input type="text" name="coupon_code" value="SUBMIT YOUR CODE" /></div>
<input type="submit" class="btn-apply" value="APPLY"/>
</form>
</div>
This is just your basic discount code form. You can make any design modifications as you want the only things that are important are the form tags and the input box. Once you have your form you will want to create the following javascript
$('#discountcode-form').submit(function(e)
{
e.preventDefault();
$.ajax({
url:$('#discountcode-form').attr('action'),
type:'POST',
data:'ajax=true&'+$('#discountcode-form').serialize(),
success:function(data)
{
if(data != '')
{
// Display error message however you would like
}
}
});
});
What this script does is takes the action url from the form and passes all of the forms data to our php script using the jQuery ajax function. It then listens for a response. If it getts something other then null you can take that message and display it however you like.
If you have any questions please let me know and as always leave your feedback...
PHP CMS Frameworks
July 16, 2015
Read more →
CodeIgniter
File Upload and Validation in CodeIgniter
In this article, we are going to discuss about How to do the file upload and validation in CodeIgniter. I would like to explain how to upload files to server in CodeIgniter and to validate it with Form Validation library.
Step 1 :
Create a view that contains form fields and a field with input type file (Register.php) and add the below code in that file.
<?php echo form_open_multipart('welcome/register/'); ?>
form_open_multipart is used to upload files. It supports the input type file. Next we have to add other form fields and fiel field.
<?php echo validation_errors('<p class="form_error">','</p>'); ?>
<?php echo form_open_multipart('welcome/register/'); ?>
<input type="text" name="firstname" placeholder="Enter your Firstname"/>
<input type="text" name="city" placeholder="Enter your City"/>
<input type="file" name="userimage">
<button type="submit">Create Account</button>
</form>
Step 2:
Now, the form is submitted to the Register method in Welcome controller. Our Register method in Welcome contoller looks like this Welcome.php
public function register(){
$this->load->library('form_validation');
$this->form_validation->set_rules('firstname', 'First Name', 'required|trim|xss_clean');
$this->form_validation->set_rules('city', 'City', 'required|trim|xss_clean');
$this->form_validation->set_rules('userimage', 'Profile Image', 'callback_image_upload');
if($this->form_validation->run() == TRUE){
echo "Account Created Successfully";
}
$this->load->view('register');
}
Step 3:
Create a callback function for uploading image and validation. Method image_upload looks like the following.
function image_upload(){
if($_FILES['userimage']['size'] != 0){
$upload_dir = './images/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
$config['upload_path'] = $upload_dir;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = 'userimage_'.substr(md5(rand()),0,7);
$config['overwrite'] = false;
$config['max_size'] = '5120';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userimage')){
$this->form_validation->set_message('image_upload', $this->upload->display_errors());
return false;
}
else{
$this->upload_data['file'] = $this->upload->data();
return true;
}
}
else{
$this->form_validation->set_message('image_upload', "No file selected");
return false;
}
}
Explaining the callback function.
Steps Involved are
Hope this is helpful.
- How to upload files to server
- How to Validate file before uploading
- How to upload files to server
Step 1 :
Create a view that contains form fields and a field with input type file (Register.php) and add the below code in that file.
<?php echo form_open_multipart('welcome/register/'); ?>
form_open_multipart is used to upload files. It supports the input type file. Next we have to add other form fields and fiel field.
<?php echo validation_errors('<p class="form_error">','</p>'); ?>
<?php echo form_open_multipart('welcome/register/'); ?>
<input type="text" name="firstname" placeholder="Enter your Firstname"/>
<input type="text" name="city" placeholder="Enter your City"/>
<input type="file" name="userimage">
<button type="submit">Create Account</button>
</form>
Step 2:
Now, the form is submitted to the Register method in Welcome controller. Our Register method in Welcome contoller looks like this Welcome.php
public function register(){
$this->load->library('form_validation');
$this->form_validation->set_rules('firstname', 'First Name', 'required|trim|xss_clean');
$this->form_validation->set_rules('city', 'City', 'required|trim|xss_clean');
$this->form_validation->set_rules('userimage', 'Profile Image', 'callback_image_upload');
if($this->form_validation->run() == TRUE){
echo "Account Created Successfully";
}
$this->load->view('register');
}
Step 3:
Create a callback function for uploading image and validation. Method image_upload looks like the following.
function image_upload(){
if($_FILES['userimage']['size'] != 0){
$upload_dir = './images/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
$config['upload_path'] = $upload_dir;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = 'userimage_'.substr(md5(rand()),0,7);
$config['overwrite'] = false;
$config['max_size'] = '5120';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userimage')){
$this->form_validation->set_message('image_upload', $this->upload->display_errors());
return false;
}
else{
$this->upload_data['file'] = $this->upload->data();
return true;
}
}
else{
$this->form_validation->set_message('image_upload', "No file selected");
return false;
}
}
Explaining the callback function.
Steps Involved are
- First we are checking if the file is submitted with the form. If the file is empty, we are setting the form validation error message as "No file selected".
- We are creating a directory if the directory does not exist.
- We have to configure the directory path, allowed upload files, filename, maximum file size, maximum width, maximum height etc.,
- Then we are uploading the file. If upload fails, error message is set to the form validation.
Hope this is helpful.
PHP CMS Frameworks
June 28, 2015
Read more →
YII
Yii – Load modules dynamically from db or directory
In this article, we are going to discuss about How to load the modules dynamically from DB or from Directory in YII framework. In Yii application development, we can set up modules configuration in config.php. Sometimes, we need to load modules configuration from database or directory glob. After searching the topic in google and comparing some solutions, I found the elegant way to implement this. Hope it can help.
You can modify the index.php file of your Yii application.
require_once($yii);
class ExtendableWebApp extends CWebApplication {
protected function init() {
// this example dynamically loads every module which can be found
// under `modules` directory
// this can be easily done to load modules
// based on MySQL db or any other as well
foreach (glob(dirname(__FILE__).'/protected/modules/*', GLOB_ONLYDIR) as $moduleDirectory) {
$this->setModules(array(basename($moduleDirectory)));
}
return parent::init();
}
}
$app=new ExtendableWebApp($config);
$app->run();
Reference: http://www.yiiframework.com/forum/index.php/topic/23467-dynamically-load-modules-models-and-configurations/page__p__144316#entry144316
You can modify the index.php file of your Yii application.
require_once($yii);
class ExtendableWebApp extends CWebApplication {
protected function init() {
// this example dynamically loads every module which can be found
// under `modules` directory
// this can be easily done to load modules
// based on MySQL db or any other as well
foreach (glob(dirname(__FILE__).'/protected/modules/*', GLOB_ONLYDIR) as $moduleDirectory) {
$this->setModules(array(basename($moduleDirectory)));
}
return parent::init();
}
}
$app=new ExtendableWebApp($config);
$app->run();
Reference: http://www.yiiframework.com/forum/index.php/topic/23467-dynamically-load-modules-models-and-configurations/page__p__144316#entry144316
PHP CMS Frameworks
June 17, 2015
Read more →
Magento
Magento Functional and Factory class groups
In this article, we are going to discuss about the Functional and Factory class groups in Magento. As you know Magento is built based on module architecture, which leads to the requirement that there must be an interaction between modules. Hence, in this part we will learn about the way these modules used.
Definition and Examples of Functional and Factory class groups
Functional Class
Factory Class
Create an instance of class Mage_Catalog_Model_Product
Mage::getModel('catalog/product')
Generate an instance of class Mage_Catalog_Block_Product_View
Mage::getBlockSingleton('catalog/product_view')
Definition of Instance, the ways to create the instance object in Magento
Mage::getModel('catalog/product');
Mage::getBlockSingleton('catalog/product_view');
Mage::app()->getLayout()-createBlock('catalog/product_view')
The process to generate an instance through the function Mage::getModel() is as below:
1) Call function getModel() trong class Mage
2) Call function getModelInstance() in class Mage_Core_Model_Config
3) Call function getModelClassName(). This function will return the name of the model with catalog/product is Mage_Catalog_Model_Product.
4) Add a new object by the New command:
$obj = new $className($constructArguments);
In this example, $className = 'Mage_Catalog_Model_Product'
Get different instances from different places:
– With creating a Instance of a model, the function Mage::getModel() always returns a new object (instance).
– Function Mage::getSingleton() always gives only one object (instance) back.
Definition and Examples of Functional and Factory class groups
Functional Class
- Class: only contains functions and static attributes? (not sure)
- For example: Mage
Factory Class
- Class: consists of functions to create the instance (object) of different Classes. Class depends on input parameters
- For example: class Mage
Create an instance of class Mage_Catalog_Model_Product
Mage::getModel('catalog/product')
Generate an instance of class Mage_Catalog_Block_Product_View
Mage::getBlockSingleton('catalog/product_view')
Definition of Instance, the ways to create the instance object in Magento
- Definition : In OOP, Instance is an Object
- Create an instance object in Magento
Mage::getModel('catalog/product');
Mage::getBlockSingleton('catalog/product_view');
Mage::app()->getLayout()-createBlock('catalog/product_view')
The process to generate an instance through the function Mage::getModel() is as below:
1) Call function getModel() trong class Mage
2) Call function getModelInstance() in class Mage_Core_Model_Config
3) Call function getModelClassName(). This function will return the name of the model with catalog/product is Mage_Catalog_Model_Product.
4) Add a new object by the New command:
$obj = new $className($constructArguments);
In this example, $className = 'Mage_Catalog_Model_Product'
Get different instances from different places:
– With creating a Instance of a model, the function Mage::getModel() always returns a new object (instance).
– Function Mage::getSingleton() always gives only one object (instance) back.
PHP CMS Frameworks
June 10, 2015
Read more →
Drupal
Download and install Drupal modules using Drush
In this article, we are going to discuss about How to download and install Drupal modules using Drush command. One of the best things about building websites with Drupal is that there are thousands of modules that help you quickly create functionality.
To set things up, you need to download Drush and add it to your path. For example, you might unpack it into /opt/drush and then add the following line to your ~/.bashrc:
PATH=/opt/drush:$PATH
export PATH
Reload your ~/.bashrc with source ~/.bashrc, and the drush command should become available. If you're on Microsoft Windows, it might need some more finagling. (Or you can just give up and use a virtual image of Linux to develop your Drupal websites.
Drush is a huge time-saver. For example, I install dozens of modules in the course of building a Drupal website. Instead of copying the download link, changing to my sites/all/modules directory, pasting the download URL into my terminal window after wget, unpacking the file, deleting the archive, and then clicking through the various module enablement screens, I can just issue the following commands to download and enable the module.
drush dl modulename
drush en -y modulename
(The -y option means say yes to all the prompts.)
So much faster and easier. You can use these commands with several modules (module1 module2 module3), and you can use drush cli to start a shell that's optimized for Drush.
Drush is also useful if you've screwed up your Drupal installation and you need to disable themes or modules before things can work again. In the past, I'd go into the {system} table and carefully set the status of the offending row to 0. Now, that's just a drush dis modulename.
Drush has a bucketload of other useful commands, and drush help is well worth browsing. Give it a try!
To set things up, you need to download Drush and add it to your path. For example, you might unpack it into /opt/drush and then add the following line to your ~/.bashrc:
PATH=/opt/drush:$PATH
export PATH
Reload your ~/.bashrc with source ~/.bashrc, and the drush command should become available. If you're on Microsoft Windows, it might need some more finagling. (Or you can just give up and use a virtual image of Linux to develop your Drupal websites.
Drush is a huge time-saver. For example, I install dozens of modules in the course of building a Drupal website. Instead of copying the download link, changing to my sites/all/modules directory, pasting the download URL into my terminal window after wget, unpacking the file, deleting the archive, and then clicking through the various module enablement screens, I can just issue the following commands to download and enable the module.
drush dl modulename
drush en -y modulename
(The -y option means say yes to all the prompts.)
So much faster and easier. You can use these commands with several modules (module1 module2 module3), and you can use drush cli to start a shell that's optimized for Drush.
Drush is also useful if you've screwed up your Drupal installation and you need to disable themes or modules before things can work again. In the past, I'd go into the {system} table and carefully set the status of the offending row to 0. Now, that's just a drush dis modulename.
Drush has a bucketload of other useful commands, and drush help is well worth browsing. Give it a try!
PHP CMS Frameworks
June 03, 2015
Read more →
Joomla
Web Site Tour Builder - Joomla extension download
Web Site Tour Builder module is very easy to use and allow you to create a very cool tour in simple steps. Web Site Tour Builder gives you the ability to create amazing tour which easily arouse visitor interest, with a User Friendly Backend, highly customizable solution to build your tour into your site.
Features
Usefult to continue tour in multiple pages
Compatible With All recents Popular Browsers
Check this short tutorial video here: https://www.youtube.com/watch?v=mOdl9xbQAEw
Extension Name: Web Site Tour Builder
Price: Paid (€ 19,00)
More info and reviews: Web Site Tour Builder on JED
For Demo - Click Here
Download Paid Version - Click Here
For Documentation - Click Here
Features
- Support Continued Tour in Multiple Pages
- 5 Types of Display ad ( Button, Link, Autostart on Load, LightBox on Load, Manual )
- 3 Types of Popup Box ( Modal, Tooltip, Nohighlight )
- 3 Selectors Type ( id, class, name) You can append tour to all html class
- 4 Positions (Top, Bottom, Left, Right )
- Draggable Box
- Keywords Controls to change step
- Rotation Control
- Steps Title
- Steps Text with Editor WYSIWYG for J3
- Redirect to Control
Usefult to continue tour in multiple pages
- 2 Popup Tour Themes
- 2 LightBox Themes
- Cookies Options - to not show always the tour
Compatible With All recents Popular Browsers
- Google Chrome
- Firefox
- Safari
- Opera
- Internet Explorer(IE7+)
Check this short tutorial video here: https://www.youtube.com/watch?v=mOdl9xbQAEw
Extension Name: Web Site Tour Builder
Price: Paid (€ 19,00)
More info and reviews: Web Site Tour Builder on JED
For Demo - Click Here
Download Paid Version - Click Here
For Documentation - Click Here
PHP CMS Frameworks
May 31, 2015
Read more →
CodeIgniter
Export data as CSV from database in CodeIgniter
In this article, we are going to discuss about How to export the data as CSV from database in CodeIgniter. In CodeIgniter we can export data easily from database as CSV using a library called dbutil. We can pass the query result directly into the dbutil function and we can download the data as CSV.
In your model, write down a function called exportCSV as mentioned below.
function ExportCSV()
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$filename = "filename_you_wish.csv";
$query = "SELECT * FROM table_name WHERE 1";
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
force_download($filename, $data);
}
You can change the filename and the database query as per your needs. Call this function from your controller.
In your model, write down a function called exportCSV as mentioned below.
function ExportCSV()
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$filename = "filename_you_wish.csv";
$query = "SELECT * FROM table_name WHERE 1";
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
force_download($filename, $data);
}
You can change the filename and the database query as per your needs. Call this function from your controller.
PHP CMS Frameworks
May 25, 2015
Read more →
CakePHP
Populate dropdown values in Cakephp using AJAX
In this article, we are going to discuss about How to populate the dropdown values in Cakephp using AJAX. CakePHP is an open source web application framework. It follows the Model-View-Controller (MVC) approach and is written in PHP. CakePHP uses well-known software engineering concepts and software design patterns, such as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.
Step 1 :
Add the below code in your View File where you want to apply the Ajax Dropdown
<div id="zoneDiv"></div>
<script>
$(document).ready(function(){
$('#HotelCountryId').change(function(){
var countryID = $(this).val();
$.ajax({
dataType: "html",
type: "POST",
evalScripts: true,
url: '<?php echo Router::url(array('controller'=>'zones','action'=>'ajaxzone'));?>',
data: ({countryid:countryID}),
success: function (data, textStatus){
$("#zoneDiv").html(data);
}
});
});
});
</script>
Step 2 :
Add the below code in your Controller function from where you want to populate data
public function ajaxzone($id = null) {
// debug($this->request->data['countryid']);exit;
$this->layout = 'ajax';
$id = $this->request->data['countryid'];
if (!$this->Zone->exists($id)) {
throw new NotFoundException(__('Invalid zone'));
}
$options = array('conditions' => array('Zone.country_id' => $id));
$this->set('zones', $this->Zone->find('list', $options));
}
Step 3:
The view file of this function ajaxzone.ctp
<?php
echo $this->Form->input('zone_id', array('class'=>'form-control','placeholder'=>'State'));
?>
Step 1 :
Add the below code in your View File where you want to apply the Ajax Dropdown
<div id="zoneDiv"></div>
<script>
$(document).ready(function(){
$('#HotelCountryId').change(function(){
var countryID = $(this).val();
$.ajax({
dataType: "html",
type: "POST",
evalScripts: true,
url: '<?php echo Router::url(array('controller'=>'zones','action'=>'ajaxzone'));?>',
data: ({countryid:countryID}),
success: function (data, textStatus){
$("#zoneDiv").html(data);
}
});
});
});
</script>
Step 2 :
Add the below code in your Controller function from where you want to populate data
public function ajaxzone($id = null) {
// debug($this->request->data['countryid']);exit;
$this->layout = 'ajax';
$id = $this->request->data['countryid'];
if (!$this->Zone->exists($id)) {
throw new NotFoundException(__('Invalid zone'));
}
$options = array('conditions' => array('Zone.country_id' => $id));
$this->set('zones', $this->Zone->find('list', $options));
}
Step 3:
The view file of this function ajaxzone.ctp
<?php
echo $this->Form->input('zone_id', array('class'=>'form-control','placeholder'=>'State'));
?>
PHP CMS Frameworks
May 17, 2015
Read more →
Wordpress
Create a XML and JSON web service using WordPress
In this article, we are going to discuss about How to create a XML and JSON web service using Wordpress. WordPress started in 2003 with a single bit of code to enhance the typography of everyday writing and with fewer users than you can count on your fingers and toes. Since then it has grown to be the largest self-hosted blogging tool in the world, used on millions of sites and seen by tens of millions of people every day.
Create a wordpress page and call it json or whatever you like and then add a json.php file within your wordpress theme then add the code below.
<?php
/*
Template Name: json
*/
/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {
/* soak in the passed variable or set our own */
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
$user_id = intval($_GET['user']); //no default
/* connect to the db */
global $wpdb;
/* create one master array of the records */
$posts = array();
$the_query = new WP_Query( "author=$user_id&showposts=$number_of_posts" );
while ( $the_query->have_posts() ) : $the_query->the_post();
// add any extras that you would like to this array
$posts[] = array('title'=> get_the_title(),'content'=>get_the_content(),'link'=>get_permalink(get_the_ID()));
endwhile;
/* output in necessary format */
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
else {
header('Content-type: text/xml');
echo '<posts>';
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo '<',$key,'>';
if(is_array($value)) {
foreach($value as $tag => $val) {
echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
}
}
echo '</',$key,'>';
}
}
}
echo '</posts>';
}
/* reset query */
wp_reset_postdata();
}
http://example.co.uk/json/?user=1&num=3&format=json
Create a wordpress page and call it json or whatever you like and then add a json.php file within your wordpress theme then add the code below.
<?php
/*
Template Name: json
*/
/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {
/* soak in the passed variable or set our own */
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
$user_id = intval($_GET['user']); //no default
/* connect to the db */
global $wpdb;
/* create one master array of the records */
$posts = array();
$the_query = new WP_Query( "author=$user_id&showposts=$number_of_posts" );
while ( $the_query->have_posts() ) : $the_query->the_post();
// add any extras that you would like to this array
$posts[] = array('title'=> get_the_title(),'content'=>get_the_content(),'link'=>get_permalink(get_the_ID()));
endwhile;
/* output in necessary format */
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
else {
header('Content-type: text/xml');
echo '<posts>';
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo '<',$key,'>';
if(is_array($value)) {
foreach($value as $tag => $val) {
echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
}
}
echo '</',$key,'>';
}
}
}
echo '</posts>';
}
/* reset query */
wp_reset_postdata();
}
http://example.co.uk/json/?user=1&num=3&format=json
PHP CMS Frameworks
May 11, 2015
Read more →
Magento
Steps to setup Authorize.net Direct Post Method in Magento
In this article, we are going to discuss about How to integrate and setup the Authorize.net Direct post method in Magento. Authorize.net's Direct Post Method of payment gateway integration is a great option for Magento sites because it allows for a seamless customer experience while simplifying PCI compliance by keeping all sensitive credit card information off of the Magento server. Configuring Magento for use with Direct Post Method (DPM) is supposed to be quick and easy and it can be as long as you aware of a few less than obvious steps.
Step 1 :
Make sure that your Authorize.net account is a "Card Not Present" (CNP) account. You can confirm whether or not your Authorize.net account is setup for CNP transactions by logging in to the Merchant Account Admin and verifying that you have CNP features like Recurring Billing and Fraud Detection Suite listed in the Tools section.
If you do not see these options or you get errors like "Transactions of this market type cannot be processed on this system" when attempting to authorize payments, the issue is most likely that the account is setup for card present transactions only. If you are using a test account the easiest solution is to just create a new account and make sure to select Card Not Present.
Step 2 :
Make sure to set an MD5-Hash. DPM uses an MD5-Hash as a sort of secret key that is set in in the auth.net merchant admin and the Magento admin to help secure comminication between your magento store and auth.net. If during checkout, after entering credit card information and clicking "Place Order", you get a pop-up alert saying "Response hash validation failed. Transaction declined." the problem is most likely that this is not set.
Step 3 :
Set an MD5-Hash in the Authorize.net merchant admin under Settings > Security Settings > General Security Settings > MD5-Hash. Then enter that same value in the Magento Admin under System > Configuration > Payment Methods > Authorize.net Direct Post > Merchant MD5.
Step 4 :
Make sure that your server's time is set correctly. DPM makes use of a timestamp as a security measure and to help synchronize requests. If the server's time is incorrect you may receive a pop up stating "Gateway error: This transaction cannot be accepted." This is a generic error message. To get more specific error information you can go into app/code/core/Mage/Authorizenet/Model/Directpost.php and either log or dump $response in function process() by doing something like var_dump($reponse); die(); to output the response from auth.net.
If you get a response code 3 with a response reason code of 97 the timestamp value submitted in x_fp_timestamp is either 15 minutes ahead, or 15 minutes behind in Greenwich Mean Time (GMT) (this is the equivalent of 900 seconds ahead or 900 seconds behind in Coordinated Universal Time, or UTC). You can test your timestamps accuracy using this tool http://developer.authorize.net/tools/responsecode97/ .
On linux you can get the server time using the date command. If it is incorrect consider setting up Network Protocol Time by doing soething like this: http://alienlayer.com/install-and-configure-ntp-to-synchronize-the-system-clock-on-centos/
Step 5 :
Make sure to set the Gateway URL correctly. For test accounts Test Mode should be set to NO and the Gateway URL should be set to https://test.authorize.net/gateway/transact.dll. For Live accounts this should be chagned to https://secure.authorize.net/gateway/transact.dll
Other than that the configuration is pretty straightforward. In the Magento Admin the Authoize.net Direct Post configuration should look something like this:
I hope this helps get you up and running with this very simple and secure payment method. Please feel free to drop any questions in the comments.
Step 1 :
Make sure that your Authorize.net account is a "Card Not Present" (CNP) account. You can confirm whether or not your Authorize.net account is setup for CNP transactions by logging in to the Merchant Account Admin and verifying that you have CNP features like Recurring Billing and Fraud Detection Suite listed in the Tools section.
If you do not see these options or you get errors like "Transactions of this market type cannot be processed on this system" when attempting to authorize payments, the issue is most likely that the account is setup for card present transactions only. If you are using a test account the easiest solution is to just create a new account and make sure to select Card Not Present.
Step 2 :
Make sure to set an MD5-Hash. DPM uses an MD5-Hash as a sort of secret key that is set in in the auth.net merchant admin and the Magento admin to help secure comminication between your magento store and auth.net. If during checkout, after entering credit card information and clicking "Place Order", you get a pop-up alert saying "Response hash validation failed. Transaction declined." the problem is most likely that this is not set.
Step 3 :
Set an MD5-Hash in the Authorize.net merchant admin under Settings > Security Settings > General Security Settings > MD5-Hash. Then enter that same value in the Magento Admin under System > Configuration > Payment Methods > Authorize.net Direct Post > Merchant MD5.
Step 4 :
Make sure that your server's time is set correctly. DPM makes use of a timestamp as a security measure and to help synchronize requests. If the server's time is incorrect you may receive a pop up stating "Gateway error: This transaction cannot be accepted." This is a generic error message. To get more specific error information you can go into app/code/core/Mage/Authorizenet/Model/Directpost.php and either log or dump $response in function process() by doing something like var_dump($reponse); die(); to output the response from auth.net.
If you get a response code 3 with a response reason code of 97 the timestamp value submitted in x_fp_timestamp is either 15 minutes ahead, or 15 minutes behind in Greenwich Mean Time (GMT) (this is the equivalent of 900 seconds ahead or 900 seconds behind in Coordinated Universal Time, or UTC). You can test your timestamps accuracy using this tool http://developer.authorize.net/tools/responsecode97/ .
On linux you can get the server time using the date command. If it is incorrect consider setting up Network Protocol Time by doing soething like this: http://alienlayer.com/install-and-configure-ntp-to-synchronize-the-system-clock-on-centos/
Step 5 :
Make sure to set the Gateway URL correctly. For test accounts Test Mode should be set to NO and the Gateway URL should be set to https://test.authorize.net/gateway/transact.dll. For Live accounts this should be chagned to https://secure.authorize.net/gateway/transact.dll
Other than that the configuration is pretty straightforward. In the Magento Admin the Authoize.net Direct Post configuration should look something like this:

I hope this helps get you up and running with this very simple and secure payment method. Please feel free to drop any questions in the comments.
PHP CMS Frameworks
April 19, 2015
Read more →
YII
Export to Excel from Grid view in YII Framework 2.0
In this article, we are going to discuss about How to export the grid view data in to excel in YII Frameworkk 2.0. The Yii PHP project started on January 1, 2008, in order to fix some drawbacks of the PRADO framework.
For example, in its early versions PRADO was slow when handling complex pages, had a steep learning curve and many controls were difficult to customize, while Yii was much more efficient at that time. In October 2008, after ten months of private development, the first alpha version of Yii was released. On December 3, 2008, Yii 1.0 was formally released.
Step 1 : Install PHP Excel In Yiiframework 2.0
Add below line in composer.json and update composer to install phpoffice excel.
"require": {
......
"phpoffice/phpexcel": "*"
......
}
Step 2 : Excel Gridview Class In Yiiframework 2.0
Create a class file with name 'ExcelGrid.php' by extending the basic GridView class.
<?php
namespace app\components;
use Yii;
use Closure;
use yii\i18n\Formatter;
use yii\base\InvalidConfigException;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\widgets\BaseListView;
use yii\base\Model;
use \PHPExcel;
use \PHPExcel_IOFactory;
use \PHPExcel_Settings;
use \PHPExcel_Style_Fill;
use \PHPExcel_Writer_IWriter;
use \PHPExcel_Worksheet;
class ExcelGrid extends \yii\grid\GridView
{
public $columns_array;
public $properties;
public $filename='excel';
public $extension='xlsx';
private $_provider;
private $_visibleColumns;
private $_beginRow = 1;
private $_endRow;
private $_endCol;
private $_objPHPExcel;
private $_objPHPExcelSheet;
private $_objPHPExcelWriter;
public function init(){
parent::init();
}
public function run(){
//$this->test();
$this->init_provider();
$this->init_excel_sheet();
$this->initPHPExcelWriter('Excel2007');
$this->generateHeader();
$row = $this->generateBody();
$writer = $this->_objPHPExcelWriter;
$this->setHttpHeaders();
$writer->save('php://output');
Yii::$app->end();
//$writer->save('test.xlsx');
parent::run();
}
public function init_provider(){
$this->_provider = clone($this->dataProvider);
}
public function init_excel_sheet(){
$this->_objPHPExcel=new PHPExcel();
$creator = '';
$title = '';
$subject = '';
$description = 'Excel Grid';
$category = '';
$keywords = '';
$manager = '';
$created = date("Y-m-d H:i:s");
$lastModifiedBy = '';
extract($this->properties);
$this->_objPHPExcel->getProperties()
->setCreator($creator)
->setTitle($title)
->setSubject($subject)
->setDescription($description)
->setCategory($category)
->setKeywords($keywords)
->setManager($manager)
->setCompany($company)
->setCreated($created)
->setLastModifiedBy($lastModifiedBy);
$this->_objPHPExcelSheet = $this->_objPHPExcel->getActiveSheet();
}
public function initPHPExcelWriter($writer)
{
$this->_objPHPExcelWriter = PHPExcel_IOFactory::createWriter(
$this->_objPHPExcel,
$writer
);
}
public function generateHeader(){
$this->setVisibleColumns();
$sheet = $this->_objPHPExcelSheet;
$colFirst = self::columnName(1);
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
$this->_endCol++;
$head = ($column instanceof \yii\grid\DataColumn) ? $this->getColumnHeader($column) : $column->header;
$cell = $sheet->setCellValue(self::columnName($this->_endCol) . $this->_beginRow, $head, true);
}
$sheet->freezePane($colFirst . ($this->_beginRow + 1));
}
public function generateBody()
{
$columns = $this->_visibleColumns;
$models = array_values($this->_provider->getModels());
if (count($columns) == 0) {
$cell = $this->_objPHPExcelSheet->setCellValue('A1', $this->emptyText, true);
$model = reset($models);
return 0;
}
$keys = $this->_provider->getKeys();
$this->_endRow = 0;
foreach ($models as $index => $model) {
$key = $keys[$index];
$this->generateRow($model, $key, $index);
$this->_endRow++;
}
// Set autofilter on
$this->_objPHPExcelSheet->setAutoFilter(
self::columnName(1) .
$this->_beginRow .
":" .
self::columnName($this->_endCol) .
$this->_endRow
);
return ($this->_endRow > 0) ? count($models) : 0;
}
public function generateRow($model, $key, $index)
{
$cells = [];
/* @var $column Column */
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
} else {
$format = $column->format;
$value = ($column->content === null) ?
$this->formatter->format($column->getDataCellValue($model, $key, $index), $format) :
call_user_func($column->content, $model, $key, $index, $column);
}
if (empty($value) && !empty($column->attribute) && $column->attribute !== null) {
$value =ArrayHelper::getValue($model, $column->attribute, '');
}
$this->_endCol++;
$cell = $this->_objPHPExcelSheet->setCellValue(self::columnName($this->_endCol) . ($index + $this->_beginRow + 1),
strip_tags($value), true);
}
}
protected function setVisibleColumns()
{
$cols = [];
foreach ($this->columns as $key => $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
}
$cols[] = $column;
}
$this->_visibleColumns = $cols;
}
public function getColumnHeader($col)
{
if(isset($this->columns_array[$col->attribute]))
return $this->columns_array[$col->attribute];
/* @var $model yii\base\Model */
if ($col->header !== null || ($col->label === null && $col->attribute === null)) {
return trim($col->header) !== '' ? $col->header : $col->grid->emptyCell;
}
$provider = $this->dataProvider;
if ($col->label === null) {
if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) {
$model = new $provider->query->modelClass;
$label = $model->getAttributeLabel($col->attribute);
} else {
$models = $provider->getModels();
if (($model = reset($models)) instanceof Model) {
$label = $model->getAttributeLabel($col->attribute);
} else {
$label =$col->attribute;
}
}
} else {
$label = $col->label;
}
return $label;
}
public static function columnName($index)
{
$i = $index - 1;
if ($i >= 0 && $i < 26) {
return chr(ord('A') + $i);
}
if ($i > 25) {
return (self::columnName($i / 26)) . (self::columnName($i % 26 + 1));
}
return 'A';
}
protected function setHttpHeaders()
{
header("Cache-Control: no-cache");
header("Expires: 0");
header("Pragma: no-cache");
header("Content-Type: application/{$this->extension}");
header("Content-Disposition: attachment; filename={$this->filename}.{$this->extension}");
}
}
Add the above class in 'project/components' folder and defined namespace as
namespace app\components;
Step 3 : Gridview To Excel In Yiiframework 2.0
After completed above steps, Just you have to call 'ExcelGrid' widget using namespace to export data as excel in yii2.
Excel.php
<?php
\app\components\ExcelGrid::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//'extension'=>'xlsx',
//'filename'=>'excel',
'properties' =>[
//'creator' =>'',
//'title' => '',
//'subject' => '',
//'category' => '',
//'keywords' => '',
//'manager' => '',
],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'username',
'createdby',
'createdon',
],
]);
?>
Controller.php
<?php
............
class CategoryController extends Controller
public function actionExcel()
{
$searchModel = new categorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->renderPartial('excel', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionIndex()
{
$searchModel = new categorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
............
?>
For example, in its early versions PRADO was slow when handling complex pages, had a steep learning curve and many controls were difficult to customize, while Yii was much more efficient at that time. In October 2008, after ten months of private development, the first alpha version of Yii was released. On December 3, 2008, Yii 1.0 was formally released.
Step 1 : Install PHP Excel In Yiiframework 2.0
Add below line in composer.json and update composer to install phpoffice excel.
"require": {
......
"phpoffice/phpexcel": "*"
......
}
Step 2 : Excel Gridview Class In Yiiframework 2.0
Create a class file with name 'ExcelGrid.php' by extending the basic GridView class.
<?php
namespace app\components;
use Yii;
use Closure;
use yii\i18n\Formatter;
use yii\base\InvalidConfigException;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\widgets\BaseListView;
use yii\base\Model;
use \PHPExcel;
use \PHPExcel_IOFactory;
use \PHPExcel_Settings;
use \PHPExcel_Style_Fill;
use \PHPExcel_Writer_IWriter;
use \PHPExcel_Worksheet;
class ExcelGrid extends \yii\grid\GridView
{
public $columns_array;
public $properties;
public $filename='excel';
public $extension='xlsx';
private $_provider;
private $_visibleColumns;
private $_beginRow = 1;
private $_endRow;
private $_endCol;
private $_objPHPExcel;
private $_objPHPExcelSheet;
private $_objPHPExcelWriter;
public function init(){
parent::init();
}
public function run(){
//$this->test();
$this->init_provider();
$this->init_excel_sheet();
$this->initPHPExcelWriter('Excel2007');
$this->generateHeader();
$row = $this->generateBody();
$writer = $this->_objPHPExcelWriter;
$this->setHttpHeaders();
$writer->save('php://output');
Yii::$app->end();
//$writer->save('test.xlsx');
parent::run();
}
public function init_provider(){
$this->_provider = clone($this->dataProvider);
}
public function init_excel_sheet(){
$this->_objPHPExcel=new PHPExcel();
$creator = '';
$title = '';
$subject = '';
$description = 'Excel Grid';
$category = '';
$keywords = '';
$manager = '';
$created = date("Y-m-d H:i:s");
$lastModifiedBy = '';
extract($this->properties);
$this->_objPHPExcel->getProperties()
->setCreator($creator)
->setTitle($title)
->setSubject($subject)
->setDescription($description)
->setCategory($category)
->setKeywords($keywords)
->setManager($manager)
->setCompany($company)
->setCreated($created)
->setLastModifiedBy($lastModifiedBy);
$this->_objPHPExcelSheet = $this->_objPHPExcel->getActiveSheet();
}
public function initPHPExcelWriter($writer)
{
$this->_objPHPExcelWriter = PHPExcel_IOFactory::createWriter(
$this->_objPHPExcel,
$writer
);
}
public function generateHeader(){
$this->setVisibleColumns();
$sheet = $this->_objPHPExcelSheet;
$colFirst = self::columnName(1);
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
$this->_endCol++;
$head = ($column instanceof \yii\grid\DataColumn) ? $this->getColumnHeader($column) : $column->header;
$cell = $sheet->setCellValue(self::columnName($this->_endCol) . $this->_beginRow, $head, true);
}
$sheet->freezePane($colFirst . ($this->_beginRow + 1));
}
public function generateBody()
{
$columns = $this->_visibleColumns;
$models = array_values($this->_provider->getModels());
if (count($columns) == 0) {
$cell = $this->_objPHPExcelSheet->setCellValue('A1', $this->emptyText, true);
$model = reset($models);
return 0;
}
$keys = $this->_provider->getKeys();
$this->_endRow = 0;
foreach ($models as $index => $model) {
$key = $keys[$index];
$this->generateRow($model, $key, $index);
$this->_endRow++;
}
// Set autofilter on
$this->_objPHPExcelSheet->setAutoFilter(
self::columnName(1) .
$this->_beginRow .
":" .
self::columnName($this->_endCol) .
$this->_endRow
);
return ($this->_endRow > 0) ? count($models) : 0;
}
public function generateRow($model, $key, $index)
{
$cells = [];
/* @var $column Column */
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
} else {
$format = $column->format;
$value = ($column->content === null) ?
$this->formatter->format($column->getDataCellValue($model, $key, $index), $format) :
call_user_func($column->content, $model, $key, $index, $column);
}
if (empty($value) && !empty($column->attribute) && $column->attribute !== null) {
$value =ArrayHelper::getValue($model, $column->attribute, '');
}
$this->_endCol++;
$cell = $this->_objPHPExcelSheet->setCellValue(self::columnName($this->_endCol) . ($index + $this->_beginRow + 1),
strip_tags($value), true);
}
}
protected function setVisibleColumns()
{
$cols = [];
foreach ($this->columns as $key => $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
}
$cols[] = $column;
}
$this->_visibleColumns = $cols;
}
public function getColumnHeader($col)
{
if(isset($this->columns_array[$col->attribute]))
return $this->columns_array[$col->attribute];
/* @var $model yii\base\Model */
if ($col->header !== null || ($col->label === null && $col->attribute === null)) {
return trim($col->header) !== '' ? $col->header : $col->grid->emptyCell;
}
$provider = $this->dataProvider;
if ($col->label === null) {
if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) {
$model = new $provider->query->modelClass;
$label = $model->getAttributeLabel($col->attribute);
} else {
$models = $provider->getModels();
if (($model = reset($models)) instanceof Model) {
$label = $model->getAttributeLabel($col->attribute);
} else {
$label =$col->attribute;
}
}
} else {
$label = $col->label;
}
return $label;
}
public static function columnName($index)
{
$i = $index - 1;
if ($i >= 0 && $i < 26) {
return chr(ord('A') + $i);
}
if ($i > 25) {
return (self::columnName($i / 26)) . (self::columnName($i % 26 + 1));
}
return 'A';
}
protected function setHttpHeaders()
{
header("Cache-Control: no-cache");
header("Expires: 0");
header("Pragma: no-cache");
header("Content-Type: application/{$this->extension}");
header("Content-Disposition: attachment; filename={$this->filename}.{$this->extension}");
}
}
Add the above class in 'project/components' folder and defined namespace as
namespace app\components;
Step 3 : Gridview To Excel In Yiiframework 2.0
After completed above steps, Just you have to call 'ExcelGrid' widget using namespace to export data as excel in yii2.
Excel.php
<?php
\app\components\ExcelGrid::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//'extension'=>'xlsx',
//'filename'=>'excel',
'properties' =>[
//'creator' =>'',
//'title' => '',
//'subject' => '',
//'category' => '',
//'keywords' => '',
//'manager' => '',
],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'username',
'createdby',
'createdon',
],
]);
?>
Controller.php
<?php
............
class CategoryController extends Controller
public function actionExcel()
{
$searchModel = new categorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->renderPartial('excel', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionIndex()
{
$searchModel = new categorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
............
?>
PHP CMS Frameworks
April 15, 2015
Read more →
No more posts to load.
About this blog
PHPCMSFramework.com
Tutorials for WordPress, Laravel, Drupal, Joomla, Symfony & more — including AI-powered PHP guides. Publishing since 2012.
Trending posts
- Building a RAG System in Laravel from Scratch
- Steps to create a Contact Form in Symfony With SwiftMailer
- Build an AI Code Review Bot with Laravel — Real-World Use Case
- Build a WhatsApp AI Assistant Using Laravel, Twilio and OpenAI
- CIBB - Basic Forum With Codeigniter and Twitter Bootstrap
- Drupal 7 - Create your custom Hello World module
- Laravel and Prism PHP: The Modern Way to Work with AI Models
- Create Front End Component in Joomla - Step by step procedure
- A step by step procedure to develop wordpress plugin
- Symfony Framework - Introduction