What is “inheritance” in Javascript?

October 16, 2013 Leave a comment

In simple terms, inheritance is the concept of one thing gaining the properties or behaviours of something else. To say A inherits from B, is saying that A is a type of B. A Bird inherits from Animal because a Bird is a type of Animal – it can do the same things, but a little more (or differently)!

In JavaScript, this relationship is a little complicated to specify, but bear with the syntax. You must use a special object called prototype which assigns properties to a type such as Animal. Only functions have a prototype, which is why you must create a function first:

function Animal() {}; // This is the Animal *Type*

Animal.prototype.eat = function () {

alert(“All animals can eat!”);

};

Now to create a type that inherits from Animal, you also use the prototype object, but this time the one belonging to the other type, e.g. Bird:

function Bird() {}; // Declaring a Bird *Type*

Bird.prototype = new Animal(); // Birds inherit from Animal

Bird.prototype.fly = function() {

alert(“Birds are special, they can fly!”);

};

The effect of this is that any Birds you create (called an instance of Bird) all have the properties of Animals, but they also have the additional .fly():

var aBird = new Bird(); // Create an instance of the Bird Type

aBird.eat(); // It should alert, so the inheritance worked

aBird.fly(); // Important part of inheritance, Bird is also different to Animal

 

var anAnimal = new Animal(); // Let’s check an instance of Animal now

anAnimal.eat(); // Alerts, no problem here

anAnimal.fly(); // Error will occur, since only Birds have fly() in its prototype

Categories: Javascipt

Javascript how to parse JSON array

October 16, 2013 Leave a comment

Javascript has a built in JSON parse for strings,IMPORTANT: the JSON.parse method wont work in old old browsers.You can use parseJSON available in jQuery.

Consider the following example,

 

<!DOCTYPE html>
<html>
<head>
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”&gt;
</script>
<script>
var jscountry = ‘{“counters”:[‘+
‘{ “country”:”India”,”value” : “IN”},’+
‘{ “country”:”USA”,”value” : “US”}]}’;
var state = ‘{“IN” : [‘+
‘{ “txt”:”Tamil Nadu”,”value”:”TN” },{ “txt”:”Kerela”,”value”:”KL” }], “US” : [{ “txt”:”Newy York”,”value”:”NY” },{ “txt”:”Alabama”,”value”:”AL” }]}’;

var CountryData = jQuery.parseJSON(jscountry);
var optionsAsString = “”;

for (var i in CountryData.counters) {
var counter = CountryData.counters[i];
console.log(counter.country);
optionsAsString += “<option value='” + counter.value + “‘>” + counter.country + “</option>”;
}
jQuery(function(){
$(‘select#country’).append( optionsAsString );
$(‘select#country’).on(‘change’,function(){
$(‘select#state’).html( prepareState($(this).val()));
});
});

function prepareState(st){
var optionsAsString = “”;
var StateData = jQuery.parseJSON(state);
var _st = st;
for (var i in StateData[_st]) {
var counter = StateData[_st][i];
optionsAsString += “<option value='” + counter.value + “‘>” + counter.txt + “</option>”;
console.log(optionsAsString);
}
return optionsAsString;
}

</script>
</head>
<body>

<select id=”country”></select>
<select id=”state”><option value=””>Select Region</option></select>
</body>
</html>

Categories: Javascipt, jQuery

How to get handle of your controller in magento?

November 30, 2012 1 comment

To get handle of your controller, you will need some debugging techniques.
In action of your controller insert line:

Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles());
It works for admin and frontend cotrollers in a same way.
And your custom action will look something like this:
publicfunctionindexAction()
{
        $this->loadLayout();
        $this->renderLayout();
        Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles());
}
In your browsers output you will get something like this:
Frontend controller
array(5) {
  [0] => string(7) "default"
  [1] => string(13) "STORE_default"
  [2] => string(29) "THEME_frontend_default_hybrid"
  [3] => string(29) "companyname_developers_index_index"
  [4] => string(19) "customer_logged_out"
}
Admin controller:
array(4) {
  [0] => string(7) "default"
  [1] => string(11) "STORE_admin"
  [2] => string(30) "THEME_adminhtml_default_actionname"
  [3] => string(28) "adminhtml_switch_index_index"
}
Categories: Magento

How to create new page in Magento Module ?

November 30, 2012 1 comment

Some time we have more modules used in sites.Now we have the situation to list the overall best seller from the site in separate page.so this takes url like http://www.domain.com/module-front-name/controller/action.

We can able to write controller and action any module which we used in magento. suppose we have the module which is used to make csvconversion installed in site. we can use this module to create page to list the best seller. Choosing module based on task needs to have sense. But here i chose csvconversion module as an example only.

app–
code—
local—
CompanyName–
ModuleName(Csvconversion)—
Block–
Helper—
Controller–
etc—
config.xml

Every module should have basic folder structure like above with config.xml like,

<?xml version=”1.0″?>
<config>
<modules>
<Companyname_Csvconversion>
<version>0.1.0</version>
</Companyname_Csvconversion>
</modules>…

In config.xml we have to set front name as like we want. for example i want my url should be like http://www.domain.com/best/seller/index

Here best – Companyname_Csvconversion , seller – controller , index – action

We can able to define front name for the respective module in config.xml like

<frontend>
<routers>
<csvconversion>
<use>standard</use>
<args>
<module>Companyname_Csvconversion</module>
<frontName>best</frontName>
</args>
</csvconversion>
</routers>
<layout>
<updates>
<csvconversion>
<file>bestseller.xml</file>
</csvconversion>
</updates>
</layout>
</frontend>

Defining bestseller.xml under layout tag will tell the module to use this xml for layout files.

Now create SellerController.php under controller folder like

class Companyname_Csvconversion_SellerController extends Mage_Core_Controller_Front_Action {

public function indexAction() {
$this->loadLayout();
$this->renderLayout();
}
}

Now create bestseller.xml and put it in theme/layout/bestseller.xml like

<?xml version=”1.0″?>
<layout version=”0.1.0″>
<default>
</default>

<csvconversion_best_seller>
<reference name=”root”>
<action method=”setTemplate”>
<template>page/column-2right.phtml</template>
</action>
</reference>

<reference name=”content”>
<block type=”csvconversion/best” name=”bestseller”  as=”bestseller” template=”catalog/bestseller.phtml” />
</reference>
</csvconversion_best_seller>

</layout>

Here <block type=”csvconversion/best” … magento checks best.php from block folder.under block folder , we need to have best.php like

class Companyname_Csvconversion_Block_Best extends Mage_Core_Block_Template {

public function _prepareLayout() {
return parent::_prepareLayout();
}

public function getBestsellingProducts() {
// number of products to display
$productCount = 5;
$params = $this->getRequest()->getParams();
// store ID
$storeId = Mage::app()->getStore()->getId();

$category = new Mage_Catalog_Model_Category();

// get most viewed products for current category
$products = Mage::getResourceModel(‘reports/product_collection’)
->addAttributeToSelect(‘*’)
->addOrderedQty()
->setStoreId($storeId)
->addStoreFilter($storeId)
->setOrder(‘ordered_qty’, ‘desc’)
->setPageSize($productCount);

Mage::getSingleton(‘catalog/product_status’)
->addVisibleFilterToCollection($products);
Mage::getSingleton(‘catalog/product_visibility’)
->addVisibleInCatalogFilterToCollection($products);
return $products;
}

}

Now we need to have template file as like defined in bestseller.xml, under catalog folder , have bestseller.phtml like

<?php
$model = Mage::getModel(‘catalog/product’);
$_helper = $this->helper(‘catalog/output’);
$storeId = Mage::app()->getStore()->getId();
$catalog = $this->getLayout()->createBlock(‘catalog/product_list’)->setStoreId($storeId);
if ($this->getBestsellingProducts()->count() > 0) {
foreach ($this->getBestsellingProducts() as $value) {
$_product = $model->load($value[‘entity_id’]);

……// dessign the data as like you want here

}

}

we can call getBestsellingProducts in template file since we declare the block file as best in xml file.Now you can call url http://www.domain.com/best/seller/index to see the result.

By this way we can add page in magento module.

 

 

 

Categories: Magento

Add Product to Cart using Multi dimensional Array

September 12, 2012 Leave a comment

I have learned simple way of coding from one video which explains the CART functionility.I’d like to share the ideas here.

In online shopping site, we will have the cart functionality which is having Multi Dimensional Array using Session. For example, I have the List of products in product details page having Add to Cart button respectively. Every product has the unique identity which is called Product_Id or Item_id. Assume the we are getting required details from database. $id will hold product id from database

Let me explain with one product. Below is the code to show product with add to cart button.

<form id=”form1″ name=”form1″ method=”post” action=”cart.php”>
<input type=”hidden” name=”pid” id=”pid” value=”<?php echo $id; ?>” />
<input type=”submit” name=”button” id=”button” value=”Add to Shopping Cart” />
</form>

When user click add to cart button, form action will take to cart.php file. There we are going to process with Product ID.So under Cart.php file ,

Step1:

session_start(); // Start session first thing in script
Step2:

// Connect to the MySQL database   (Consider we have the code to connect mysql )
include “connect_to_mysql.php”;

Step3:

//(if user attempts to add something to the cart from the product page)

if (isset($_POST[‘pid’])) {
$pid = $_POST[‘pid’];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION[“cart_array”]) || count($_SESSION[“cart_array”]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION[“cart_array”] = array(0 => array(“item_id” => $pid, “quantity” => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION[“cart_array”] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == “item_id” && $value == $pid) {
// That item is in cart already so let’s adjust its quantity using array_splice()
array_splice($_SESSION[“cart_array”], $i-1, 1, array(array(“item_id” => $pid, “quantity” => $each_item[‘quantity’] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION[“cart_array”], array(“item_id” => $pid, “quantity” => 1));
}
}
header(“location: cart.php”);
exit();
}
?>

Step4:

// (if user chooses to empty their shopping cart)

<?php

if (isset($_GET[‘cmd’]) && $_GET[‘cmd’] == “emptycart”) {
unset($_SESSION[“cart_array”]);
}
?>

Step5:

//if user chooses to adjust item quantity

<?php

if (isset($_POST[‘item_to_adjust’]) && $_POST[‘item_to_adjust’] != “”) {
// execute some code
$item_to_adjust = $_POST[‘item_to_adjust’];
$quantity = $_POST[‘quantity’];
$quantity = preg_replace(‘#[^0-9]#i’, ”, $quantity); // filter everything but numbers
if ($quantity >= 100) { $quantity = 99; }
if ($quantity < 1) { $quantity = 1; }
if ($quantity == “”) { $quantity = 1; }
$i = 0;
foreach ($_SESSION[“cart_array”] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == “item_id” && $value == $item_to_adjust) {
// That item is in cart already so let’s adjust its quantity using array_splice()
array_splice($_SESSION[“cart_array”], $i-1, 1, array(array(“item_id” => $item_to_adjust, “quantity” => $quantity)));
} // close if condition
} // close while loop
} // close foreach loop
}
?>

Step6:

//if user wants to remove an item from cart

<?php

if (isset($_POST[‘index_to_remove’]) && $_POST[‘index_to_remove’] != “”) {
// Access the array and run code to remove that array index
$key_to_remove = $_POST[‘index_to_remove’];
if (count($_SESSION[“cart_array”]) <= 1) {
unset($_SESSION[“cart_array”]);
} else {
unset($_SESSION[“cart_array”][“$key_to_remove”]);
sort($_SESSION[“cart_array”]);
}
}
?>

Now we will have Cart product in $_SESSION[“cart_array”] Using this we can iterate to render the Cart page.

Categories: php

Match the current URI to set module, controller, action in Magento

September 3, 2012 Leave a comment

I have the situtation to set my custom name with base url. Suppose I have the url like http://www.test.com , now needed to add custom name like api. But magento will have to find the module with respection controller and action.

There is way to set our custom name with magento using router. We need to set Router.php file under any module/Controller folder.

getEvent()->getFront();
$helpers = new Mage4u_Helpers_Controller_Router();
$front->addRouter(‘front_name’, $helpers);
}

/**
* Attempt to match the current URI to this module
* If match found, set module, controller, action and dispatch
*
* @param Zend_Controller_Request_Http $request
* @return bool
*/
public function match(Zend_Controller_Request_Http $request)
{
$front = $this->getFront();
$identifier = trim($request->getPathInfo(), ‘/’);
if(substr($identifier, 0, strlen(‘api’)) == ‘api’){
$action = “api”;
$request->setModuleName(‘api’)
->setControllerName(‘index’)
->setActionName(trim($action, ‘/’))
->setParam(‘param’, $action);
return true;
}

}

/**
* Returns the current request object
*
* @return Zend_Controller_Request_Http
*/
protected function getRequest()
{
return $this->_requestObject;
}
}

Now you can call like http://www.test.com/api Magento will consider this module as api, controller as indexController, action as apiAction.

Categories: Magento Tags:

Detecting an undefined object property in JavaScript

September 3, 2012 Leave a comment

Use below code to prevent undefined error when using javascript

if (typeof something === "undefined") 
   alert("something is undefined");
Categories: Javascipt Tags:

Find Device type using Zend Framework

June 27, 2012 2 comments

I have situation to create site for both mobile and deskop. I found it could be possible in zend using WURFL.

Step 1

Download wurfl-php-1.1.tar.gz from here

Step 2

Create library folder under  project root directory.Extract wurfl-php-1.1.z.tar.gz file and put the wurfl-php-1.1 folder inside library folder.

Step 3

Create Folder “data/wurfl/cache/” under project root directory and give 777 permission to cache folder

Step 4

Copy the web_browsers_patch.xml file and wurfl-latest.zip file from the path  “library/wurfl-php-1.1/tests/resources/” and paste to “data/wurfl/”

Step 5

Create wurfl-config.php and put the file under application/configs/

<?php
$resourcesDir            = dirname(__FILE__) . ‘/../../data/wurfl/’;

$wurfl[‘main-file’]      = $resourcesDir  . ‘wurfl-latest.zip’;
$wurfl[‘patches’]        = array($resourcesDir . ‘web_browsers_patch.xml’);

$persistence[‘provider’] = ‘file’;
$persistence[‘dir’]      = $resourcesDir . ‘/cache/’;

$cache[‘provider’]       = null;

$configuration[‘wurfl’]       = $wurfl;
$configuration[‘persistence’] = $persistence;
$configuration[‘cache’]       = $cache;
?>

Step 6

Open application.ini file and add the following

resources.useragent.wurflapi.wurfl_api_version = “1.1”
resources.useragent.wurflapi.wurfl_lib_dir = APPLICATION_PATH “/../library/wurfl-php-1.1/WURFL/”
resources.useragent.wurflapi.wurfl_config_file = APPLICATION_PATH “/configs/wurfl-config.php”

Step 7

Now need to write plugin called Mobile.php  to find the device type under \library\ZC\Controller\Plugin

<?php

/**
* Description of Mobile
*
* @author Dinesh Kumar
*/
class ZC_Controller_Plugin_Mobile extends Zend_Controller_Plugin_Abstract {

public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {

$bootstrap = Zend_Controller_Front::getInstance()->getParam(“bootstrap”);
$useragent = $bootstrap->getResource(“useragent”);
$device = $useragent->getDevice();
Zend_Registry::set(“useragent”, $useragent);
Zend_Registry::set(“device”, $device);

/**
* @todo change this to be Mobile
*/
//echo $device->getType() . ” is the type of device”;
if ($device->getType() == “mobile”) {
/**
* Set the layout to be mobile, here we make sure we streamline what is loaded
* so as to not load things that arent needed.
*/
if ($request->getControllerName() == ‘admin’ && $request->getActionName() == ‘login’) {
Zend_Layout::getMvcInstance()->setLayout(“mobile_admin”);
} else {
Zend_Layout::getMvcInstance()->setLayout(“mobile”);
}
/**
* Here we check to see if a mobile version of the template exists.  if it does then we change the view suffix
* this allows us to load the mobile view if it exists and the defgault view if it doesnt.
*/
$base = APPLICATION_PATH . “/mobile/views/scripts/”;
$mobile = $base . $request->getControllerName() . “/” . $request->getActionName() . “.phtml”;
//Zend_Controller_Action_HelperBroker::getExistingHelper(‘ViewRenderer’)->setViewBasePathSpec($base .  $request->getControllerName() . “/”);

$this->bootstrap = Zend_Controller_Front::getInstance()->getParam(‘bootstrap’);
$view = $this->bootstrap->getResource(‘view’);

//add base path for layout overriding
$view->setScriptPath(NULL);
$view->setScriptPath(APPLICATION_PATH . ‘/mobile/views/scripts/’);
//use this ajax action
if($request->getActionName() == ‘logout’ || $request->getActionName() == ‘delete’ || $request->getActionName() == ‘downloadtransaction’)
Zend_Controller_Action_HelperBroker::getStaticHelper(“ViewRenderer”);
else
{
$html = $view->render($request->getControllerName() . “/” . $request->getActionName() . ‘.phtml’);

Zend_Controller_Action_HelperBroker::getExistingHelper(‘ViewRenderer’)->setViewBasePathSpec($request->getControllerName() . “/” . $request->getActionName() . ‘.phtml’);
}

}
}

}

Step 8

Add the following line in application.ini file

resources.frontController.plugins.Mobile = “ZC_Controller_Plugin_Mobile”
autoloaderNamespaces.zc    = “ZC_”

Step 9

Create layout  file called mobile.phtml and mobile_admin.phtml for admin login action under \application\layouts\scripts\

Step 10

Create folder under application\mobile\views\scripts  for putting mobile action template files, for example if we have billcontroller with indexAction  , we will have bill folder under  both \application\views\scripts\bill\index.phtml  and application\mobile\views\scripts\bill\index.phtml

Now you can check the site with both desktop browser and mobile browser  to see the different layout for the same url.

Categories: Zend

Hide DIV for few seconds using Jquery


Suppose we can display the success message in the DIV like

<div id=”message”> Successfully Sent…</div>

We are in need to hide the div after 5 second  – 5000 milliseconds. Use the following piece of  jquery in your <head> tag

setTimeout(function() {
$('#mydiv').fadeOut('fast');
}, 5000); // <-- time in milliseconds

This will hide the message after 5 seconds.

Categories: jQuery

First day of last month date function in PHP


I had chance to use this First day of last month  date function when developing the site. I was used the following

$lastmonthLastDay =   date('Y-m-d', strtotime("last day of last month"));
$lastmonthFirstDay= date('Y-m-d', strtotime("first day of -1 month"));

Which works only in PHP 5.3 not in PHP 5.2

To be more universe, we need to do it like ,

$firstDay = date('d-m-Y', mktime(0, 0, 0, date("m", strtotime("-1 month")), 1, date("Y",strtotime("-1 month"))));
$lastDay = date('d-m-Y', mktime(-1, 0, 0, date("m"), 1, date("Y")));

check this for more datails, mktime()  function returns the Unix timestamp for a date.

Categories: php