Get Customer ID in Home Page - Magento 2 - php

I need to get the Customer ID primary in Home Page, but not have a Session Interface to give this information.
I tried theses:
\Magento\Backend\Model\Session
\Magento\Catalog\Model\Session
\Magento\Checkout\Model\Session
\Magento\Customer\Model\Session
\Magento\Newsletter\Model\Session
Exists one interface to give Customer ID on every page?

There are methods available in magento2 to get customer id, one of the method is using Object Manager as below code.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
$customerId = $customerSession->getCustomer()->getId(); // get the customer Id

namespace Vendor\Module\Block;
class Form extends \Magento\Framework\View\Element\Template
protected $customerSession;
/**
* Construct
*
* #param \Magento\Framework\View\Element\Template\Context $context
* #param \Magento\Customer\Model\Session $customerSession
* #param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
array $data = []
) {
parent::__construct($context, $data);
$this->customerSession = $customerSession;
}
public function _prepareLayout()
{
var_dump($this->customerSession->getCustomer()->getId());
exit();
return parent::_prepareLayout();
}

Related

bavix/laravel-wallet new updated function to get transfers data from database in laravel

I have created a tiktok like app which retrieve data from mysql database using api from laravel, first i was using bavix/laravel-wallet package version 5.3.2. to create a virtual wallet for gift system in the app. And i have a function which used to send gift to another user (coins) and that user receive gifts in his wallet, i display a list of the Items which contain a number and value of the gifts he received from other users so he can redeem them later.
below is the class which was used to retrieve list of the gift of the user to and display on his wallet ready to be redeemed..
<?php
namespace App\Http\Resources;
use App\Models\Item as ItemModel;
use Bavix\Wallet\Models\Transfer;
use Illuminate\Http\Resources\Json\JsonResource;
class Gift extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
static $currency;
if (empty($currency)) {
$code = setting('payment_currency', config('fixtures.payment_currency'));
$symbol = $code;
$currency = $symbol !== $code ? $symbol : $code;
}
$data = [];
/** #var \App\Models\User $this */
/** #var ItemModel $item */
foreach (ItemModel::get() as $item) {
$transfers = $this->transfers()
->where('to_type', $item->getMorphClass())
->where('to_id', $item->getKey())
->where('status', Transfer::STATUS_PAID)
->count();
$data[] = [
'item' => Item::make($item),
'balance' => $transfers,
'value' => sprintf('%s%.2f', $currency, ($item->value * $transfers) / 100),
];
}
return $data;
}
}
The above class was getting a list of all the gifts which was received by the current user in the transfers table and 'to_type' column was returning the Item modal(App/Models/Item) and i was get the result correctly.
But the question here is when i update my laravel to verion 9 and bavix/laravel-wallet to version 9.0 the transfers variable return 0 data from the database because 'to_type' column in database change and does not return Item modal anymore otherwise it returning the Wallet Model and I have no idea how to change my codes to get the same result as from the previous versions.
I read the package documentation but i did not get any luck.
Below is the Item Model class ...
<?php
namespace App\Models;
use Bavix\Wallet\Interfaces\Customer;
use Bavix\Wallet\Interfaces\ProductInterface;
use Bavix\Wallet\Traits\HasWallet;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
class Item extends Model implements ProductInterface
{
use HasWallet, LogsActivity;
// protected static $logFillable = true;
// protected static $logOnlyDirty = true;
protected $fillable = [
'name', 'image', 'price', 'value', 'minimum',
];
/**
* #param Customer $customer
* #param int $quantity
* #param bool $force
*
* #return bool
*/
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logFillable()
->logOnlyDirty();
}
public function canBuy(Customer $customer, int $quantity = 1, bool $force = null): bool
{
return true;
}
public function getAmountProduct(Customer $customer): int|string
{
return $this->price;
}
public function getDescriptionForEvent(string $event): string
{
return sprintf('Item "%s" was %s.', $this->name, $event);
}
/**
* #return array
*/
public function getMetaProduct(): ?array
{
return ['title' => $this->name];
}
/**
* #return string
*/
public function getUniqueId(): string
{
return (string)$this->getKey();
}
}
Below is the item Db...
Below is the Transfer table
Below is the Wallet Table
Anyone who can help or get any direction on where to read so i can understand how to accomplish that..

Display flat rate on magento 2 product page

I want to display flat rate on magento 2 product page. I have that code from here:
https://www.magentoextensions.org/documentation/_carrier_2_flatrate_8php_source.html
Code:
<?php
namespace Vendor\MariuszModule\Block;
use Magento\OfflineShipping\Model\Carrier\Flatrate\ItemPriceCalculator;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Carrier\AbstractCarrier;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Magento\Shipping\Model\Rate\Result;
/**
* Class MariuszModule
* #package Vendor\MariuszModule\Block
*/
class MariuszModule extends \Magento\Framework\View\Element\Template
{
/**
* #var Http
*/
protected $request;
/**
* MariuszModule constructor.
* #param \Magento\Backend\Block\Template\Context $context
* #param \Magento\Framework\App\Request\Http $request
* #param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\App\Request\Http $request,
\Magento\OfflineShipping\Model\Carrier\Flatrate $flatRate,
\Magento\Quote\Model\Quote\Address\RateRequest $rateRequest,
\Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
\Magento\OfflineShipping\Model\Carrier\Flatrate\ItemPriceCalculator $itemPriceCalculator,
array $data = [])
{
$this->request = $request;
$this->itemPriceCalculator = $itemPriceCalculator;
$this->_rateResultFactory = $rateResultFactory;
$this->flatRate = $flatRate;
$this->rateRequest = $rateRequest;
parent::__construct($context, $data);
}
public function saleble()
{
$flatRate = $this->flatRate;
$rateRequest = $this->rateRequest;
$freeBoxes = $flatRate->getFreeBoxesCount($rateRequest);
return $flatRate->getShippingPrice($rateRequest,$freeBoxes);
}
}
But my code display nothing. I really dont know why this don't work.
Thanks for some help

How would one construct a complex/composite controller for multiple controllers

I am new to OOP/MVC and I do have a basic understanding of a controller which interacts with an underlying model. Basically, a controller acts as a "CRUD gateway" to a model. However, consider an e-commerce marketplace object: Order.
An e-commerce order in a marketplace would interact with multiple tables and hence an order can be thought of as a join of multiple tables: orders, order_items, order_sellers, order_buyer (and more perhaps).
If I understand it correctly, each one of these tables would have a controller allowing CRUD operations (OrderInfoController, OrderItemController,OrderSellerController,OrderBuyerController etc.).
However, could I also create a controller for 'Orders' which then instantiates the Controller Object for each of the tables involved in an Order?
OrderController {
$this->orderInfo = OrderInfo Object;
$this->orderItems = array of Order Item Objects;
$this->orderSellers = array of Order Seller Objects;
$this->orderBuyer = OrderBuyer Object;
function create($arr_order)
//create the order object by calling each of the member controllers.
function get($orderId)
//get the complete order by order Id....
function update($orderId)
function delete($orderId)
}
I have gone through a few MVC docs but I have not come across a solution to this problem. My question is then: Is this the correct approach to write a controller which interacts with multiple tables?
To
If I understand it correctly, each one of these tables would have a controller allowing CRUD operations [...].
In a web MVC-based application, each request is, indeed, served by a controller (the "C" in "MVC").
Though, the controller delegates the whole processing of the request to one or more application services (e.g. use cases, e.g actions - see resources list below), as part of the service layer. These services interact with the model (the "M" in "MVC"), e.g. domain model, e.g. model layer, which, in turn, interact with the database.
The final result of the processing of the request data, e.g. the response object, is either returned to the controller, in order to be passed and printed on screen by the view (the "V" in "MVC"), or directly to the view, for the same reason.
After watching both videos in the resources list below, you will understand, that the model doesn't need to know anything about the database. So, the components of the model layer (mostly interfaces) should not know where and how the data passed to them by the services is saved. Therefore, the services and the controllers should also know nothing about the database.
All informations regarding the database should be located in data mappers only - as part of the infrastructure layer. These objects should be the only ones understanding the database API. Therefore, the only ones containing and beeing able to execute SQL statements.
To
Is this the correct approach to write a controller which interacts with multiple tables?
No. But it's not a problem. Just keep learning about MVC.
Resources:
Keynote: Architecture the Lost Years by Robert Martin.
Sandro Mancuso : Crafted Design
Here is some code of mine. At first sight, it's maybe a lot of it, but I'm confident, that it will help you to better understand.
For simplicity, follow the definition of the method getAllUsers in the view class SampleMvc\App\View\Template\Users\Users.
First of all, here is a not so important note (yet): In my code, the controller only updates the model layer, and the view only fetches data from the model layer. Only the response returned by the view is, therefore, printed. The controller and the view are called by a class RouteInvoker, like this:
<?php
namespace MyPackages\Framework\Routing;
//...
class RouteInvoker implements RouteInvokerInterface {
//...
public function invoke(RouteInterface $route): ResponseInterface {
$controller = $this->resolveController($route);
$view = $this->resolveView($route);
$parameters = $route->getParameters();
$this->callableInvoker->call($controller, $parameters);
return $this->callableInvoker->call($view, $parameters);
}
//...
}
The result ($response) of RouteInvoker:invoke is printed like this:
$responseEmitter->emit($response);
And from here follows an example of a code invoked by RouteInvoker:invoke:
A controller to handle the users:
<?php
namespace SampleMvc\App\Controller\Users;
use function sprintf;
use SampleMvc\App\Service\Users\{
Users as UserService,
Exception\UserExists,
};
use Psr\Http\Message\ServerRequestInterface;
/**
* A controller to handle the users.
*/
class Users {
/**
*
* #param UserService $userService A service to handle the users.
*/
public function __construct(
private UserService $userService
) {
}
/**
* Add a user.
*
* #param ServerRequestInterface $request A server request.
* #return void
*/
public function addUser(ServerRequestInterface $request): void {
$username = $request->getParsedBody()['username'];
try {
$this->userService->addUser($username);
} catch (UserExists $exception) {
//...
}
}
/**
* Remove all users.
*
* #return void
*/
public function removeAllUsers(): void {
$this->userService->removeAllUsers();
}
}
A view to handle the users:
Notice, that controller and view share the same UserService instance.
<?php
namespace SampleMvc\App\View\Template\Users;
use SampleMvc\App\{
View\Layout\Primary,
Service\Users\Users as UserService,
Components\Service\MainNavigation,
};
use Psr\Http\Message\{
ResponseInterface,
ResponseFactoryInterface,
};
use AlePackages\Template\Renderer\TemplateRendererInterface;
/**
* A view to handle the users.
*/
class Users extends Primary {
/**
*
* #param UserService $userService A service to handle the users.
*/
public function __construct(
ResponseFactoryInterface $responseFactory,
TemplateRendererInterface $templateRenderer,
MainNavigation $mainNavigationService,
private UserService $userService
) {
parent::__construct($responseFactory, $templateRenderer, $mainNavigationService);
}
/**
* Display the list of users.
*
* #return ResponseInterface The response to the current request.
*/
public function default(): ResponseInterface {
$bodyContent = $this->templateRenderer->render('#Templates/Users/Users.html.twig', [
'activeNavItem' => 'Users',
'users' => $this->getAllUsers(),
]);
$response = $this->responseFactory->createResponse();
$response->getBody()->write($bodyContent);
return $response;
}
/**
* Add a user.
*
* #return ResponseInterface The response to the current request.
*/
public function addUser(): ResponseInterface {
$bodyContent = $this->templateRenderer->render('#Templates/Users/Users.html.twig', [
'activeNavItem' => 'Users',
'message' => 'User successfully added',
'users' => $this->getAllUsers(),
]);
$response = $this->responseFactory->createResponse();
$response->getBody()->write($bodyContent);
return $response;
}
/**
* Remove all users.
*
* #return ResponseInterface The response to the current request.
*/
public function removeAllUsers(): ResponseInterface {
$bodyContent = $this->templateRenderer->render('#Templates/Users/Users.html.twig', [
'activeNavItem' => 'Users',
'message' => 'All users successfully removed',
'users' => $this->getAllUsers(),
]);
$response = $this->responseFactory->createResponse();
$response->getBody()->write($bodyContent);
return $response;
}
/**
* Get a list of users.
*
* #return (string|int)[][] The list of users.
*/
private function getAllUsers(): array {
$users = $this->userService->findAllUsers();
$usersFormatted = [];
foreach ($users as $user) {
$usersFormatted[] = [
'id' => $user->getId(),
'username' => $user->getUsername(),
];
}
return $usersFormatted;
}
}
A service to handle the users:
<?php
namespace SampleMvc\App\Service\Users;
use SampleMvc\Domain\Model\User\{
User,
UserCollection,
};
use SampleMvc\App\Service\Users\Exception\UserExists;
/**
* A service to handle the users.
*/
class Users {
/**
*
* #param UserCollection $userCollection A collection of users.
*/
public function __construct(
private UserCollection $userCollection
) {
}
/**
* Find a user by id.
*
* #param int $id An id.
* #return User|null The found user or null.
*/
public function findUserById(int $id): ?User {
return $this->userCollection->findById($id);
}
/**
* Find all users.
*
* #return User[] The list of users.
*/
public function findAllUsers(): array {
return $this->userCollection->all();
}
/**
* Add a user.
*
* #param string|null $username A username.
* #return User The added user.
*/
public function addUser(?string $username): User {
$user = $this->createUser($username);
return $this->storeUser($user);
}
/**
* Remove all users.
*
* #return void
*/
public function removeAllUsers(): void {
$this->userCollection->clear();
}
/**
* Create a user.
*
* #param string|null $username A username.
* #return User The user.
*/
private function createUser(?string $username): User {
$user = new User();
$user->setUsername($username);
return $user;
}
/**
* Store a user.
*
* #param User $user A user.
* #return User The stored user.
* #throws UserExists A user already exists.
*/
private function storeUser(User $user): User {
if ($this->userCollection->exists($user)) {
throw new UserExists('Username "' . $user->getUsername() . '" already used');
}
return $this->userCollection->store($user);
}
}
An exception indicating that a user already exists:
<?php
namespace SampleMvc\App\Service\Users\Exception;
/**
* An exception indicating that a user already exists.
*/
class UserExists extends \OverflowException {
}
An interface to a collection of users:
Notice, that this is an interface.
Notice, that this interface is a component of the domain model!
Notice, that its implementation (e.g. SampleMvc\Domain\Infrastructure\Repository\User\UserCollection further down below) is not part of the domain model, but of the infrastructure layer!
<?php
namespace SampleMvc\Domain\Model\User;
use SampleMvc\Domain\Model\User\User;
/**
* An interface to a collection of users.
*/
interface UserCollection {
/**
* Find a user by id.
*
* #param int $id An id.
* #return User|null The found user or null.
*/
public function findById(int $id): ?User;
/**
* Get all users from the collection.
*
* #return User[] All users in the collection.
*/
public function all(): array;
/**
* Store a user.
*
* #param User $user A user.
* #return User The stored user.
*/
public function store(User $user): User;
/**
* Check if a user exists in the collection.
*
* #param User $user A user.
* #return bool True if the user exists, or false otherwise.
*/
public function exists(User $user): bool;
/**
* Remove all users from the collection.
*
* #return static
*/
public function clear(): static;
}
A collection of users:
<?php
namespace SampleMvc\Domain\Infrastructure\Repository\User;
use SampleMvc\Domain\Model\User\{
User,
UserCollection as UserCollectionInterface,
};
use SampleMvc\Domain\Infrastructure\Mapper\User\UserMapper;
/**
* A collection of users.
*/
class UserCollection implements UserCollectionInterface {
/**
*
* #param UserMapper $userMapper A user mapper.
*/
public function __construct(
private UserMapper $userMapper
) {
}
/**
* #inheritDoc
*/
public function findById(int $id): ?User {
return $this->userMapper->fetchUserById($id);
}
/**
* #inheritDoc
*/
public function all(): array {
return $this->userMapper->fetchAllUsers();
}
/**
* #inheritDoc
*/
public function store(User $user): User {
return $this->userMapper->saveUser($user);
}
/**
* #inheritDoc
*/
public function exists(User $user): bool {
return $this->userMapper->userExists($user);
}
/**
* #inheritDoc
*/
public function clear(): static {
$this->userMapper->deleteAllUsers();
return $this;
}
}
An interface to a user mapper:
Notice that this is the interface of a data mapper.
<?php
namespace SampleMvc\Domain\Infrastructure\Mapper\User;
use SampleMvc\Domain\Model\User\User;
/**
* An interface to a user mapper.
*/
interface UserMapper {
/**
* Fetch a user by id.
*
* Note: PDOStatement::fetch returns FALSE if no record is found.
*
* #param int $id A user id.
* #return User|null The user or null.
*/
public function fetchUserById(int $id): ?User;
/**
* Fetch all users.
*
* #return User[] The list of users.
*/
public function fetchAllUsers(): array;
/**
* Save a user.
*
* #param User $user A user.
* #return User The saved user.
*/
public function saveUser(User $user): User;
/**
* Check if a user exists.
*
* Note: PDOStatement::fetch returns FALSE if no record is found.
*
* #param User $user A user.
* #return bool True if the user exists, or false otherwise.
*/
public function userExists(User $user): bool;
/**
* Delete all users.
*
* #return static
*/
public function deleteAllUsers(): static;
}
A PDO user mapper:
Notice, that this component is the implementation of a data mapper.
Notice, that this component is the only one understanding the database API. Therefore, the only one containing and beeing able to execute SQL statements.
Notice, that this component is not part of the domain model, but of the infrastructure layer!
(1) Notice, that you can write any SQL statements that you want, including JOIN statements. So, the fetched data can come from multiple tables as well.
(2) Notice also, that the result of a method of this class could be a list of objects of a type defined by you (!), independent of the underlying table(s) data..
The conclusion from (1) and (2) above: The database structure does NOT affect in any way the way in which your application is structured.
<?php
namespace SampleMvc\Domain\Infrastructure\Mapper\User;
use SampleMvc\Domain\{
Model\User\User,
Infrastructure\Mapper\User\UserMapper,
};
use PDO;
/**
* A PDO user mapper.
*/
class PdoUserMapper implements UserMapper {
/**
*
* #param PDO $connection A database connection.
*/
public function __construct(
private PDO $connection
) {
}
/**
* #inheritDoc
*/
public function fetchUserById(int $id): ?User {
$sql = 'SELECT * FROM users WHERE id = :id LIMIT 1';
$statement = $this->connection->prepare($sql);
$statement->execute([
'id' => $id,
]);
$dataArray = $statement->fetch(PDO::FETCH_ASSOC);
return ($dataArray === false) ? null : $this->convertDataArrayToUser($dataArray);
}
/**
* #inheritDoc
*/
public function fetchAllUsers(): array {
$sql = 'SELECT * FROM users';
$statement = $this->connection->prepare($sql);
$statement->execute();
$listOfDataArrays = $statement->fetchAll(PDO::FETCH_ASSOC);
return $this->convertListOfDataArraysToListOfUsers($listOfDataArrays);
}
/**
* #inheritDoc
*/
public function saveUser(User $user): User {
return $this->insertUser($user);
}
/**
* #inheritDoc
*/
public function userExists(User $user): bool {
$sql = 'SELECT COUNT(*) as cnt FROM users WHERE username = :username';
$statement = $this->connection->prepare($sql);
$statement->execute([
':username' => $user->getUsername(),
]);
$data = $statement->fetch(PDO::FETCH_ASSOC);
return ($data['cnt'] > 0) ? true : false;
}
/**
* #inheritDoc
*/
public function deleteAllUsers(): static {
$sql = 'DELETE FROM users';
$statement = $this->connection->prepare($sql);
$statement->execute();
return $this;
}
/**
* Insert a user.
*
* #param User $user A user.
* #return User The user, with updated id.
*/
private function insertUser(User $user): User {
$sql = 'INSERT INTO users (username) VALUES (:username)';
$statement = $this->connection->prepare($sql);
$statement->execute([
':username' => $user->getUsername(),
]);
$user->setId($this->connection->lastInsertId());
return $user;
}
/**
* Update a user.
*
* #param User $user A user.
* #return User The user.
*/
private function updateUser(User $user): User {
$sql = 'UPDATE users SET username = :username WHERE id = :id';
$statement = $this->connection->prepare($sql);
$statement->execute([
':username' => $user->getUsername(),
':id' => $user->getId(),
]);
return $user;
}
/**
* Convert the given data array to a user.
*
* #param array $dataArray A data array.
* #return User The user.
*/
private function convertDataArrayToUser(array $dataArray): User {
$user = new User();
$user
->setId($dataArray['id'])
->setUsername($dataArray['username'])
;
return $user;
}
/**
* Convert the given list of data arrays to a list of users.
*
* #param array[] $listOfDataArrays A list of data arrays.
* #return User[] The list of users.
*/
private function convertListOfDataArraysToListOfUsers(array $listOfDataArrays): array {
$listOfUsers = [];
foreach ($listOfDataArrays as $dataArray) {
$listOfUsers[] = $this->convertDataArrayToUser($dataArray);
}
return $listOfUsers;
}
}

Magento 2 : How to get order id for a guest customer in controller after click on place order button?

I have created payment method module. In this module when i was logged in, it was successfully got order id from Magento\Quote\Api\CartManagementInterface interface. but when i was guest, i was not able to get order id from Magento\Quote\Api\CartManagementInterface interface.
I was search in google and found that, for guest customer interface was changed Magento\Quote\Api\GuestCartManagementInterface. I have also try this interface, but still not working for get order id of guest customer.
When i have click on place order button, My module controller is called.
My controller code is given below.
<?php
namespace Mageniks\Testpayment\Controller\Payment;
use Magento\Framework\Controller\ResultFactory;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Quote\Api\GuestCartManagementInterface;
class Redirect extends \Magento\Framework\App\Action\Action
{
/**
* Customer session model
*
* #var \Magento\Customer\Model\Session
*/
protected $_customerSession;
protected $resultPageFactory;
protected $_paymentMethod;
protected $_checkoutSession;
protected $checkout;
protected $cartManagement;
protected $guestcartManagement;
protected $orderRepository;
protected $_scopeConfig;
/**
* #param \Magento\Framework\App\Action\Context $context
* #param \Magento\Customer\Model\Session $customerSession
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Customer\Model\Session $customerSession,
\Mageniks\Testpayment\Model\PaymentMethod $paymentMethod,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
CartManagementInterface $cartManagement,
GuestCartManagementInterface $guestcartManagement
) {
$this->_customerSession = $customerSession;
parent::__construct($context);
$this->_paymentMethod = $paymentMethod;
$this->_checkoutSession = $checkoutSession;
$this->cartManagement = $cartManagement;
$this->guestcartManagement = $guestcartManagement;
$this->orderRepository = $orderRepository;
$this->_scopeConfig = $scopeConfig;
}
public function execute()
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
$orderId = '';
if($customerSession->isLoggedIn())
{
// FOR LOGIN CUSTOMER GET ORDER ID
$orderId = $this->cartManagement->placeOrder($this->_checkoutSession->getQuote()->getId());
}
else
{
// FOR GUEST CUSTOMER GET ORDER ID
try
{
$orderId = $this->guestcartManagement->placeOrder($this->_checkoutSession->getQuote()->getId());
} catch (\Exception $e)
{
echo $e->getMessage();
}
}
$order = $this->orderRepository->get($orderId);
if ($order){
$order->setState($this->_scopeConfig->getValue('payment/testpayment/new_order_status', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
$order->setStatus($this->_scopeConfig->getValue('payment/testpayment/new_order_status', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
$order->save();
}
}
}
?>
How can I get order id for guest customer in controller after click on place order button ? Please help me. Any help would be appreciated.
Thanks
Is the order correctly registered for guest customers ? Do you have any exceptions ?
Maybe you can try this :
$quote->setCustomerId(null)
->setCustomerEmail($quote->getBillingAddress()->getEmail())
->setCustomerIsGuest(true)
->setCustomerGroupId(Group::NOT_LOGGED_IN_ID);
$quote->collectTotals();
$orderId = $this->cartManagement->placeOrder($quote->getId());
I never tested my code without it though, but no matter the type of customer I always have my order id.

How can i save custom field value in customer_entity table in Magento 2 using observer

Below is my observer code:
<?php
class CustomerOrderCountObserver implements ObserverInterface
{
/**
* #var customerFactory
*/
private $customerFactory;
/**
*
* #param CustomerFactory $customerFactory
*/
public function __construct(
CustomerFactory $customerFactory
) {
$this->customerFactory = $customerFactory;
}
/**
* Upgrade customer password hash when customer has logged in
*
* #param \Magento\Framework\Event\Observer $observer
* #return void
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$orderInstance = $observer->getEvent()->getdata();
$orderIds = $observer->getEvent()->getdata('order_ids');
$orderCount = is_array($orderIds)?count($orderIds):0;
$orderId = current($orderIds);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$session = $objectManager->get('Magento\Customer\Model\Session');
if($session->isLoggedIn()) {
$customer = $this->customerFactory->create()->load($session->getCustomerId());
$orderCount = $orderCount + $customer->getOrderCount();
$customer->setOrderCount($orderCount);
$customer->save($customer);
}
}
}
I don't know what I am doing wrong with this. It is not saving the customer column value order_count
Try saving using the customer data changes using a resourceModel instead of saving using the model
$customerResourceModel->save($customer);
Try loading customer from model
$customer = Mage::getModel('customer/customer')->load($session->getCustomerId());

Categories