Friday 29 April 2016

Adding products to cart via url in magento

If your Planning to do a website that opens directly on the cart page, in the cart it needs to have some products already selected and it should be ready to go to the checkout page.

Every time the user goes to the page, some products.

<a href="http://example.com/index.php/checkout/cart/add/product/1/form_key/<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>/">My cart</a>

Wednesday 27 April 2016

How to add form alt message/text on custom payment method like Paypal in magento


When you Create a Custom Payment Method Module in Magento. Add form alt message/text on custom payment method like Paypal(You will be redirected to the PayPal website).

in app/code/local/Companyname/Custompayment/Model/Custompayment.php

class Companyname_Custompayment_Model_Custompayment extends Mage_Payment_Model_Method_Abstract
{
    .
    .
    .
    .
    protected $_formBlockType = 'custompayment/standard_form';
    .
    .
    .
    .
    public function __construct($params = array())
    {
        ............
    }
}

Create new form.php and paste the following contents in that file.
app/code/local/Companyname/Custompayment/Block/Standard/Form.php

class Companyname_Custompayment_Block_Standard_Form extends Mage_Payment_Block_Form
{
    protected function _construct()
    {
        $config = Mage::getModel('custompayment/config');
        $this->setTemplate('custompayment/payment/redirect.phtml')
            ->setRedirectMessage(
                Mage::helper('custompayment')->__('You will be redirected to the Custompayment website when you place an order.')
            )
            ->setMethodTitle('')
            ->setMethodLabelAfterHtml($config->getFieldValue('title'));
        parent::_construct();
    }
}

In this file,  we've set up a template file path which will be used when Magento show our payment method related Message/info. Let's create the related template file.

Create new redirect.phtml in app/design/frontend/base/default/template/custompayment/payment/redirect.phtml

<ul class="form-list" id="payment_form_<?php echo $this->getMethodCode() ?>" style="display:none;">
    <li class="form-alt"><?php echo $this->getRedirectMessage() ?></li>
</ul>

Tuesday 26 April 2016

Create dropdown/select box in magento system.xml for payment/shipping configuration

Create drop down in system.xml and show custom values in it, rather than using default magento classes only

Directory : app/code/local/Companyname/Modulename/config/system.xml

In system.xml

<config>
  <sections>
<payment>
  <groups>
<Modulename translate="label" module="Modulename">
<label>Payment Module</label>
       <sort_order>670</sort_order>
       <show_in_default>1</show_in_default>
       <show_in_website>1</show_in_website>
       <show_in_store>0</show_in_store>
<fields>
<paymentmethod translate="label comment">
   <label>Payment method</label>
   <comment>Omni Payment method.</comment>
   <frontend_type>select</frontend_type>
   <source_model>Modulename/Modelname</source_model>
   <sort_order>30</sort_order>
   <show_in_default>1</show_in_default>
   <show_in_website>0</show_in_website>
   <show_in_store>0</show_in_store>
</paymentmethod>
</fields>
</Modulename>
            </groups>
        </payment>
    </sections>
</config>

If you want to create your custom source_Model, you need to do the following steps: Create a Pmethod.php in app/code/local/Companyname/Modulename/Model/Pmethod.php Companyname_Modulename is our module name. You need to create a function name toOptionArray() as mention below, the value and label can be anything you want to be display in dropdown

In Pmethod.php 

class Companyname_Modulename_Model_Pmethod
{
    public function toOptionArray()
    {
        return array(
            array(
                'value' => 'key1',
                'label' => 'Label 1',
            ),
            array(
                'value' => 'key2',
                'label' => 'label 2',
            )
        );
    }
}

CURL Work in magento code using Varien_Http_Adapter_Curl with PHP and Magento example


Magento Example

PHP CURL library is used to fetch third party contents, transfer files and post data. Magento Wraps the CURL Functions in its library with its own wrapper functions. There is no Hard and Fast Rule that we need to only use this function, but the magento core code makes use of this library. Varien_Http_Adapter_Curl class is responsible for providing the wrapper functions.

$clienturl = 'https://www.omnipaymentapi.com/backoffice/tools/status.php';
$jsonData = array(
               "firstdata"=>'firstdata',
               "seconddata"=>'seconddata'
               );
$http = new Varien_Http_Adapter_Curl();
$config = array('timeout' => 30,'header'=>false); # Or whatever you like!
$http->setConfig($config);
$http->write(Zend_Http_Client::POST, $clienturl, '1.1', array(), $jsonData);
$response = $http->read();
$http->close();
$xml  = new SimpleXMLElement($response);
echo '<pre>';print_r($xml);exit;

The above code fetches the lastest information on magento blog in xml format. The $curl->write function accepts the method name (GET,POST), URL,HTTP version,headers,body etc. The $curl->read function will execute the curl_exec() internally.

 PHP Example


$ch = curl_init(); // use curl to connect
$targetURL = "https://www.omnipaymentapi.com/backoffice/tools/status.php";
$data = array(
               "firstdata"=>'firstdata',
               "seconddata"=>'seconddata'
               );
//echo 'test';exit;
curl_setopt($ch, CURLOPT_URL, $targetURL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);

Wednesday 20 April 2016

How to enable error and exception logging log in magento

By default, Magento does not enable messages about errors and exceptions logging; so if something bad happens, you don't even know.
To turn on the logging, you can change to
System > Configuration > Developer > Log Settings and set the «Enabled» option to «Yes»
Don't forget to set full access permissions (777) of following folder: /var/log, since that is the place where those log files are stored.

Monday 18 April 2016

How to get user ip in PHP/Codeigniter

$_SERVER['REMOTE_ADDR'] may not actually contain real client IP addresses, as it will give you a proxy address for clients connected through a proxy, for example. That may well be what you really want, though, depending what your doing with the IPs. Someone's private RFC1918 address may not do you any good if you're say, trying to see where your traffic is originating from, or remembering what IP the user last connected from, where the public IP of the proxy or NAT gateway might be the more appropriate to store.

There are several HTTP headers like X-Forwarded-For which may or may not be set by various proxies. The problem is that those are merely HTTP headers which can be set by anyone. There's no guarantee about their content. $_SERVER['REMOTE_ADDR'] is the actual physical IP address that the web server received the connection from and that the response will be sent to. Anything else is just arbitrary and voluntary information. There's only one scenario in which you can trust this information: you are controlling the proxy that sets this header. Meaning only if you know 100% where and how the header was set should you heed it for anything of importance.

For Codeigniter


$this->input->ip_address();

For PHP

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}
echo $ip;

Saturday 16 April 2016

Hide first default load div (Avoiding expressions) shown on page load in angularjs

As the others mentioned, use ng-cloak but also add the following to your CSS if it is the first to load in your page.

[ng\:cloak],[ng-cloak],.ng-cloak{display:none !important}
This will ensure that your div template is hidden. Below that div template, add something like

Loading...
The assignment of the $root.initializing.status with cause a true value for ng-hide.

<tr class="ng-cloak" dir-paginate="product in products">
             .........
             .........
             .........
</tr>

How to ignore chmod/permission of files and directory changes on git/bitbucket

if you want a git/bitbucket repository to ignore permission changes (chmod),
type the following command into the Terminal while inside the git/bitbucket repository:

git config core.filemode false
It is usually possible to do this for all git repositories at once, instead of going one-by-one.
This is done by using the following command inside the Terminal (no need to be inside a git repository for this command):

git config --global core.filemode false

Thursday 14 April 2016

Magento Interview Questions and Answers

Q 1. What is Magento?
Ans. Magento is a feature-rich eCommerce platform built on open-source technology that provides online merchants with unprecedented flexibility and control over the look, content and functionality of their eCommerce store. Magentos intuitive administration interface features powerful marketing, search engine optimization and catalog-management tools to give merchants the power to create sites that are tailored to their unique business needs. Designed to be completely scalable and backed by Variens support network, Magento offers companies the ultimate eCommerce solution.
Q 2. What is the difference between Mage::getSingletone() andMage::getModel() in Magento
Ans. Mage::getSingletone() always finds for an existing object if not then create that a newobject but Mage::getModel() always creates a new object.
Q 3. Why Magento use EAV database model ?
Ans. In EAV database model, data are stored in different smaller tables rather than storing in asingle table.product name is stored in catalog_product_entity_varchar tableproduct id is stored in catalog_product_entity_int tableproduct price is stored in catalog_product_entity_decimal tableMagento Use EAV database model for easy upgrade and development as this model givesmore flexibility to play with data and attributes.
Q 4. How to upgrade to the latest version using Magento Connect?
Ans. Upgrading Magento to the latest version is a fairly simple task. Copy and Paste this key magento-core/Mage_All_Latest VIA Magento Connect where it states Paste extension key to install:. This will upgrade Magento to the newest version.
Q 5. Explain about the Modules of Magento?
Ans. Magento supports installation of modules through a web-based interface accessible through the administration area of a Magento installation. Modules are hosted on the Magento eCommerce website as a PEAR server. Any community member can upload a module through the website and is made available once confirmed by a member of the Magento team. Modules are installed by entering a module key, available on the module page, into the web based interface.
There are three categories of modules hosted on Magento Connect:
    Core Modules
    Community Modules
    Commercial Modules
Core and Community modules can be installed via the administration area. Commercial module pages provide price information and a link to an external website.
Q 6. What technology used by Magento?
Ans. Magento uses PHP as a web server scripting language and the MySQL Database. The data model is based on the Entity-attribute-value model that stores data objects in tree structures, thus allowing a change to a data structure without changing the database definition.
Q 7. What is MVC structure in Magento?
Ans. The Model-View-Controller (MVC) architecture traces its
origins back to the Smalltalk Programming language and Xerox
Parc. Since then, there have been many systems that describe
their architecture as MVC. Each system is slightly
different, but all have the goal of separating data access,
business logic, and user-interface code from one another.
Q 8. What is benefit of namespace (package) in magento?
Ans. We can have more than one module with same name but they should be placed in different namespaces. All magento core modules are contained in mage namespace.
core/Mage/Catalog
and all custom modules are placed in
local/CustomModule
Q 9. How to include CMS block in template file(.phtml)?
Ans. Access block’s content from .phtml template file by :
echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘static_block_id’)->toHTML();
Q 10. How to add an external javascript/css file to Magento?
Ans.
css/yourstyle.css
or
skin_jsjs/ yourfile.js
skin_csscss/yourstyle. css
Q 11. What are handles in magento (layout)?
Ans. Handles are basically used for controlling the structure of the page like which block will be displayed and where. First level child elements of the node are called layout handles. Every page request can have several unique Handles. The handle is called for every page. handle for products belongs to virtual product type, PRODUCT_TYPE_simple is called for product details page of simple product type and PRODUCT_TYPE_virtual is called for the virtual product detail page and customer_logged_in handle is called only if customer is logged in. The muster_index_index handle is created by combining the frontName (muster), Action Controller (index), and Action Controller Action Method (index) into a single string and this handle will be called only when /zag/index/index url is accessed.
Q 12. What is in magento?
Ans. The routers tag allow us to decide frontname for each module. The tag is defined in config.xml file of module. For Namespace_MyModule frontname is moduleurl so the url will be like :
websiteurl.com/moduleurl/controllername/actionname
standard
Namespace_MyModule
moduleurl
Q 13. Which factors affect performance of magento?
Ans.
1. EAV structure of magento database, even for retrieving single entity the query becomes very complex .
2. Magento’s template system involves a lot of recursive rendering
3. Huge XML trees built up for layout configuration, application configuration settings
Q 14. How to improve magento performance?
Ans.
Enabled magento caching
MySQL Query caching
Enable Gzip Compression
Disable any unused modules
Disable the Magento log
Optimise your images
Combine external CSS/JS into one file
Enable Apache KeepAlives: Make sure your Apache configuration has KeepAlives enabled.
Q 15. How to get the Total Price of items currently in the Cart?
Ans. helper(‘checkout’)->formatPrice(Mage::getSingleton(‘checkout/cart’)->getQuote()->getGrandTotal()); ?>
Q 16. How to set different themes for logged in users?
Ans. if(Mage::getSingleton(‘customer/session’)->isLoggedIn()):
Mage::getDesign()->setPackageName(‘package_name’)->setTheme(‘themename’);
endif;
Q 17. How to create magento custom module?
Ans. Steps to create custom magento module:
Namespace : Zag
Module Name : Mymodule
1. Create directory Mymodule in app/code/local/Zag
2. Create Block, controllers, etc, Module directories. Create controller, block and module file as required.
3. Create module configuration file (app/code/local/Zag/Mymodule/etc/config.xml).
4. Create xml file (app/etc/modules/Zag_ Mymodule.xml)to enable/disable module and tell magento system from which code pool that module will be taken.
Q 18. How to set different themes for each store?
Ans. Go to : System>Designs
Then, add new design change or edit existing. You can select Store and Custom Design.
Q 19. How to make product’s custom attribute searchable in adavance search?
Ans. Go to : Catalog > Attribues > Manage Attribues
Edit the attribute and select “Yes” for Use in Advanced Search.
Q 20. How to fetch 5 bestsellers products programmatically?
Ans.
Mage::getResourceModel(‘reports/product_collection’)
->addOrderedQty()
->addAttributeToSelect(‘*’)
->setPage(1, 5)
->load();
Q.21-Explain Magento’s MVC architecture
Ans. First of all, what is MVC?
MVC stands for Model-View-Controller. Any application that separates it’s data access, business logicand user interface is called MVC. There can be two types of MVC: convention-based andconfiguration-based. Example, cakePHP is convention-based, i.e. you just need to follow the instructions of the core system to get your module ready in just few lines. Magento is configuration-based, i.e. you need to specify each and every thing to your module’s config file in order to get it work. Magento has Controller (for Routing), Block (for Business Logic), Model (for DB access, sql) and Template file (for Presentation i.e. View).
How Magento’s MVC works:
1. When you enter the URL (something like http://mysite.com/frontname/controller/method/param1/value1/param2/value2), this URL is intercepted by one PHP file called index.php which instantiates Magento application
2. Magento application instantiates Front Controller object
3. Further, front controller instantiates Router objects (specified in module’s config.xml, global tag)
4. Now, Router is responsible to “match” the frontname which is in our URL
5. If “match” is found, it sees controller name and method name in the URL, which is finally called.
6. Now depending on what is written in action name (method name), it is executed. If any models are called in it, the controller method will instantiate that model and call the method in it which is requested.
7. Then the controller action (method) instantiate the Layout object, which calls Block specified for this action (method) name (Each controller action name have block and template file associated with it, which can be found at app/design/frontend or adminhtml/namespace/module/layout/module.xml file, name of layout file (module.xml) can be found in config.xml of that module, in layout updates tag).
8. Template file (.phtml) now calls the corresponding block for any method request. So, if you write $this->methodName in .phtml file, it will check “methodName” in the block file which is associated in module.xml file.
9. Block contains PHP logic. It references Models for any data from DB.
10. If either Block, Template file or Controller need to get/set some data from/to database, they can call Model directly like Mage::getModel(‘modulename/modelname’).

Q.22 How Magento ORM works?
Ans. ORM stands for Object Relational Mapping. It’s a programming technique used to convert different types of data to Objects and vice versa.
In Magento, ORM is shown as Model (based on Zend Framework’s Zend_Db_Adapter), which further breaks down to two types of Models.
- First is the “simple” i.e. Regular Models which is nothing but flat table or our regular table structure.
- Second Model is EAV (Entity Attribute Value), which is quite complicated and expensive to query.
All Magento Models interacting with database are inherited from Mage_Core_Model_Abstract class, which is further inherited from Varien_Object.
Difference between two Models is, Simple Model is inherited from Mage_Core_Model_Resource_Db_Abstract class,
while EAV is inherited from Mage_Eav_Model_Entity_Abstract.
For those who don’t know what EAV is, please read my 3rd answer below.
So, to end up this question,
when you want to get some data in Magento, you call it like this:
Mage::getModel('module/model')->load(1);
where 1 is the primary key id for some Regular/Simple table, while in EAV so many tables are joined to fetch just single row of data.

23. What is EAV in Magento?
Ans. EAV, stands for Entity Attribute Value, is a technique which allows you to add unlimited columns to your table virtually. Means, the fields which is represented in “column” way in a regular table, is represented in a “row” (records) way in EAV. In EAV, you have one table which holds all the “attribute” (table field names) data, and other tables which hold the “entity” (id or primary id) and value (value for that id) against each attribute.
In Magento, there is one table to hold attribute values called eav_attribute and 5-6 tables which holds entity and data in fully normalized form,
- eav_entity, eav_entity_int (for holding Integer values),
- eav_entity_varchar (for holding Varchar values),
- eav_entity_datetime (for holding Datetime values),
- eav_entity_decimal (for holding Decimal/float values),
- eav_entity_text (for holding text (mysql Text type) values).
EAV is expensive and should only be used when you are not sure about number of fields in a table which can vary in future. To just get one single record, Magento joins 4-5 tables to get data in EAV. But this doesn’t mean that EAV only has drawbacks. The main advantage of EAV is when you may want to add table field in future, when there are thousands or millions of records already present in your table. In regular table, if you add table field with these amount of data, it will screw up your table, as for each empty row also some bytes will be allocated as per data type you select. While in EAV, adding the table column will not affect the previously saved records (also the extra space will not get allocated!) and all the new records will seamlessly have data in these columns without any problem.
24. Difference between Mage::getSingleton() and Mage::getModel()
The difference between Mage:getSingleton() and Mage::getModel() is that the former one does not create an object if the object for same class is already created, while the later creates new objects every time for the class when it’s called.
Mage::getSingleton() uses the “singleton design pattern” of PHP. If the object is not created, it will create it.
Mage::getSingleton() is mostly used when you want to create an object once, modify it and later fetch from it. Popular example is session, you first create a session object, and then add/remove values from session across different pages, so that it retains your values (e.g. cart values, logged in customer details, etc.) and doesn’t create new session object losing your last changes.
Mage::getModel() is used when you want to have the fresh data from the database. Example is when you want to show records from database.

Monday 11 April 2016

Today's/Month sales report on admin dashboard in magento

The sales report is one of the main progress indicators in e-commerce. We often create a sales report using the default Magento features – just go to Reports -> Sales -> Orders, and then, fill in the filter form on that page. This way allows us to get full information about sales on the web store.

Nevertheless, getting back to all these actions every time is not handy, especially if we do not need the full report. So, let’s find out how to display the reports in different parts in the admin panel.

First of all, we add a part of the code that will display our report on the dashboard in the admin panel – so, to do this place the following code snippet to
[Magento root]/app/design/adminhtml/default/default/template/dashboard/index.phtml:

<div class="entry-edit cmsdas-1 todaysale">
                <div class="cms-entry-edit-head">
                <div class="lifetime-sales"><?php echo "Today's sales"  ?></div>
                    <div class="cms-va">
                        <span class="price"><?php echo Mage::helper('NAMESPACE_MODULE/todaysale')->getTotals();?></span>
                    <span style="font-size:14px; color:#686868;">
                    </span>
                    </div>
                </div>
            </div>
In this code snippet we have a standard markup and use custom helper Mage::helper('NAMESPACE_MODULE/todaysale')->getTotals(). In this case, the helper returns an information about the report.

Pay attention to the code helper which generates information about the report. Here are several methods that build the report.

class NAMESPACE_MODULE_Helper_Todaysale extends Mage_Core_Helper_Abstract {
    public function getTotals() {
       
        $isFilter= '';
        $todaysales = Mage::getResourceModel('reports/order_collection')
            ->calculateSales($isFilter);
        $todayStartOfDayDate  = Mage::app()->getLocale()->date()
            ->setTime('00:00:00')
            ->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
        //$todayStartOfDayDate ='2016-04-7 00:00:00';
        $todayEndOfDayDate  = Mage::app()->getLocale()->date()
            ->setTime('23:59:59')
            ->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
       
        $todaysales->addAttributeToFilter('created_at', array(
            'from'  => $todayStartOfDayDate,
            'to'    =>  $todayEndOfDayDate,                  
        ));
        $todaysales->load();
        $todaysale = $todaysales->getFirstItem();
        //$this->addTotal($this->__("Today's Sales"), $todaysale->getLifetime());
        return (string)Mage::helper('core')->currency($todaysale->getLifetime(), true, false);
    }
}

Enable template path hint in admin Panel - Magento

There are two ways to enable admin panel path hints.

1.
You can enable template and block path hints in every store (including the admin store) by setting them in the Magento configuration. To do this, simply edit your module's configuration file app/etc/config.xml (which gets injected into Magento's global configuration).

To enable template and block path hints in the admin area add this to your app/etc/config.xml file
<config>

    ...

    <stores>
        <admin>
            <dev>
                <debug>
                    <template_hints>1</template_hints>
                    <template_hints_blocks>1</template_hints_blocks>
                </debug>
            </dev>
        </admin>
    </stores>
</config>
To disable path hints simply change to 0, or delete the node.

2.

You can do it by changing the database directly. If you have something like phpMyAdmin that is a good way to gain access. Enter this SQL.

INSERT INTO `core_config_data` (`scope`, `scope_id`, `path`, `value`)
       VALUES ('websites', '0', 'dev/debug/template_hints', '1');

When you are done with path hints just delete the matching record from core_config_data Or update the value field to 0 instead of deleting the whole record, it will probably be the last one since you've just added it.

Saturday 9 April 2016

How to get last week' date range in PHP, Codeigniter, CakePHP

$previous_week = strtotime("-1 week +1 day");
$start_week = strtotime("last sunday midnight",$previous_week);
$end_week = strtotime("next saturday",$start_week);
$start_week = date("Y-m-d",$start_week);
$end_week = date("Y-m-d",$end_week);
echo $start_week.' '.$end_week ;

Monday 4 April 2016

How to add 00 after a number in php

$value = 100.25;
echo number_format($value, 2);

Curl automatically display the result? / Without print, response is displayed me in CURL php

By default, the curl extension prints out the result.
You need to enable the CURLOPT_RETURNTRANSFER option, like so:

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

After that option is enabled, curl_exec will return the result, instead.