Custom column with filter on admin grid in magento

Recently, I have worked on magento admin grid and I want to add custom column with filter on customer grid without adding column in customer table. I have faced lot of issue during this development and after digging continuously 2 hour I found terms addExpressionAttributeToSelect  . This is finally solved my problem.

I did customization on _prepareCollection function and  _prepareColumns function .It worked fine.

In _prepareCollection function, add below expression after getting the $collection

$collection->addExpressionAttributeToSelect('column_column', new Zend_Db_Expr("CUSTOM_MYSQL_EXPRESSSION"), array());

And add following column code in _prepareColumn method.

$this->addColumn('custom_column', array(
'header' => Mage::helper('customer')->__('CUSTOM COLUMN'),
'index' => 'custom_column',
));

Magento : Custom Stock Status

In Magento, once I was working Product Detail page, and used to see, status of a Product “In Stock” or “Out of Stock” What I want was to modify these Stock status messages, and go through all of the admin but don’t get any column there to modify these messages, but later on I find out solution in below manner, Please check it out –

You should have some basic knowledge of using FTP –

Open your FTP, and go through the below given path –

/app/design/frontend/{your_package}/{your_theme}/template/catalog/product/view/type/availability/default.phtml

Here your_package is package used by your Magento setup, and your_theme is a theme assigned to the magento.

open file, here you will see that “In Stock” and “Out of Stock” are written in a different conditions, Just change these string according to you –

$_product = $this->getProduct(); ?>
<?php if ($this->displayProductStockStatus()): ?>
    <?php if ($_product->isAvailable()): ?>
        <p class="availability in-stock">
            <span class="label"><?php echo $this->helper('catalog')->__('Availability:') ?></span>
            <span class="value"><?php echo $this->helper('catalog')->__('In stock') ?></span>
        </p>
    <?php else: ?>
        <p class="availability out-of-stock">
            <span class="label"><?php echo $this->helper('catalog')->__('Availability:') ?></span>
            <span class="value"><?php echo $this->helper('catalog')->__('Out of stock') ?></span>
        </p>
    <?php endif; ?>
<?php endif; ?>

Magento : Product stock quantity

From here you can get any product’s stock  quantity information like quantity (qty), minimum quantity (min_qty), stock availability (is_in_stock), minimum and maximum sale quantity (min_sale_qty and max_sale_qty).

Load Product

For that you need to load product. There are two ways to load product

1. Load by product id

$id = 12; // put custom product_id
$_product = Mage::getModel('catalog/product')->load($id);

2. Load by Product Sku

$sku = "bloga2bizz"; //custom product sku
 $_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);

 

Get Product stock information

$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product);

You can check stock data in following way:-

echo "<pre>"; print_r($stock->getData()); echo "</pre>";

or

echo $stock->getQty();
echo $stock->getMinQty();
echo $stock->getMinSaleQty();

Magento : Fetch products with layered navigation programmatically in custom php file

 Buy cheap and genuine Windows 7 product key  |
 Windows 7 Product Key for Windows 32bit/64bit Updated 2016y  |
 Windows 7 Ultimate ISO download  |
 Windows 7 Product Key Generator 32 bit and 64 bit Full  |
 Legit Windows 7 Product Key Online Store, PayPal Support  |
 Windows 7 Ultimate with Service Pack 1 Product Key,Windows 7 Key Sale  |
 Windows 7 Key  |
 Get Free Windows 7 Product Key  |
windows-10-education-key
windows-10-enterprise-key
office-2010-key
windows-7-key-sale
windows-10-home-key
windows-10-activation-key
windows-10-pro-key
office-2016-key
windows-10-key
office-2013-key
windows-10-iso
windows-7-key
windows-10-product-key

Here is way to fetch products with layered navigation programmatically in custom php file.

<?php
require_once('app/Mage.php'); //Must have file to begin
 
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); //Initialize store
 
$catId = Mage::app()->getRequest()->getParam('categoryId'); //Pass categoryId in get variable
    $storeId = Mage::app()->getWebsite(true)->getDefaultGroup()->getDefaultStoreId();
    $page_no = Mage::app()->getRequest()->getParam('page_no');
    $params = Mage::app()->getRequest()->getParams(); //Pass attributes in key=>value form to filter results.
    $category = Mage::getModel('catalog/category')->load($catId);
 
    $layer = Mage::getModel("catalog/layer");
    $layer->setCurrentCategory($category);
    $attributes = $layer->getFilterableAttributes(); //get all filterable attributes available in selected category layered navigation
    $attr = array();
    foreach ($attributes as $attribute) {
        if ($attribute->getAttributeCode() == 'price') {
            $filterBlockName = 'catalog/layer_filter_price';
        } elseif ($attribute->getBackendType() == 'decimal') {
            $filterBlockName = 'catalog/layer_filter_decimal';
        } else {
            $filterBlockName = 'catalog/layer_filter_attribute';
        }
        $attr[$attribute->getAttributeCode()] = $attribute->getFrontendLabel();
 
    }
    $filters = array_intersect_key($params, $attr);
    $collection = $category->getProductCollection()
                    ->addAttributeToFilter(
                        'status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
                    ->addAttributeToSelect('*');
    foreach ($filters as $key => $value) {
        if($key == 'price'){
            $priceFilter = explode('-', $value);
            $collection->addAttributeToFilter('price', array('gteq' => $priceFilter[0]));
            $collection->addAttributeToFilter('price', array('lteq' => $priceFilter[1]));
        }
        else{
            $collection->addAttributeToFilter($key, array('in' => $value));
        }
    }
    $collection->setPage($page_no, 10);
foreach($collection as $product){
   echo $product->getName();
}

Redirect functions in magento

Following redirect functions are present in app/code/core/Mage/Core/Controller/Varien/Action.php file.

  1. Redirect specific url : _redirectUrl($url);
  2. Redirect to specific path :  _redirect($path, $arguments=array());
  3. Success page redirection : _redirectSuccess($defaultUrl);
  4. Error page redirection : _redirectError($defaultUrl);
  5. Set referer url to redirect : _redirectReferer($defaultUrl=null);
  6. Get referer url via HTTP_REFERER, regular or requested param : _getRefererUrl()

Examples

In your controller class, you can use as follows

 $this->_redirect($path, $arguments=array());
 // or use,
 $this->_redirectUrl($url);

Here is another way,

//For simple url redirect:

 $url = "http://blog.a2bizz.com";
 Mage::app()->getFrontController()->getResponse()->setRedirect($url);

// Redirect with arguments
 Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl($path, $arguments));

Magento: Create Custom Module

Today, We are going learn to create custom module in Magento, so here are the below steps to create a sample ‘Helloworld’ module-

New Custom Module Creator for Magento2

Sample file structure:

[root]\app\code\local\{Namespace}\{Modulename}
[root]\app\code\local\{Namespace}\{Modulename}\controllers
[root]\app\code\local\{Namespace}\{Modulename}\etc
[root]\app\code\local\{Namespace}\{Modulename}\etc\config.xml
[root]\app\code\local\{Namespace}\{Modulename}\Helper
[root]\app\code\local\{Namespace}\{Modulename}\Model
[root]\app\code\local\{Namespace}\{Modulename}\{Modulename}.php

{Namespace} is a user defined variable. Basically it’s just a mechanism that allows the user to create disparate classes that would otherwise have the same names.

{Modulename} this is the name of your module.

controllers is where all the controllers go.

Model holds all of the models for your module.

For example we use “A2bizz” as namespace and “Helloworld” as Module. we entirely sure if it matters or not, but as a general rule we always capitalize the first letter and leave the rest lower case.

Step One

Inform Magento that you have a custom module. Note the file locations (need to create directories as necessary).

app/etc/modules/A2bizz_HelloWorld.xml

<?xml version=”1.0″?>
<config>
	<modules>
		<A2bizz_HelloWorld>
			<active>true</active>
			<codePool>local</codePool>
		</A2bizz_HelloWorld>
	</modules>
</config>

In this way we have informed Magento that we have an active module (you can turn it off from here by setting ‘active’ to false. we have also informed Magento that it is located in the ‘local’ code pool.

Step Two

Configure your new module. Note the file locations (need to create directories as necessary).

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

<?xml version=”1.0″?>
<config>
	<global>
		<modules>
			<a2bizz_helloworld>
				<version>0.1.0</version>
			</a2bizz_helloworld>
		</modules>
		<blocks>
			<helloworld>
				<rewrite>
					<helloworld>A2bizz_HelloWorld_Block_HelloWorld</helloworld>
				</rewrite>
			</helloworld>
		</blocks>
	</global>
	<frontend>
		<routers>
			<helloworld>
				<use>standard</use>
				<args>
					<module>A2bizz_HelloWorld</module>
					<frontName>helloworld</frontName>
				</args>
			</helloworld>
		</routers>
		<layout>
			<updates>
				<helloworld>
					<file>helloworld.xml</file>
				</helloworld>
			</updates>
		</layout>
	</frontend>
</config>

Here we informed Magento of module version (it’s an arbitrary version). Version matters when you set up your module to be update-able. (A newer version will inform Magento to run the update files if you have them).

We aware Magento that module contains block files which are found in A2bizz/HelloWorld/Block. Here class name will have A2bizz_HelloWorld_Block. If you want to see the many possibilities of stuff that goes in here, check out Magento config files (such as Catalog/etc/config.xml). You’ll also see other xml files in there.

Step Three

Here is my block code. It doesn’t really do anything, but shows some functionality.

app/code/local/A2bizz/HelloWorld/Block/HelloWorld.php

<?php
class A2bizz_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
{
	public function _prepareLayout()
	{
		$this->getLayout()->getBlock(‘breadcrumbs’)
			->addCrumb(‘home’, array(‘label’=>Mage::helper(‘catalogsearch’)->__(‘Home’),
						‘title’=>Mage::helper(‘catalogsearch’)->__(‘Go to Home Page’),
						‘link’=>Mage::getBaseUrl())
						)
			->addCrumb(‘customer’, 
						array(‘label’=>Mage::helper(‘customer’)->__(‘Foo’))
						);
		return parent::_prepareLayout();
	}

	public function myMessage(){
		return “This is A2bizz, This is our module.”;
	}
}
?>

Step Four

Now we create a template file (.phtml) file.

app/design/frontend/default/default/template/helloworld/helloworld.phtml

<?php

echo ‘Hello World ! This A2bizz’;
echo “<BR/>”;
echo $this->myMessage();

?>

Now, Our custom module has been created you can use it, for additional functionality.

Static custom blocks short-codes are not working in Magento 1.9.2.2

 Buy cheap and genuine Windows 7 product key  |
 Windows 7 Product Key for Windows 32bit/64bit Updated 2016y  |
 Windows 7 Ultimate ISO download  |
 Windows 7 Product Key Generator 32 bit and 64 bit Full  |
 Legit Windows 7 Product Key Online Store, PayPal Support  |
 Windows 7 Ultimate with Service Pack 1 Product Key,Windows 7 Key Sale  |
 Windows 7 Key  |
 Get Free Windows 7 Product Key  |
windows-10-education-key
windows-10-enterprise-key
office-2010-key
windows-7-key-sale
windows-10-home-key
windows-10-activation-key
windows-10-pro-key
office-2016-key
windows-10-key
office-2013-key
windows-10-iso
windows-7-key
windows-10-product-key

Nowadays, most common question asked in magento community or stackexchange are “Static custom blocks short-codes are not working in Magento 1.9.2.2“. This issue arise due to following reason.

1. Update magento version to version 1.9.2.2
2. Installing patch SUPEE-6788

Example : I have include CMS static page as following

{{block type="cms/block" block_id="custom_static_block"}}

After updating this, “custom_static_block” is not displaying in home page. The shortcode also shows PHP error in log file under var folder.

Notice: Undefined variable: block  in /app/code/core/Mage/Core/Model/Email/Template/Filter.php on line xxx

I have checked and found that, All the custom static blocks are now working. This is new security patch SUPEE-6788. Custom static blocks need to added in whitelist.

More details technical regarding SUPEE-6788

The responsible code in Filter.php are given below :

if (isset($blockParameters['type'])) {
  if ($this->_permissionBlock->isTypeAllowed($blockParameters['type'])) {
    $type = $blockParameters['type'];
    $block = $layout->createBlock($type, null, $blockParameters);
  }
} elseif (isset($blockParameters['id'])) {
    $block = $layout->createBlock('cms/block');
    if ($block) {
     $block->setBlockId($blockParameters['id']);
   }
}

Now go to the System=> Permission => Blocks

System-permission->blocks

Simply you need to add block type which you have to add block with shortcode. Click on add new. Set block name Ex. “cms/block” and “is_allowed” to “yes”

System-permission->blocks

Now your static block will be in whitelisted and will be able to show in frontend.
div style=”display:none;”>
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |
cheap football kits  |

Fix ‘Namespace_Module_Helper_Data’ not found fatal error in Magento ?

Following are the steps to resolve”fatal error: Class ‘Namespace_Module_Helper_Data’ not found” error.

  1. Install the extension when compilation is disabled in Magento admin.
  2. To check whether compilation is enabled or disabled, go to
    Admin > system >Tools > compilation  check enabled / disabled
  3. If enabled, then disable it and install the extension. Once the extension is installed you can enable compilation again by using ‘Re-run Compilation.
  4. If you have already installed the extension & are facing the above error, Disable the extension from app/etc/modules/Namespace_Module.xml
  5. <active>true</active> 
    To
    <active>false</active>
  6. Clear cache from var/cache folder.
  7. Now you will have the access to Magento admin panel from where you can disable the compilation.
  8. Now enable the extension from Namespace_Module.xml
  9. <active>false</active>
    To
    <active>true</active>
  10. Clear cache from var/cache folder.

Cron System In Magento

Basic

Magento Cron System is used to run tasks on recurring basis as with any cron based system. “cron.php” located in magento base folder is the main entry for magento cron system.Magento cron you need to put “http://yourdomainname.com/cron.php” in your web server cron job

There are various default cron job setup already in magento, so its recommend that you setup cron in magento. The default cron jobs in magento are related to log cleaning, newsletter, product stock notifications, currency updates.

 

Add cron to your module

Add following xml to your custom module’s config.xml

default>
  <crontab>
      <jobs>
          <job_unique_name>
              <schedule>
                  <cron_expr>0 2 * * *</cron_expr>
              </schedule>
              <run>
                  <model>test/observer::cronMethod</model>
              </run>
          </job_unique_name>
      </jobs>
  </crontab>
</default>
Magento also uses a table “cron_schedule” where is stores the status of all cron jobs. This is also a useful table which you can use debug your cron jobs.
There are various settings options for cron in admin which you can configure located at “Sytem -> Configuration -> Advanced -> System -> Cron”.

These settings are given below :

  1. Generate Schedules Every: After how many minutes should we generate a new cron entry in database
  2. Schedule Ahead for: How many minutes ahead should the cron entry be done in database.
  3. Missed if Not Run Within: Mark status as missed if cron has not run with these many minutes
  4. History Cleanup Every: Delete cron entry after how many minutes
  5. Success History Lifetime: After how many minutes to delete a cron entry with status success
  6. Failure History Lifetime: After how many minutes to delete a cron entry with status failure

Cron job details in Magento

To implement cron in magento, follwing files refers,

1. “cron.php”
2. “Mage_Cron_Model_Observer”
3. “app/code/core/Mage/Cron/etc/config.xml”
cron.php
Mage::getConfig()->init()->loadEventObservers('crontab');
Mage::app()->addEventArea('crontab');
Mage::dispatchEvent('always');
Mage::dispatchEvent('default');
app/code/core/Mage/Cron/etc/config.xml
<crontab>
        <events>
            <default>
                <observers>
                    <cron_observer>
                        <class>cron/observer</class>
                        <method>dispatch</method>
                    </cron_observer>
                </observers>
            </default>
            <always>
                <observers>
                    <cron_observer>
                        <class>cron/observer</class>
                        <method>dispatchAlways</method>
                    </cron_observer>
                </observers>
            </always>
        </events>
    </crontab>
You can find “dispatch()” function under “Mage_Cron_Model_Observer” class.

Magento Patch, Do your site required it

    From January, 2015 , Magento has started to got attacks, and the securities issues might be common for all the magento users, which has threatens most of the store owners, here we have come below with the symptoms, which might come if there is any security issue on your Magento server  –

SYMPTOMS

Recommend that you look for the following signs to determine if your site has potentially been compromised:

  • Check your list of administrator users for unknown accounts. We have seen vpwq and defaultmanager being used, but any unknown account is suspicious
  • Check your Magento installation for any unknown files that were recently created and are suspicious. Compare all files to your code repository or staging server.
  • Check server access log files for request POST /index.php/admin/Cms_Wysiwyg/directive/index/ coming from unknown IP addresses.
  • Run a tool to check for trojans (e.g. chkrootkit)
  • Check for wrong permissions
  • Check for hidden files
  • Check for suspicious ports being opened (command: netstat -nap | grep LISTEN )
  • Check for any port redirections on OS level (sample command: iptables -L -n)

If you suspect that the site is compromised, contact the security department of your hosting company for an audit.

CHECKING SITES VIA API

If you have several sites to check or you simply prefer to use our API, send a request like this:

$ curl https://magento.com/security-patch-check/{domain}/{admin path}

Optionally, you can force the API to check in https mode:

$ curl https://magento.com/security-patch-check/{domain}/{admin path}/https

Finally, if your admin path is more than one level deep, replace slashes with exclamation points, like this:

# /my/long/admin/path becomes:
$ curl https://magento.com/security-patch-check/{domain}/my\!long\!admin\!path

INSTALL PATCH

While a large number of merchants have successfully downloaded the patch, many still have not done so. Please act now to ensure that your Magento store is secure!

Community Edition Patches: