Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento 2 Add Product Review And Rating Programatically

In this post i am going to explain that how to create product review and rating programatically from csv file in Magento 2.

Magento 2 Add Product Review And Rating Programatically


Create import_review.php file in root of your magento and add following code.

<?php

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');

ini_set('display_errors', 1);

$file = fopen('products_review.csv', 'r');


$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$reviewFactory = $objectManager->get("Magento\Review\Model\ReviewFactory");
$ratingFactory = $objectManager->get("Magento\Review\Model\RatingFactory");
$storeManager = $objectManager->get("Magento\Store\Model\StoreManagerInterface");

$i = 0;
while (($line = fgetcsv($file)) !== FALSE) {
    if (count($line) > 0) {

        $sku = $line[0];
        $review_rating = $line[1];
        $reviewTitle = $line[2];
        $reviewDetail = $line[3];
        $UserEmail = $line[4];
        $customerId = 0;

        if ($i > 0) {
            $productId = $objectManager->get('Magento\Catalog\Model\Product')->getIdBySku($sku);

            if ($productId) {
                $reviewFinalData = array();
                $reviewFinalData['ratings'][1] = $review_rating;
                $reviewFinalData['ratings'][2] = $review_rating;
                $reviewFinalData['ratings'][3] = $review_rating;

                $reviewFinalData['nickname'] = "Guest";

                if ($UserEmail) {
                    $websiteId = $storeManager->getWebsite()->getWebsiteId();
                    $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');
                    $customer = $customerFactory->create();
                    $customer->setWebsiteId($websiteId);
                    $customer->loadByEmail($UserEmail);
                    $data = $customer->getData();
                    $customerId = $data['entity_id'];
                    $firstname = $data['firstname'];
                    $lastname = ($data['lastname'] ? " " . $data['lastname'] : "");
                    $reviewFinalData['nickname'] = $firstname . $lastname;
                }

                $reviewFinalData['title'] = $reviewTitle;
                $reviewFinalData['detail'] = $reviewDetail;

                $review = $reviewFactory->create()->setData($reviewFinalData);

                $review->unsetData('review_id');

                $review->setEntityId($review->getEntityIdByCode(\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE))
                        ->setEntityPkValue($productId)
                        ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED)//By default set approved
                        ->setStoreId($storeManager->getStore()->getId())
                        ->setStores([$storeManager->getStore()->getId()]);

                if ($customerId) {
                    $review->setCustomerId($customerId);
                }

                $review->save();

                foreach ($reviewFinalData['ratings'] as $ratingId => $optionId) {
                    $ratingFactory->create()
                            ->setRatingId($ratingId)
                            ->setReviewId($review->getId())
                            ->addOptionVote($optionId, $productId);
                }

                $review->aggregate();
            }
        }
    }
    $i++;
}
?>


You can download sample csv file and script from following link

Download

Basic Simple CRUD Application with Express and MongoDB

In this post i have created a basic simple application using Express and MongoDB to Create, Read, Update and Delete data in MongoDB.

Crud-express-mongodb


To use this application you need to install Node.js and also have some basic knowledge of typing commands.

To check if you have Node installed, open up your command line and run the following code:
node -v

In this example we are going to store databases on cloud like mlab.com. So you need to create your database before starting this. 

Now let's create required files step by step:

Step1: Create server.js file and add following code

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;

/////Body parser
app.use(bodyParser.urlencoded({extended: true}))
//app.use(bodyParser.json());
app.use(express.static('public'));
app.set('view engine', 'ejs')


/////MongoDB
var db;
var ObjectId = require('mongodb').ObjectID;

MongoClient.connect('your_mongodb_url', (err, database) => {
    if (err) {
        throw err;
    }

    db = database.db('db_name')
    db.collection('customer')
    app.listen(3000, () => {
        console.log('database connected listening on 3000');
    })
})

app.get('/', (req, res) => {
    db.collection('customer').find().toArray((err, result) => {
        if (err) {
            throw err;
        }
        res.render('index.ejs', {data: result})
    })
})

app.post('/addnew', (req, res) => {

    var myobj = {name: req.body.name, address: req.body.address};
    db.collection("customer").insertOne(myobj, function (err, result) {
        if (err) {
            throw err;
        }
        console.log("1 record inserted");
        res.redirect('/')
    });
})


////////////////////Update
app.get('/update/:id', (req, res) => {
    var user_id = req.params.id;
    console.log(user_id);
    var query = {_id: ObjectId(user_id)};
    db.collection("customer").find(query).toArray(function (err, result) {
        if (err) {
            throw err;
        }
        console.log(result);
        res.render('update.ejs', {data: result})
    });
})

app.post('/updatepost', (req, res) => {
    var myquery = {_id: ObjectId(req.body.id)};
    //var newvalues = {name: req.body.name, address: req.body.quote};
    var newvalues = {$set: {name: req.body.name, address: req.body.address}};
    var extra = {upsert: true};
    db.collection("customer").updateOne(myquery, newvalues, extra, function (err, result) {
        if (err) {
            throw err;
        }
        console.log("1 record updated");
        res.redirect('/')
    });
})


/////////////////Delete
app.get('/delete/:id', (req, res) => {
    var user_id = req.params.id;
    console.log(user_id);
    var query = {_id: ObjectId(user_id)};
    db.collection("customer").deleteOne(query, function (err, obj) {
        if (err) {
            throw err;
        }
        console.log("1 record deleted");
        res.redirect('/')
    });
})

Note: Replace 'your_mongodb_url' with your mongodb url and 'db_name' with the database name.

Step2: Create package.json file and add following code

{
  "name": "node",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js",
    "dev": "nodemon server.js"
  },
  "author": "Hardik Patel",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "ejs": "^2.5.7",
    "express": "^4.16.2",
    "mongodb": "^3.0.1"
  },
  "devDependencies": {
    "nodemon": "^1.14.7"
  }
}

Step3: Create new folder 'views'

Step4: In views folder create new file index.ejs and add following code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Basic CRUD Example</title>
</head>
<body>
  <ul class="quotes">
  <% for(var i=0; i<data.length; i++) {%>
    <li class="quote">
      <span><%= data[i].name %>: </span>
      <span><%= data[i].address %></span>
      <!--<span><%= data[i]._id %></span>-->
      <a href="update/<%= data[i]._id %>">Update</a>
      <a href="delete/<%= data[i]._id %>">Delete</a>
    </li>
  <% } %>
  </ul>

  <form action="/addnew" method="POST">
    <input type="text" placeholder="name" name="name">
    <input type="text" placeholder="address" name="address">
    <button type="submit">Submit</button>
  </form>
</body>
</html>

Step5: In views folder create new file update.ejs and add following code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Basic CRUD Example</title>
</head>
<body>
  <form action="/updatepost" method="POST">
    <input style="width:300px;" type="text" placeholder="name" name="name" value="<%= data[0].name %>">
    <br><br>
    <input style="width:300px;" type="text" placeholder="address" name="address" value="<%= data[0].address %>">
    <br><br>
    <input style="width:300px;" type="text" placeholder="id" name="id" value="<%= data[0]._id %>">
    <br><br>
    <a href="/">Back</a>
    <button type="submit">Update</button>

  </form>
</body>
</html>

Note: Make sure you have added all required node module in your application. You can download required module from here.


Download

PayEase Payment Gateway For Magento 2

PayEase is the payment service provider in China. After converting our client site to Magento 2, i tried to find Payease payment extension. But unfortunately Payease was not there. So we are unable to process payment without Payease payment method. That is why i have developed my custom PayEase extension for Magento 2. I hope this will help someone else.

payease-payment-method-magento2


Download

Magento2 – Write Custom Mysql Query In External File

Here we learn how to write custom mysql add, update or delete query in external file

Suppose we have table ’employee’ with fields emp_id, emp_name, emp_code and emp_salary.

use Magento\Framework\App\Bootstrap;
require $_SERVER["DOCUMENT_ROOT"] . '/app/bootstrap.php';
 
$params = $_SERVER;
 
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('employee'); //table name with prefix

//Select Data from table
$sql = "Select * FROM " . $tableName;
$result = $connection->fetchAll($sql); // gives associated array, table fields as key in array.
 
//Delete Data from table
$sql = "Delete FROM " . $tableName." Where emp_id = 10";
$connection->query($sql);
 
//Insert Data into table
$sql = "Insert Into " . $tableName . " (emp_id, emp_name, emp_code, emp_salary) Values ('','XYZ','ABD20','50000')";
$connection->query($sql);
 
//Update Data into table
$sql = "Update " . $tableName . "Set emp_salary = 20000 where emp_id = 12";
$connection->query($sql);

Magento 2 Stock control issue in Cancelled/Failed order

I experience a problem with stock control in Magento 2. After placing an order, the inventory is reduced. However, when i cancel the payment, the qty is increased by 2. It looks like restoring the cart results in increasing the stocks, as well as canceling the order. So i think there is something wrong in magento's restore cart function.

You can remove the event that increases the stock on restoring a quote.
This will require an edit in a magento core file.

In: vendor/magento/module-catalog-inventory/etc/events.xml

remove:

<event name="restore_quote">
  <observer name="inventory" instance="Magento\CatalogInventory\Observer\RevertQuoteInventoryObserver"/>
</event>

 

Copyright @ 2017 HKBlog.