Stock Table Creation: Detail/list Page loading issue. Magento 2

dbusername = Database Name 
localhost = Use Host IP
dbname = Database Name
CREATE ALGORITHM=UNDEFINED DEFINER=`dbusername`@`localhost` SQL SECURITY INVOKER VIEW `inventory_stock_1`  AS  select distinct `legacy_stock_status`.`product_id` AS `product_id`,`legacy_stock_status`.`website_id` AS `website_id`,`legacy_stock_status`.`stock_id` AS `stock_id`,`legacy_stock_status`.`qty` AS `quantity`,`legacy_stock_status`.`stock_status` AS `is_salable`,`product`.`sku` AS `sku` from (`dbname`.`cataloginventory_stock_status` `legacy_stock_status` join `dbname`.`catalog_product_entity` `product` on((`legacy_stock_status`.`product_id` = `product`.`entity_id`)));
Example:
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY INVOKER VIEW `inventory_stock_1`  AS  select distinct `legacy_stock_status`.`product_id` AS `product_id`,`legacy_stock_status`.`website_id` AS `website_id`,`legacy_stock_status`.`stock_id` AS `stock_id`,`legacy_stock_status`.`qty` AS `quantity`,`legacy_stock_status`.`stock_status` AS `is_salable`,`product`.`sku` AS `sku` from (`exampledatabasename`.`cataloginventory_stock_status` `legacy_stock_status` join `exampledatabasename`.`catalog_product_entity` `product` on((`legacy_stock_status`.`product_id` = `product`.`entity_id`)));

Category Page loading issue, (Exception #0 (DomainException): Undefined factory mysql)

Category Page loading issue, if that page have sidebar "search/engine" tracking.
Step 1: Check Catalog Search Default Search Engine options under catalog menu and enable Mysql Engine
Step 2: Check Other Catalog Search Extensions Modules
Example: Advanced Search,Auto Complete Search Extensions 
Step 3: Update the 'core_config_data' table 'catalog/search/engine' path value using below code
UPDATE core_config_data set value = 'mysql' where path='catalog/search/engine'	 // As default its mysql2

How to Get Number of Product Reviews Magento 2

Display the average stars and reviews count of product

<?php
$productId = 'your_product_id';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$reviewFactory = $objectManager->create('Magento\Review\Model\Review');
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
$storeManager  = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManager->getStore()->getStoreId();
$reviewFactory->getEntitySummary($product, $storeId);

$ratingSummary = $product->getRatingSummary()->getRatingSummary();
$reviewCount = $product->getRatingSummary()->getReviewsCount();
?>
<?php if($ratingSummary){ ?>
<div class="product-reviews-summary short">
    <div class="rating-summary">
        <div title="<?php echo (int)$ratingSummary; ?>%" class="rating-result">
            <span style="width:<?php echo (int)$ratingSummary; ?>%"><span><?php echo (int)$ratingSummary; ?>%</span></span>
        </div>
    </div>
    <div class="reviews-actions">
        <?php echo __('('.$reviewCount.') Reviews'); ?>
    </div>
</div>
<?php } ?>

Update Cron file in Magento and Server

Update Cron file in Magento and Server:

1. Setting up the Magento cronjob using shell access

It is strongly recommended not to run the cronjob under the

crontab -e
root/superuser account. If you are logged in as root, please switch (su) to a non-privileged account.
Before setting up a new cronjob, please make sure the Magento cronjob (a cron running cron.php) hasn’t been set up yet. Use the following command to get the currently installed cronjobs:

If the cronjob hasn’t been set up yet, you will need to open the crontab file to set up the cronjob. The crontab manages which and when cronjobs are run on the server.

crontab -l

Now, go to the end of the last line in the cron tab file and press enter to create a new line.

Enter the following line and replace YOURDOMAIN.com and PATH_TO_MAGENTO with the URL of the root directory of your Magento installation:

*/5 * * * * wget -O /dev/null -q http://www.YOURDOMAIN.com/PATH_TO_MAGENTO/cron.php > /dev/null
 
OR
 
*/5 * * * * /bin/php /var/www/vhosts/YOURDOMAIN/htdocs/cron.php > /dev/null
 
OR
 
*/5 * * * * wget -O /dev/null -q /var/www/vhosts/YOURDOMAIN/htdocs/cron.php > /dev/null
 
OR
 
*/5 * * * * /bin/php -q /var/www/vhosts/YOURDOMAIN/htdocs/cron.php   (Its working for us)

 

It is very important that the cron.php file of Magento gets executed every five minutes. Do not change this to a longer interval.

Please try to call the URL you’ve entered into the cron tab using your browser. A blank page should be returned. If the page can’t be found (404), that means the URL to the cronjob manager of Magento (cron.php) is wrong. This means the cron job won’t execute and hasn’t been set up properly. It is really important you enter the correct URL – it is always the URL to the cron.php file sitting inside the root directory of your Magento installation.

Save the cron tab using CTRL+X, enter y to save the changes and press enter. The following message should be displayed:

crontab: installing new crontab

 

 

Magento New Order Mail Not Sending Admin Issue

 

Note : Check the mail after each steps Completed

Step1 : Email Model Template File

File Path: app/code/core/Mage/Core/Model/Email/Template.php 

Note : Move to local path app/code/local/Mage/Core/Model/Email/Template.php 

Changed the Below line In Your Template.php file

<?php
    if ($this->hasQueue()&& $this->getQueue() instanceof Mage_Core_Model_Email_Queue) /* line number 407 version 1.9.2.2 */
 
  to
 
    if (!($this->hasQueue()) && $this->getQueue() instanceof Mage_Core_Model_Email_Queue)
 
  (or)
    if (!($this->hasQueue() && $this->getQueue() instanceof Mage_Core_Model_Email_Queue))
 ?>

Step2 : Sales Model Template File

File Path: app/code/core/Mage/Sales/Model/Order.php 

Note : Move to local path app/code/local/Mage/Sales/Model/Order.php 

Changed the Below line In Your Order.php file

<?php 
  $mailer->setQueue($emailQueue)->send(); 
 
  to
 
  $mailer->send(); 
?>

 

Step3: Check Cron (Scheduled Tasks)  in magento Admin Panel

Path:Configuration -> Advanced -> System -> Cron (Scheduled Tasks) – all the times are in minutes 

Check Below Options is Set Low Values Or Not

‘Generate Schedules’, ‘Every Schedule Ahead for’

 

Step4: Cron File Update

cron.php should be as like Magento Version

Add the Below code in your cron.php file after this line

<?php
$isShellDisabled = is_array($disabledFuncs) ? in_array('shell_exec', $disabledFuncs) : true;
/* line number 47 version 1.9.2.2  */
/* Added Code */ 
$isShellDisabled = true;
?>

 

 

 

Remove index.php from Magento URL in windows server

To remove the index.php from URL in magento normally we will use htaccess. But, it will work in apache server only. So, to remove the index.php in windows server, we need to use the below code in web.config file.

Save the below code within the “web.config” file and upload it into your magento root directory.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite> 
<rules>
 
 
 
<rule name="Remove index.php Rule" stopProcessing="true"> 
<match url=".*" ignoreCase="false" /> 
<conditions> 
<add input="{URL}" pattern="^/(media|skin|js)/" ignoreCase="false" negate="true" /> 
<add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" /> 
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" /> 
</conditions> 
<action type="Rewrite" url="index.php" /> 
</rule>
 
 
 
</rules>
</rewrite>
</system.webServer>
<system.net>
<mailSettings>
<smtp>
<network host="localhost" />
</smtp>
</mailSettings>
</system.net>
</configuration>

Create the Custom Form with Mail Template in Magento

Step1: Create the new modules

File path – app/etc/modules

<?xml version="1.0"?>
<config>
<modules>
<Custom_ContactForm>
<active>true</active>         
<codePool>local</codePool>
</Custom_ContactForm>
</modules>
</config>

Save as app/etc/modules/Custom_ContactForm.xml

Step2: Create the Controllers and Template File

Path:app/code/local/Custom/ContactForm/controllers

<?php class Custom_ContactForm_IndexController extends Mage_Core_Controller_Front_Action {
const XML_PATH_EMAIL_RECIPIENT = 'contacts/email/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/email/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/email/email_template';
const XML_PATH_ENABLED = 'contacts/contacts/enabled';
public function indexAction() {
//Get current layout state
$this->loadLayout();
$block = $this->getLayout()->createBlock( 'Mage_Core_Block_Template', 'custom.contactform', array( 'template' => 'custom/contactform.phtml' ) );
$this->getLayout()->getBlock('content')->append($block);
$this->_initLayoutMessages('core/session');
$this->renderLayout();
}
public function sendemailAction() {
//Fetch submited params
$params = $this->getRequest()->getParams();
if ( $params ) {
$translate = Mage::getSingleton('core/translate');
/* @var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($params);
$error = false;
if (!Zend_Validate::is(trim($params['name']) , 'NotEmpty')) { $error = true; }
if (!Zend_Validate::is(trim($params['comment']) , 'NotEmpty')) { $error = true; }
if (!Zend_Validate::is(trim($params['email']), 'EmailAddress')){ $error = true; }
if (Zend_Validate::is(trim($params['hideit']), 'NotEmpty')) { $error = true; }
if ($error) { throw new Exception(); }
$mailTemplate = Mage::getModel('core/email_template')->loadByCode('Custom Mail Template Name');
// Load the Custom template from "Admin Template name" which under System ->Transactional Emails * @var $mailTemplate Mage_Core_Model_Email_Template */
$mailTemplate->setDesignConfig(array('area' => 'frontend')) ->setReplyTo($params['email']) ->sendTransactional( $mailTemplate,
// Changed above variabe as like this, while implementing Custom Template
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER), Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT), null, array('data' => $postObject) );
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
echo $translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
//Redirect back to index action of (this) custom-contactform controller
$this->_redirect('redirectpagepath eg:home/?sent=success#contact');
return;
}
catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
//Redirect back to index action of (this) custom-contactform controller
$this->_redirect('redirectpagepath eg:home/');
return;
}
} else {
//Redirect back to index action of (this) custom-contactform controller
$this->_redirect('redirectpagepath eg:home/');
}
//Redirect back to index action of (this) custom-contactform controller
$this->_redirect('redirectpagepath eg:home/');
}
} ?> 

Save as app/code/local/Custom/ContactForm/controllers/IndexController.php

Create the Mail Template for Module

<?xml version="1.0"?>
 
<config>
    <modules>
        <Custom_ContactForm>
            <version>0.1.0</version>
        </Custom_ContactForm>
    </modules>   
 
    <frontend>
        <routers>
            <Custom_ContactForm>
                <use>standard</use>
                <args>
                    <module>Custom_ContactForm</module>
                    <frontName>custom-contactform</frontName>
                </args>
            </Custom_ContactForm>
        </routers>
    </frontend>    
    <global>      
    	<template>
    		<email>
		  <custom_form_email_template translate="label" module="contacts">
			<label>Custom Form</label>
			<file>custom_form.html</file>
			<type>html</type>
		   </custom_form_email_template>
		</email>
    	</template>
    </global>     
</config>

Save as app/code/local/Custom/ContactForm/etc/config.xml

Step3: Create the Frontend Form File

Path:app/design/frontend/yourtheme/default/template/custom

<div class="box simple_contact">
<form id="conversationform" name="offerform_form" action="<?php echo $this->getUrl('custom-contactform/') ?>index/sendemail" method="post">
	<input type="text" class="required-entry input-text conversation_input" placeholder="Your Name" name="name" id="yourname">
	<input type="text" class="required-entry input-text conversation_input"  placeholder="Company Name" name="companyname" id="companyname">
	<input type="text" class="required-entry input-text conversation_input"  placeholder="Email Address" name="email" id="email">
	<input type="text" class="required-entry input-text conversation_input"  placeholder="Telephone Number" name="telephone" id="telephone">
	<input type="text" class="required-entry input-text conversation_input"  placeholder="I'm Interested In" name="interested" id="interested">
	<textarea class="required-entry input-text conversation_input"  placeholder="Message" name="comment" id="message"></textarea>
    <div class="button-set">
       <input type="text" name="hideit" id="hideit" value="" style="display:none !important;" />
	   <button class="form-button" type="submit" id="conversubmit"><span>SEND MESSAGE</span></button>
    </div>
</form>
 
</div>

Save as app/design/frontend/yourtheme/default/template/custom/contactform.phtml

Step4: Create the Custom Transactional Mail Template File

Path: app/locale/en_US/template/email/

<!--@subject Your Subject eg:hai@-->
<!--@vars {"var data.name":"Sender Name", "var data.email":"Sender Email", "var data.telephone":"Sender Telephone", "var data.comment":"Comment"} @-->
Name: {{var data.name}}
Email: {{var data.email}}
Telephone: {{var data.telephone}}
Comment: {{var data.comment}}

save as app/locale/en_US/template/email/custom_form.html

Important Code

Set Transactional Mail Template

$mailTemplate = Mage::getModel('core/email_template')->loadByCode('Your Transactional Template Name');
$mailTemplate->setDesignConfig(array('area' => 'frontend')) ->setReplyTo($params['email']) ->sendTransactional(
//Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE), $mailTemplate,
// Changed above variabe as like this, while implementing Custom Template
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER), Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT), null, array('data' => $postObject) );

If Category Have Only One Product Auto Redirect To Product Details Page Magento

Put this code your category page template file example 2column_left.phtml

$product = Mage::registry('current_product');  
if($product == ''){
    $category = Mage::registry('current_category');
    if(is_object($category)){
        $catLoaded = Mage::getModel('catalog/category')->load($category->getEntityId());
        $collection = $catLoaded->getProductCollection();
        $collection->addAttributeToSelect('*');
        if(count($collection) == 1){
            foreach($collection as $product){
                $productUrl = $product->getProductUrl();
                header("location:$productUrl");
                exit;
            }
        }
    }
}

Change magento contact form FROM address as User contact address

  1. In magento we could set the contact from FROM address in admin under Admin->Configuration->Contact->Email Sender(Field)

  2. In our case, we cant able to send email from Same address like XXX@knowledgebags.com to XXX@knowledgebags.com. So, we need to change the email from address as like user emails address. So, we did as like below!
  3. //Copy
    /app/code/core/Mage/Contacts/controllers/IndexController.php
     //Copy above file Into below location: 
    /app/code/local/Mage/Contacts/controllers/IndexController.php
    //You can comment out line 97, don’t need that anymore:
    //->setReplyTo($post['email'])
     //Comment out line 100, the one causing the problem:
    //Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
     //Add a new line 101:
    array('email' => $post['email'], 'name' => $post['name']),
     //Save and you’re done!

4. Also, in my case Copy file into local folder not worked. So, we have did the test in /core folder itself and tested. Its worked fine.

NOTE: Also, we have changed all email sender admin as different address. For customer, order emails…etc

Magento configuration and Migration issues in windows server

We have faced below list of issues while using Magento in windows server.

  1. Magento 1.* PHP version should be 5.*
  2. url_rewrite – Need to use web.config based on IIS version
  3. In My case, url_rewrite not installed. To check this follow below steps.
    ->Start IIS Manager (Start >> Run, type inetmgr and hit enter).
    ->In IIS, select the Default Web Site.
    ->Under Features View, click URL Rewrite. (Its not displayed my case)
  4. Installed url_rewrite and fixed the issues.

    I will be continue soon….