Wednesday, 29 November 2017

Magento 2 : Display All Products Review in one Pa...

Kuldeep Singh Dagar: Magento 2 : Display All Products Review in one Pa...: Magento 2 :  Display All Products Review in Separate Page Create a static block 'Review list' {{block class="Magento\Frame...

Magento Programatically Export All Products Data Into Custom CSV Files.

It's simple to create custom csv in magento . follow the steps to create custom csv. 

Create php page like 'get_product_export.php' in magento install root directory. and paste the below code.


<?php

ini_set('memory_limit','2048M');
ini_set('max_execution_time',36000000);
    require_once 'app/Mage.php';
Mage::app("default");
$_helper = Mage::helper('catalog/output');

$filename ='';
$filename ='export_all_products.csv';

$_productCollection = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect('*');

$file = fopen($filename, 'w'); 

    function getProductcatid($ProductId){
   
        $productload = Mage::getModel('catalog/product')->load($ProductId);
        $cats = $productload->getCategoryIds();
        foreach ($cats as $category_id) {
            $_cat .= $category_id.',' ;
           
        }
        return  substr($_cat,0,-1);
    }

    function getAttrLabel($name, $attr_val, $_product){
    if(!empty($attr_val)){
$attr_val = explode(" ", $attr_val);
$attr_names = [];
foreach ($attr_val as $attr_id) {
$attr = $name;
$attr = $_product->getResource()->getAttribute($attr);
if ($attr->usesSource()) {
    $attr_info = $attr->getSource()->getOptionText($attr_id);
    $attr_info = implode(",", $attr_info);
    $AttributeMaterial = $attr_info;
    return $attr_info;
}
else{
return "";
}
}
}
else{
return "";
}
    }

foreach ($_productCollection as $_product):  
    $product_id = $_product->getId();
    $status="FALSE";
    $name= $_product->getName();
$name=str_replace("&","&amp;",$name);
$ProductId= $_product->getEntityId();
$ProductGroup= $_product->getSku();
$ProductNameDE= $name;
$desc1=strip_tags($_product->getDescription());
$desc1=str_replace("&nbsp;"," ",$desc1);
$desc1=str_replace("&","&amp;",$desc1);
$ProductLongDescriptionDE= $desc1;

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

$imageurl="https://xxxxxx.xxx/media/catalog/product";
$Inventory=$stock->getQty();;
$ProductVAT="";
$Warranty="";
$GTIN="";
$DeliveryMethod1="";
$ProductBrandName="";

$AttributeGrosse=$_product->getGroesse();
$AttributeRingBreite="";
$AttributeRingBreite = getAttrLabel('ring_breite', $_product->getRingBreite(), $_product);
$AttributeHalskettenlange= getAttrLabel('halskette_laenge', $_product->getHalskettenlange(), $_product);
$AttributeAnhangerBreite= getAttrLabel('anhaenger_breite', $_product->getAnhangerBreite(), $_product);
$AttributeBreite= getAttrLabel('breite', $_product->getBreite(), $_product);
$AttributeLange= getAttrLabel('lange', $_product->getLange(), $_product);
$AttributeArmbandtyp= getAttrLabel('armband_typ', $_product->getArmbandtyp(), $_product);
$AttributeFarbe= getAttrLabel('farbe', $_product->getFarbe(), $_product);
$AttributeMaterial= getAttrLabel('material', $_product->getMaterial(), $_product);
$AttributeSteinart= getAttrLabel('steine', $_product->getSteinart(), $_product);
$AttributeVerschlussart="";
$AttributeGeschlecht="";
$ProductImageURL1 = $imageurl.$_product->getImage();

$gallery_images = Mage::getModel('catalog/product')->load($product_id)->getMediaGalleryImages();
$items = array();
foreach($gallery_images as $g_image) {
    $items[] = $g_image['url'];
}

$ProductImageURL1="";
$ProductImageURL2="";
$ProductImageURL3="";
$ProductImageURL4="";
$ProductImageURL5="";
$ProductImageURL6="";

if(isset($items[0])){
$ProductImageURL1 = $items[0];
}
if(isset($items[1])){
$ProductImageURL2 = $items[1];
}
if(isset($items[2])){
$ProductImageURL3 = $items[2];
}
if(isset($items[3])){
$ProductImageURL4 = $items[3];
}
if(isset($items[4])){
$ProductImageURL5 = $items[4];
}
if(isset($items[5])){
$ProductImageURL6 = $items[5];
}

$ProductSalesPrice = $_product->getSpecialPrice();
$ProductOriginalPrice = $_product->getPrice();

    if($_product->getStatus()=="1"){$status="TRUE";}
   
$ProductPublished = $status;


$data[] = array($ProductId, $ProductGroup, $ProductNameDE, $ProductLongDescriptionDE, $Category, $Inventory, $ProductVAT,
$Warranty, $GTIN, $DeliveryMethod1, $ProductBrandName, $AttributeGrosse, $AttributeRingBreite, $AttributeHalskettenlange,
$AttributeAnhangerBreite, $AttributeLange, $AttributeBreite, $AttributeLange, $AttributeArmbandtyp, $AttributeFarbe,
$AttributeMaterial, $AttributeSteinart, $AttributeVerschlussart, $AttributeGeschlecht, $ProductImageURL1, $ProductImageURL2,
$ProductImageURL3, $ProductImageURL4, $ProductImageURL5, $ProductImageURL6, $ProductSalesPrice,
$ProductOriginalPrice, $ProductPublished); 
 
endforeach; 
// print_r($data);

fputcsv($file, array('ProductId','ProductGroup','ProductNameDE','ProductLongDescriptionDE','Category','Inventory',
'ProductVAT','Warranty','GTIN','DeliveryMethod 1','ProductBrandName','Attribute Grösse','Attribute Ring Breite',
'Attribute Halskettenlänge','Attribute Anhänger Breite','Attribute Länge','Attribute Breite','Attribute Länge',
'Attribute Armbandtyp','Attribute Farbe','Attribute Material','Attribute Steinart','Attribute Verschlussart',
'Attribute Geschlecht','ProductImageURL 1','ProductImageURL 2','ProductImageURL 3','ProductImageURL 4',
'ProductImageURL 5','ProductImageURL 6','ProductSalesPrice','ProductOriginalPrice','ProductPublished')); 

foreach($data as $row){
   fputcsv($file, $row);     
}

// header('Content-Type: application/csv');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$filename.'"');
exit;
 
  echo "Done";


?>


Thanks,
Kuldeep singh

Tuesday, 28 November 2017

Magento 2 : Folders and Files Permissions. Command


The web server user must have write access to the following files and directories:

PHP version 7.

PHP Extensions Check
    curl.
    dom.
    iconv.
    mcrypt.
    simplexml.
    spl.
    xsl.
    intl.
    mbstring.
    ctype.
    hash.
    openssl.
    pdo_mysql.
    soap.
    zip.
    xmlwriter.
    phar.
    pcre.
    gd.
   
File Permission Check

    ./app/etc             writable directory permission.
    ./var                  writable directory permission.
    ./pub/media          writable directory permission.
    ./pub/static          writable directory permission.
    ./generated          writable directory permission.


Set permission  Command:

find . -type f -exec chmod 644 {} \;     // 644 permission for files
find . -type d -exec chmod 755 {} \;    // 755 permission for directory 
find ./var -type d -exec chmod 777 {} \;   // 777 permission for var folder 
find ./pub/media -type d -exec chmod 777 {} \;
find ./pub/static -type d -exec chmod 777 {} \;
find ./app/etc -type d -exec chmod 777  {} \;
chmod 644 ./app/etc/*.xml
chmod 777 ./var/.htaccess
chmod 777 ./app/etc/di.xml
chmod 777 ./app/etc/vendor_path.php
chmod 777 ./app/etc/NonComposerComponentRegistration.php
chmod 777 ./pub/media/customer/.htaccess
chmod 777 ./pub/media/theme_customization/.htaccess
chmod 777 ./pub/media/composer.json
chmod 777 ./pub/media/import/.htaccess
chmod 777 ./pub/media/.htaccess
chmod 777 ./pub/media/downloadable/.htaccess
chmod 777 ./pub/media/LICENSE.txt
chmod 777 ./pub/static/.htaccess
chmod 777 ./generated
chmod 777 ./generated/.htaccess


Thanks,
Kuldeep Singh


Monday, 27 November 2017

Magento 1.9 Auto Clean Cash Using Custom Code

Create a php page 'autocleancash.php' with below code.

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);
//echo 'Hello1';
require_once 'app/Mage.php';


Mage::init();
$types = Mage::app()->getCacheInstance()->getTypes();

try {
    echo "Cleaning data cache... \n";
    flush();
    foreach ($types as $type => $data) {
        echo "Removing $type ... ";
        echo Mage::app()->getCacheInstance()->clean($data["tags"]) ? "Cache cleared!" : "There is some error!";
        echo "\n";
    }
} catch (exception $e) {
    die("[ERROR:" . $e->getMessage() . "]");
}

echo "\n";

try {
    echo "Cleaning stored cache... ";
    flush();
    echo Mage::app()->getCacheInstance()->clean() ? "Cache cleared!" : "There is some error!";
    echo "\n\n";
} catch (exception $e) {
    die("[ERROR:" . $e->getMessage() . "]");
}             

?>



 if any issues please email me.

Thanks,
Kuldeep singh

Magento 1.9 Catalog Price Rules Not Working [SOLVED]

We have find a two solution to solve this problem.

Solution One :

Setup a cron and check is working or not. if it is working check your Default Store Timezone is matching your server timezone.

 Default Store Timezone == Server Timezone

both are same the working fine.

Other solution :


Create a php page in root directory then past a below code.

'applyrules.php '

<?php
require_once 'app/Mage.php';
Mage::init();
ini_set('max_execution_time', 1800); //900 seconds = 15 minutes

        Mage::getModel('catalogrule/rule')->applyAll();
        Mage::getModel('catalogrule/flag')->loadSelf()
            ->setState(0)
            ->save();

?>


and set a cron 'applyrules.php' one time every day

then need a clear cash auto
Need one cron auto 'cleancash'

then create a php page 'autocleancash.php' with below code.

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);
//echo 'Hello1';
require_once 'app/Mage.php';


Mage::init();
$types = Mage::app()->getCacheInstance()->getTypes();

try {
    echo "Cleaning data cache... \n";
    flush();
    foreach ($types as $type => $data) {
        echo "Removing $type ... ";
        echo Mage::app()->getCacheInstance()->clean($data["tags"]) ? "Cache cleared!" : "There is some error!";
        echo "\n";
    }
} catch (exception $e) {
    die("[ERROR:" . $e->getMessage() . "]");
}

echo "\n";

try {
    echo "Cleaning stored cache... ";
    flush();
    echo Mage::app()->getCacheInstance()->clean() ? "Cache cleared!" : "There is some error!";
    echo "\n\n";
} catch (exception $e) {
    die("[ERROR:" . $e->getMessage() . "]");
}             

?>



 if any issues please email me.

Thanks,
Kuldeep singh

 

Wednesday, 22 November 2017

Magento 2 : Display All Products Review in one Page

Magento 2 :  Display All Products Review in Separate Page

Create a static block 'Review list'

{{block class="Magento\Framework\View\Element\Template" template="Magento_Review::review_list.phtml"}}

The Create a CMS page 'Review'  and insert a widget like this

{{widget type="Magento\Cms\Block\Widget\Block" template="widget/static_block/default.phtml" block_id="36"}}

app/design/frontend/themes/themename/default/Magento_Review/templates/review_list.phtml

paste the below code or enjoy the all product review in one page.

<?php 
use Magento\Framework\App\Action\Action;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()
            ->addAttributeToSelect('*')
            ->addStoreFilter()
            ->load();

foreach ($collection as $product){
 
$imageHelper  = $objectManager->get('\Magento\Catalog\Helper\Image');
$image_url = $imageHelper->init($product, 'product_page_image_small')->setImageFile($product->getFile())->resize(250, 250)->getUrl();

$rating = $objectManager->get("Magento\Review\Model\ResourceModel\Review\CollectionFactory");
$collectionReview = $rating->create()
        ->addStatusFilter(
            \Magento\Review\Model\Review::STATUS_APPROVED
        )->addEntityFilter(
            'product',
            $product->getId()
        )->setDateOrder();
      
$this->_storeManagerInterface = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$reviewFactory = $objectManager->create('Magento\Review\Model\Review');
$storeId = $this->_storeManagerInterface->getStore()->getId();
$reviewFactory->getEntitySummary($product, $storeId);
$ratingPer = $product->getRatingSummary()->getRatingSummary();
if($ratingPer){
?>
<div class="review-all-page">
<div class="product-contener">
<div class="col-md-6" >
   <a href="<?php echo $product->getUrlKey().'.html';  ?> " > <img src="<?php echo $image_url;  ?>" /></a>
</div>

<div class="col-md-18">
    <div class="product-name"><a href="<?php echo $product->getUrlKey().'.html';  ?>" ><strong> <?php echo $product->getName(); ?> </strong></a></div>
    <div class="review-contener">
      
       
            <div class="product-reviews-summary short">
                <span>Rating:</span>
                <div class="rating-summary"><span class="label"><span>Rating:</span></span>
                    <div class="rating-result" title=" <?php echo $ratingPer.'%'; ?> ">
                        <span style="width:<?php echo $ratingPer.'%'; ?>"><span><?php echo $ratingPer.'%'; ?></span></span>
                    </div>
                </div>
            </div>
            <div class="all-review">
          <?php  foreach ($collectionReview as $reviewDetail){  ?>
          <div class="review-name-desc">
            <div class="data data_name">
                <b>By <?php  echo  $reviewDetail->getNickname();  ?></b></br>
                <span>Date Added: <?php echo date("l d F, Y", strtotime($reviewDetail->getCreatedAt()));  ?></span>
            </div>
          
            <div class="data data_desc">  <?php echo  $reviewDetail->getDetail(); ?>  </div>
         </div>
       
          
         <?php   }  ?>
            </div>
    </div>
  
</div>
</div>
</div>
 <?php  } }  ?>
  <script type="text/javascript">
            require(['jquery','domReady!'],function($){
                

                     
                        $('.all-review').each(function() {
                            var $times = $(this).children('.review-name-desc');
                            if ($times.length > 1) {  
                                 $(this).children(':nth-of-type(n+2)').addClass('more-times').hide();
                                 $(this).append('<a class="more-timesclick">+ More Review</a>');
                            }
                        });
                      
                        $(document).on('click', 'a.more-timesclick', function() {
                          $(this).parent().find('.review-name-desc.more-times').eq(0).removeClass('more-times').show();
                           $len =  $(this).parent().find('.review-name-desc.more-times').length;
                          if ($len == 0) {
                            $(this).removeClass('more-timesclick').addClass('less-timesclick').text('- Less Review');
                          }
                        }); 
                      
                         $(document).on('click', 'a.less-timesclick', function() {
                           
                            var $times = $(this).parent().children('.review-name-desc');
                            if ($times.length > 1) {  
                              
                                 $(this).parent().children(':nth-of-type(n+2)').addClass('more-times').hide();
                                 $(this).removeClass('less-timesclick').addClass('more-timesclick').text('+ More Review');
                              
                            }
                          
                        });
                
                
            });
 </script>

if any issues please email me.

Thanks,
Kuldeep Singh

Email: kuldeep4110@gmail.com

Monday, 20 November 2017

Magento 2 : Remove Products / Category's / Customers /Orders /Product Reviews Using MySQL Script

Below Truncate worked for me in Magento ver. 2.1.7


Truncate Category Tables

SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE TABLE `catalog_category_entity`;
TRUNCATE TABLE `catalog_category_entity_datetime`;
TRUNCATE TABLE `catalog_category_entity_decimal`;
TRUNCATE TABLE `catalog_category_entity_int`;
TRUNCATE TABLE `catalog_category_entity_text`;
TRUNCATE TABLE `catalog_category_entity_varchar`;
TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `catalog_category_product_index`;

INSERT INTO `catalog_category_entity` (`entity_id`, `attribute_set_id`, `parent_id`, `created_at`, `updated_at`, `path`, `position`, `level`, `children_count`) VALUES ('1', '0', '0', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '1', '0', '0', '1'),
('2', '3', '1', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '1/2', '1', '1', '0');

INSERT INTO `catalog_category_entity_int` (`value_id`, `attribute_id`, `store_id`, `entity_id`, `value`) VALUES
('1', '69', '0', '1', '1'),
('2', '46', '0', '2', '1'),
('3', '69', '0', '2', '1');

INSERT INTO `catalog_category_entity_varchar` (`value_id`, `attribute_id`, `store_id`, `entity_id`, `value`) VALUES
('1', '45', '0', '1', 'Root Catalog'),
('2', '45', '0', '2', 'Default Category');

SET FOREIGN_KEY_CHECKS = 1;

DELETE FROM url_rewrite WHERE entity_type = 'category';

*****************************************************************

Truncate Product Tables


SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;
TRUNCATE TABLE `cataloginventory_stock_status_idx`;
TRUNCATE TABLE `cataloginventory_stock_status_tmp`;
TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `catalog_category_product_index`;
TRUNCATE TABLE `catalog_category_product_index_tmp`;
TRUNCATE TABLE `catalog_compare_item`;
TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_price_index`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_bundle_selection_price`;
TRUNCATE TABLE `catalog_product_bundle_stock_index`;
TRUNCATE TABLE `catalog_product_entity`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value_to_entity`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value_video`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_index_eav`;
TRUNCATE TABLE `catalog_product_index_eav_decimal`;
TRUNCATE TABLE `catalog_product_index_eav_decimal_idx`;
TRUNCATE TABLE `catalog_product_index_eav_decimal_tmp`;
TRUNCATE TABLE `catalog_product_index_eav_idx`;
TRUNCATE TABLE `catalog_product_index_eav_tmp`;
TRUNCATE TABLE `catalog_product_index_price`;
TRUNCATE TABLE `catalog_product_index_price_bundle_idx`;
TRUNCATE TABLE `catalog_product_index_price_bundle_opt_idx`;
TRUNCATE TABLE `catalog_product_index_price_bundle_opt_tmp`;
TRUNCATE TABLE `catalog_product_index_price_bundle_sel_idx`;
TRUNCATE TABLE `catalog_product_index_price_bundle_sel_tmp`;
TRUNCATE TABLE `catalog_product_index_price_bundle_tmp`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_agr_idx`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_agr_tmp`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_idx`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_tmp`;
TRUNCATE TABLE `catalog_product_index_price_downlod_idx`;
TRUNCATE TABLE `catalog_product_index_price_downlod_tmp`;
TRUNCATE TABLE `catalog_product_index_price_final_idx`;
TRUNCATE TABLE `catalog_product_index_price_final_tmp`;
TRUNCATE TABLE `catalog_product_index_price_idx`;
TRUNCATE TABLE `catalog_product_index_price_opt_agr_idx`;
TRUNCATE TABLE `catalog_product_index_price_opt_agr_tmp`;
TRUNCATE TABLE `catalog_product_index_price_opt_idx`;
TRUNCATE TABLE `catalog_product_index_price_opt_tmp`;
TRUNCATE TABLE `catalog_product_index_price_tmp`;
TRUNCATE TABLE `catalog_product_index_tier_price`;
TRUNCATE TABLE `catalog_product_index_website`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_relation`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_url_rewrite_product_category`;
TRUNCATE TABLE `downloadable_link`;
TRUNCATE TABLE `downloadable_link_price`;
TRUNCATE TABLE `downloadable_link_purchased`;
TRUNCATE TABLE `downloadable_link_purchased_item`;
TRUNCATE TABLE `downloadable_link_title`;
TRUNCATE TABLE `downloadable_sample`;
TRUNCATE TABLE `downloadable_sample_title`;
TRUNCATE TABLE `product_alert_price`;
TRUNCATE TABLE `product_alert_stock`;
TRUNCATE TABLE `report_compared_product_index`;
TRUNCATE TABLE `report_viewed_product_aggregated_daily`;
TRUNCATE TABLE `report_viewed_product_aggregated_monthly`;
TRUNCATE TABLE `report_viewed_product_aggregated_yearly`;
TRUNCATE TABLE `report_viewed_product_index`;

SET FOREIGN_KEY_CHECKS = 1;
DELETE FROM url_rewrite WHERE entity_type = 'product';

************************************************************************

Truncate Review Tables


SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE `review`;
TRUNCATE TABLE `review_detail`;
TRUNCATE TABLE `review_entity_summary`;
TRUNCATE TABLE `review_store`;

SET FOREIGN_KEY_CHECKS = 1;

************************************************************************

Truncate Customer Tables

SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE `customer_address_entity`;
TRUNCATE TABLE `customer_address_entity_datetime`;
TRUNCATE TABLE `customer_address_entity_decimal`;
TRUNCATE TABLE `customer_address_entity_int`;
TRUNCATE TABLE `customer_address_entity_text`;
TRUNCATE TABLE `customer_address_entity_varchar`;
TRUNCATE TABLE `customer_entity`;
TRUNCATE TABLE `customer_entity_datetime`;
TRUNCATE TABLE `customer_entity_decimal`;
TRUNCATE TABLE `customer_entity_int`;
TRUNCATE TABLE `customer_entity_text`;
TRUNCATE TABLE `customer_entity_varchar`;
TRUNCATE TABLE `customer_grid_flat`;
TRUNCATE TABLE `customer_log`;
TRUNCATE TABLE `customer_log`;
TRUNCATE TABLE `customer_visitor`;
TRUNCATE TABLE `persistent_session`;
TRUNCATE TABLE `wishlist`;
TRUNCATE TABLE `wishlist_item`;
TRUNCATE TABLE `wishlist_item_option`;
SET FOREIGN_KEY_CHECKS = 1;


************************************************************************

Truncate Order Tables

SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE `gift_message`;
TRUNCATE TABLE `quote`;
TRUNCATE TABLE `quote_address`;
TRUNCATE TABLE `quote_address_item`;
TRUNCATE TABLE `quote_id_mask`;
TRUNCATE TABLE `quote_item`;
TRUNCATE TABLE `quote_item_option`;
TRUNCATE TABLE `quote_payment`;
TRUNCATE TABLE `quote_shipping_rate`;
TRUNCATE TABLE `reporting_orders`;
TRUNCATE TABLE `sales_bestsellers_aggregated_daily`;
TRUNCATE TABLE `sales_bestsellers_aggregated_monthly`;
TRUNCATE TABLE `sales_bestsellers_aggregated_yearly`;
TRUNCATE TABLE `sales_creditmemo`;
TRUNCATE TABLE `sales_creditmemo_comment`;
TRUNCATE TABLE `sales_creditmemo_grid`;
TRUNCATE TABLE `sales_creditmemo_item`;
TRUNCATE TABLE `sales_invoice`;
TRUNCATE TABLE `sales_invoiced_aggregated`;
TRUNCATE TABLE `sales_invoiced_aggregated_order`;
TRUNCATE TABLE `sales_invoice_comment`;
TRUNCATE TABLE `sales_invoice_grid`;
TRUNCATE TABLE `sales_invoice_item`;
TRUNCATE TABLE `sales_order`;
TRUNCATE TABLE `sales_order_address`;
TRUNCATE TABLE `sales_order_aggregated_created`;
TRUNCATE TABLE `sales_order_aggregated_updated`;
TRUNCATE TABLE `sales_order_grid`;
TRUNCATE TABLE `sales_order_item`;
TRUNCATE TABLE `sales_order_payment`;
TRUNCATE TABLE `sales_order_status_history`;
TRUNCATE TABLE `sales_order_tax`;
TRUNCATE TABLE `sales_order_tax_item`;
TRUNCATE TABLE `sales_payment_transaction`;
TRUNCATE TABLE `sales_refunded_aggregated`;
TRUNCATE TABLE `sales_refunded_aggregated_order`;
TRUNCATE TABLE `sales_shipment`;
TRUNCATE TABLE `sales_shipment_comment`;
TRUNCATE TABLE `sales_shipment_grid`;
TRUNCATE TABLE `sales_shipment_item`;
TRUNCATE TABLE `sales_shipment_track`;
TRUNCATE TABLE `sales_shipping_aggregated`;
TRUNCATE TABLE `sales_shipping_aggregated_order`;
TRUNCATE TABLE `tax_order_aggregated_created`;
TRUNCATE TABLE `tax_order_aggregated_updated`;

SET FOREIGN_KEY_CHECKS = 1;

Monday, 13 November 2017

Magento 2 : Product Add/Update “Asymmetric transaction rollback.” error [SOLVED]

When creating a new product or update a product then trying to save get the following error message:

'Asymmetric transaction rollback error'
The issue is resolved and the following are the steps.
  1. Reindex by using the following command
    php bin/magento indexer:reindex
  2. run below commands
    rm -rf var/cache/*
    rm -rf var/page_cache/*
    rm -rf var/generation/*
  3. Give permissions to var/generation folder.
  4. Just you can change reindex mode for product related indexer ->Update by schedule. 
    1. Product Flat Data 
    2. Category Flat Data
    3. Category Products
    4. Product Categories
    5. Product Price
    6. Product EAV 

Thursday, 26 October 2017

Magento 2 : Create Review & Rating programmatically from other db or csv?

This code is for import reviews from the other database table into magento2 product review.
Step1- Please empty review and rating tables.

Magento 2 Database table list.

  1. review
  2. review_detail
  3. review_entity_summary
  4. review_store
  5. rating_option_vote
  6. rating_option_vote_aggregated


Step2- Create 2 tables in your magento database test_customer and test_reviews.
CREATE TABLE `test_customer` (
  `customerid` int(11) NOT NULL,
  `firstname` varchar(255) NOT NULL,
  `lastname` varchar(255) NOT NULL,
  `emailaddress` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;



CREATE TABLE `test_reviews` (
  `id` int(11) NOT NULL,
  `lastmodified` varchar(255) NOT NULL,
  `productcode` varchar(255) NOT NULL,
  `reviewtitle` varchar(255) NOT NULL,
  `rate` varchar(255) NOT NULL,
  `customerid` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `location` varchar(255) NOT NULL,
  `active` varchar(255) NOT NULL,
  `reviewdescription` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;



Here you can insert the data from your csv's or other database

Step3- create a php page and paste the below code.

<?php
error_reporting(E_ALL);
set_time_limit(0);
ini_set('display_errors', '1');
ini_set('max_execution_time', 0);
ini_set('memory_limit', '3072M');
ini_set('auto_detect_line_endings', TRUE);

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();


//Get Customer email for oldsite
function get_customer_email($id)
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
    $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
    $connection = $resource->getConnection();
    $sql = "Select * FROM test_customer_au where customerid=".$id;
    $result = $connection->fetchAll($sql);
   if(count($result)>0){
    $email= $result[0]['emailaddress'];
   }
   else{$email= 'abc@testwebsite.com';}
 
    return $email;
}

// start code where old site review
/*
 * Select * FROM test_reviews where 1
 * I got all the reivew by this query.
 *
 *
 * */

$sql = "Select * FROM test_reviews where 1 ";
$result = $connection->fetchAll($sql);


foreach($result as $kk){
 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
    $customerId = '1234'; // default userid in my case when user is not avalable other wise blank
    $nickname= $kk['name'].', '.$kk['location'];
    $timestamp = '';
    $new_date_format = '';
    $timestamp = strtotime($kk['lastmodified']);
    $new_date_format = date('Y-m-d H:i:s', $timestamp);
 
   // Load product data
    $sku =$kk['productcode'];  
    $productObject = $objectManager->get('Magento\Catalog\Model\Product');
    $product = $productObject->loadByAttribute('sku', $sku);
    $productId = $product->getId();
 
    // Load customer data
    /*
*  I load email id from here by the mapping of ID from the magento2 and custom table using function
* get_customer_email()
*
* */
    if($kk['customerid']!=""){
        $email = get_customer_email($kk['customerid']);
        $customerObj = $objectManager->create('Magento\Customer\Model\ResourceModel\Customer\Collection');
        $collection = $customerObj->addAttributeToSelect('*')
        ->addAttributeToFilter('email',$email)
        ->load();
 
       $cdata=$collection->getData();
       if(isset($cdata[0]['entity_id']) && $cdata[0]['entity_id']!=''){$customerId = $cdata[0]['entity_id'];}else{$customerId = '4611';}
 
    }
 
  // Save Reviews
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

     if($kk['active']=="Y"){
$_review = $objectManager->get("Magento\Review\Model\Review")
        ->setEntityPkValue($productId)//product Id
        ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED)// approved /PENDING
        ->setTitle($kk['reviewtitle'])
        ->setDetail($kk['reviewdescription'])
        ->setEntityId(1)
        ->setStoreId(2)
        ->setStores(2)
        ->setCustomerId($customerId)//get dynamically here
        ->setNickname($nickname)
        ->save();
    }
    if($kk['active']=="N"){
$_review = $objectManager->get("Magento\Review\Model\Review")
        ->setEntityPkValue($productId)//product Id
        ->setStatusId(\Magento\Review\Model\Review::STATUS_PENDING)// approved /PENDING
        ->setTitle($kk['reviewtitle'])
        ->setDetail($kk['reviewdescription'])
        ->setEntityId(1)
        ->setStoreId(2)
        ->setStores(2)
        ->setCustomerId($customerId)//get dynamically here
        ->setNickname($nickname)
        ->save();
    }
 
   // echo "Review Has been saved ";
 
    /*
    $_ratingOptions = array(
        1 => array(1 => 1,  2 => 2,  3 => 3,  4 => 4,  5 => 5), //quality
        2 => array(1 => 6,  2 => 7,  3 => 8,  4 => 9,  5 => 10),//value
        3 => array(1 => 11, 2 => 12, 3 => 13, 4 => 14, 5 => 15),//price
        4 => array(1 => 16, 2 => 17, 3 => 18, 4 => 19, 5 => 20) //rating
    );
    */
 
    //just Assume user selected rating options
    $ratingOptions ='';
    if($kk['rate'] == "1")
    {
        $ratingOptions = array(
           // '1' => '1',
           // '2' => '7',
           // '3' => '13',
            '4' => '16',
        );
    }
    if($kk['rate'] == "2")
    {
        $ratingOptions = array(
           // '1' => '1',
           // '2' => '7',
           // '3' => '13',
            '4' => '17',
        );
    }
    if($kk['rate'] == "3")
    {
        $ratingOptions = array(
           // '1' => '1',
           // '2' => '7',
           // '3' => '13',
            '4' => '18',
        );
    }
    if($kk['rate'] == "4")
    {
        $ratingOptions = array(
           // '1' => '1',
           // '2' => '7',
           // '3' => '13',
            '4' => '19',
        );
    }
    if($kk['rate'] == "5")
    {
        $ratingOptions = array(
           // '1' => '1',
           // '2' => '7',
           // '3' => '13',
            '4' => '20',
        );
    }
 
    foreach ($ratingOptions as $ratingId => $optionIds) {
        $objectManager->get("Magento\Review\Model\Rating")
            ->setRatingId($ratingId)
            ->setReviewId($_review->getId())
            ->addOptionVote($optionIds, $productId);
    }
 
    // generates summary
            $_review->aggregate();
            // if you want to save review in previous dates
            $_review->setCreatedAt($new_date_format);
            $_review->save();
         

echo "<br/>Rating has been saved success !!!!!!!!!= ".$_review->getId();

}


?>





Wednesday, 18 October 2017

Magento 2 : issues with M2E Pro 'Duplicated line on invoice/order for configurable product'[solved]

Duplicated line on invoice/order for configurable product

When configurable product is ordered, Magento show 2 lines in order (and in invoice)
configurable product generates 2 lines : one with the actual price and the other one with $0 price.

Go this location:
app/code/Ess/M2ePro/Plugin/Order/Magento/Quote/Model/Quote/Item/

Replace 2 function :

public function aroundConvert($interceptor, \Closure $callback, $item)
    {
        return $this->execute('convert', $interceptor, $callback, [$item]);
    }

    // ---------------------------------------

    protected function processConvert($interceptor, \Closure $callback, $arguments)
    {
        $orderItem = $callback($arguments[0]);

        $this->eventManager->dispatch(
            'ess_sales_convert_quote_item_to_order_item',
            [
                'order_item' => $orderItem,
                'item' => $arguments[0],
            ]
        );

        return $orderItem;
    }
 

    To:
 
 
   public function aroundConvert($interceptor, \Closure $callback, ...$arguments)
    {
        return $this->execute('convert', $interceptor, $callback, $arguments);
    }

    // ---------------------------------------

    protected function processConvert($interceptor, \Closure $callback, $arguments)
    {
        $orderItem = $callback(...$arguments);

        $this->eventManager->dispatch(
            'ess_sales_convert_quote_item_to_order_item',
            [
                'order_item' => $orderItem,
                'item' => $arguments[0],
            ]
        );

        return $orderItem;
    }
    

Thursday, 20 July 2017

Kuldeep Singh Dagar: [SOLVED] Magento ver. 1.9.*.* Cant view product im...

Kuldeep Singh Dagar: [SOLVED] Magento ver. 1.9.*.* Cant view product im...: Problem Reasons: Wrong permissions set to uploaded files Solution: Open /lib/Varien/File/Uploader.php and make sure following permission...

[SOLVED] Magento ver. 1.9.*.* Cant view product images in admin after upload

Problem Reasons:

  • Wrong permissions set to uploaded files Solution: Open /lib/Varien/File/Uploader.php and make sure following permissions are set at chmod($destinationFile, 0640);. This code will be at around line 219.



  • Replace: line no 219 -  chmod($destinationFile, 0640); to chmod($destinationFile, 0644); or as per requirement.



  • Then rename .htaccess file to .htaccess.old in /media folder.


I tried the solution and it work fine. 

Please feel free to contact me any Magento issue at any time. 

Regards
Kuldeep
kuldeep4110@gmail.com