Drupal
Create custom theme in Drupal 8
In this tutorial we are going to discuss about, How to create custom theme (template) in Drupal 8 PHP CMS. By creating custom theme, we can customize the look and feel of the website as per our wish instead of using the pre-defined template or third party templates.
To create a new template, we have to follow the following steps.
To create a new template, we have to follow the following steps.
- Create YAML (.yml) file
- Edit YAML (.yml) file
- Remove stylesheets
- Clear the cache
- Optimize the Website
- Add CSS
- Add Javascript
Step 1: Create YAML (.yml) file
In Drupal 8, YAML file (.yml) is used in the place of .INFO files (used in Drupal 7) to tell the website that the theme exists. Similarly, the directories that contain the theme and the files with theme details have also been changed.
- Create a folder with the theme name which we are going to create like (first_theme) inside the <root>/theme folder.
- Create a new file inside the folder with the name first_theme.info.yml.
Step 2: Edit YAML file
Open the YAML file in your preferred text editor and enter the following details:
name: first_theme
description: Enter some description about your template
type: theme
core: 8.x
Type is theme and core is the version of Drupal you are creating the theme for (In this is case it is Drupal 8, so 8.x).
Now go to your Drupal website and check if the new theme appears in the Drupal appearance section. If all the steps have been correctly followed, the theme will appear in the uninstalled section of your website’s appearance tab.
Click install and set as default to set this theme as default.
Step 3: Remove Stylesheets (Optional)
After you have set the new theme as default, and then navigate to the website’s homepage, you will notice that nothing has changed. This is because Drupal includes several stylesheets that loads by default. In many cases, the best strategy is to disable some of these stylesheets.
To find out these stylesheets, you will need to inspect the source code by right-clicking and selecting View Source from the context menu and determine which CSS files you wish to remove, the rest of the process is pretty straightforward.
Go back to the first_theme.info.yml file and edit it. To remove the stylesheets you want, add this text:
stylesheets-remove
-“stylesheet to be removed”
Step 4: Clear the Cache
Now login to your Drupal website’s admin panel. Next, go to Configuration >> Performance and click Clear all caches.
Step 5: Optimize the Website
Next, go back to the Performance page and uncheck Aggregate CSS files and Aggregate JavaScript files in the Bandwidth Optimization section. This will help in speeding up the performance of the website.
Step 6: Add CSS
It is time to add reference to the CSS file that will be used for/by the theme. To do this, go to the theme’s folder and create a new file named first_theme.libraries.yml and update the file with css files which we are going to use in the theme.
global-css:
css:
theme:
css/style.css:{}
Now, add the library in the first_theme.info.yml file as well. To do this, add the below code in the file.
libraries:
-first_theme/global-css
Step 7: Add JavaScript Reference
To add reference to the JavaScript reference to the theme, add the below code snippet to the first_theme.libraries.yml file.
global-js:
js:
js/site.js:{}
dependencies:
-core/jquery
Now, add the the JavaScript library in the first_theme.info.yml file.
-first_theme/global-js
Finally the first_theme.info.yml will looks like below,
name: first_theme
description: Enter some description about your template
type: theme
core: 8.x
libraries:
-first_theme/global-css
-first_theme/global-js
PHP CMS Frameworks
September 09, 2018
Read more →
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 →
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
- CIBB - Basic Forum With Codeigniter and Twitter Bootstrap
- Building an Offline AI App with Laravel and Ollama
- Build an AI-Driven personalisation engine in Joomla using User Behaviour data
- Building a RAG System in Laravel from Scratch
- Steps to create a Contact Form in Symfony With SwiftMailer
- Drupal 7 - Create your custom Hello World module
- Build an AI Code Review Bot with Laravel — Real-World Use Case
- Symfony Framework - Introduction
- Laravel and Prism PHP: The Modern Way to Work with AI Models
- Prototype Javascript validation in Magento forms