Is magento store, user product visit history?
If yes then how can I fetch it or
if no then how can I do it?
Any web link or resource would be highly appreciated.
You can create an observer using the catalog_product_load_after event:
<global>
<events>
<catalog_product_load_after>
<observers>
<yournamespace_yourmodulename>
<type>model</type>
<class>yournamespace_yourmodulename/observer</class>
<method>saveProductVisitHistory</method>
</yournamespace_yourmodulename>
</observers>
</catalog_product_load_after>
</events>
</global>
And in the observer get the data which you need and save it somewhere:
public function saveProductVisitHistory(Varien_Event_Observer $observer) {
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customer = Mage::getSingleton('customer/session')->getCustomer();
Mage::log('Customer ID: '.$customer->getId(), null, 'custom.log');
$product = $observer->getEvent()->getProduct();
Mage::log('Visited Product ID: '.$product->getId(), null, 'custom.log');
}
}
Related
I have a page comp/computer?id=15
it has reviews that can be edited through link
http://comp/computer/update?id=3 = with FORM and submit button
how to go back after sumbit
public function actionUpdate($id)
{
$model = new ReviewForm();
$comment = Review::findOne($id);
if ($model->load($this->request->post())) {
$comment->text = $model->text;
if ($comment->save(false)) {
return $this->redirect(["?id=15"], ); ????????????
}
Yii::$app->session->setFlash(
'success',
'Success'
);
}
$model->setAttributes($comment->getAttributes(['name', 'email', 'text']));
return $this->render('update', compact('model'));
}
simply use referrer.
return $this->redirect(Yii::$app->request->referrer)
If it has no referrer or link open directly then you should either pass computer_id as param or you must have computer_id as foreign key in your review table.
Let say you have relationship with review and computer table. then you can use like this.
$compId = $comment->computer_id; // or 15 or you can paas param here
return $this->redirect(["comp/computer", "id"=> $compId]);
if comp is your hostname then
return $this->redirect(["computer", "id"=> $compId]);
its should be controller/action
return $this->redirect(["controllerId/actionId", "id"=> $compId]);
Send via mobile, sorry for typos.
I am trying to get a magento 2 shop up. I managed to install everything, but I am missing the link to get the invoice as a pdf on the frontend (which is mandatory for my clients). Here's what I have:
As you can see, i have all the links to print the order, the invoice and All invoices, but they all take me to a html page, that prints like it, which is pretty annoying. I can't manage to find any solution to this problem. Is this a base feature in magento or do i really need to pay and install another module in order to achieve this? Thanks in advance.
We managed to finally get the answer to this problem by just adding a module to our magento 2 installation.
I provide the link of it.
https://www.mageplaza.com/magento-2-pdf-invoice-extension/
It is working well for the past month now.
Create your module Vendor_Module
Create route app/code/Vendor/Module/etc/frontend/routes.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="myroute" frontName="myroute">
<module name="Vendor_Module"/>
</route>
</router>
</config>
Create front controller app/code/Vendor/Module/Controller/Getpdf/Invoice.php
<?php
declare(strict_types=1);
namespace Vendor\Module\Controller\Getpdf;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Response\RedirectInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Controller\ResultFactory;
use Magento\Sales\Model\Order\Pdf\Invoice as PdfInvoice;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Sales\Model\ResourceModel\Order\Invoice\CollectionFactory;
use Magento\Framework\Message\ManagerInterface;
class Invoice implements HttpGetActionInterface
{
const SELECTED_PARAM = 'id';
protected FileFactory $fileFactory;
protected DateTime $dateTime;
protected PdfInvoice $pdfInvoice;
protected RequestInterface $request;
protected RedirectInterface $redirect;
protected ManagerInterface $messageManager;
protected ResultFactory $resultFactory;
protected CollectionFactory $collectionFactory;
/**
* #param DateTime $dateTime
* #param FileFactory $fileFactory
* #param PdfInvoice $pdfInvoice
* #param CollectionFactory $collectionFactory
* #param RequestInterface $request
* #param RedirectInterface $redirect
* #param ManagerInterface $messageManager
* #param ResultFactory $resultFactory
*/
public function __construct(
DateTime $dateTime,
FileFactory $fileFactory,
PdfInvoice $pdfInvoice,
CollectionFactory $collectionFactory,
RequestInterface $request,
RedirectInterface $redirect,
ManagerInterface $messageManager,
ResultFactory $resultFactory
)
{
$this->fileFactory = $fileFactory;
$this->dateTime = $dateTime;
$this->pdfInvoice = $pdfInvoice;
$this->request = $request;
$this->redirect = $redirect;
$this->messageManager = $messageManager;
$this->resultFactory = $resultFactory;
$this->collectionFactory = $collectionFactory;
}
/**
* #return ResponseInterface|\Magento\Framework\Controller\Result\Redirect|\Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
try {
$collection = $this->collectionFactory->create();
$invoiceId = $this->request->getParam(self::SELECTED_PARAM);
$filterIds = $invoiceId ? [$invoiceId] : [];
$collection->addFieldToFilter(
$collection->getResource()->getIdFieldName(),
['in' => $filterIds]
);
$pdf = $this->pdfInvoice->getPdf($collection);
$fileContent = ['type' => 'string', 'value' => $pdf->render(), 'rm' => true];
return $this->fileFactory->create(
sprintf('invoice%s.pdf', $this->dateTime->date('Y-m-d_H-i-s')),
$fileContent,
DirectoryList::VAR_DIR,
'application/pdf'
);
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$resultRedirect->setUrl($this->redirect->getRefererUrl());
return $resultRedirect;
}
}
}
Now you are ready to use this controller. Just create a link and put there href with a path to our controller (In some cases it is a good idea to use Magento\Sales\Block\Order\Info as a class to your block for getting order like $order = $block->getOrder();)
Having an order information you can get invoices in your .phtml file
<?php foreach ($order->getInvoiceCollection() as $invoice):?>
<?php echo $this->escapeHtml(__('Invoice (PDF)')); ?>
<?php endforeach;?>
I have a bidirectional OneToMany relationship between the entites Basket and ProductOrder.
#OneToMany(mappedBy = "basket", cascade = CascadeType.ALL)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<ProductOrder> products = new HashSet<>();
and
#ManyToOne
#JsonIgnoreProperties("products")
private Basket basket;
When I add a new productOrder to the basket and call the update method on the basket. The productOrder is being created but gets no reference to the basket which results in the basket having no productOrders!
I tried setting the basket from the productOrder but then it ends in a endless circle and I get:
ERROR TypeError: Converting circular structure to JSON
So my question is, how to handle bidirectional relationships in jhipster?
This is how I would like to update my basket:
test-component.ts
intoBasket(product, amount) {
this.productOrder = new ProductOrder();
this.productOrder.product = product;
this.productOrder.amount = amount;
this.basketService.find(+this.account.id).subscribe((res: HttpResponse<Basket>) => {
this.basket = res.body;
this.productOrder.basket = this.basket;
this.basket.products.push(this.productOrder);
this.basketService.update(this.basket).subscribe((res: HttpResponse<Basket>) => {
console.log("test");
});
});
}
thank you!
Update
I moved some logic from the frontend to the backend:
BasketService.java
public Basket save(Basket basket) {
log.debug("Request to save Basket : {}", basket);
log.info(basket.getProducts().toString());
basket.getProducts().stream().forEach(p -> p.setBasket(basket));
return basketRepository.save(basket);
}
this saves the ProductOrders properly with a reference to the Basket. But When I try to log the products from the basket in the frontend I get null which is odd because the method
this.basketService.update(this.basket).subscribe((res: HttpResponse<Basket>) => {
console.log(res.body.products);
});
actually returns the basket filled with the new product. But it doesn't seem to save it because when I request that specific basket "/baskets/39" the response is missing the products:
{id: 39, totalPrice: 0, customerId: 39, products: null}
Update 2
okay, i restarted the product microservice which is responsible for these entities and now everything works fine. I didn't know I had to restart it but that's good to know I guess.
I am using SOAP V1 api
$parameters = array('orderIncrementId' => $postdata['order_id'], $items);
$createInvoice = $proxy->call($sessionId,'sales_order_invoice.create', $parameters);
Can someone please help me, how to trigger invoice event(sales_order_invoice_pay) when invoice from api.
Create custom event after create invoice from API.
$baseUrl = 'http://example.com/index.php/';
$proxy = new SoapClient($baseUrl.'api/soap/?wsdl');
$createInvoice = $proxy->call($sessionId,'sales_order_invoice.create', $parameters);
$orderinvoice = Mage::getModel('sales/order_invoice')->loadByIncrementId($createInvoice);
Mage::dispatchEvent('sales_order_invoice_pay_api', array('invoice'=>$orderinvoice));
Add event trigger in module config.xml file
<config>
<global>
..........
..........
<events>
<sales_order_invoice_pay_api>
<observers>
<namespace_modulename_model_observer>
<type>singleton</type>
<class>Namespace_Modulename_Model_Observer</class>
<method>setinvoicestatetaxapi</method>
</namespace_modulename_model_observer>
</observers>
</sales_order_invoice_pay_api>
</events>
..........
..........
<global>
<config>
Create / modify Observer.php
<?php
class Namespace_Modulename_Model_Observer extends Varien_Object
{
...............
...............
public function setinvoicestatetaxapi(Varien_Event_Observer $observer)
{
$invoice = $observer->getEvent()->getInvoice();
}
...............
...............
}
have an issue updating magento product from frontend using a module that its function is for customers to create their own products and have the admin approve before enabled(this part is working).
the problem is when a customer tries to updated their admin approved product (as before approval, product states that newly created product is pending, but they can still update the data/attributes created during the product create function, the same attributes that are not updating using the controller)
first of all i have a controller with the action to update the approved/pending customer product
public function editPostAction() {
$id = $this->getRequest()->getParam('productid');
if ( $id !== false ) {
list($data, $errors) = $this->validatePost();
if ( !empty($errors) ) {
foreach ($errors as $message) {
$this->_getSession()->addError($message);
}
$this->_redirect('customer/products/edit/', array(
'id' => $id
));
} else {
$customerId = $this->_getSession()->getCustomer()->getid();
$product = Mage::getResourceModel('customerpartner/customerpartner_product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('customer_id', $customerId)
->addAttributeToFilter('entity_id', $id)
->load()
->getFirstItem();
$product->setName($this->getRequest()->getParam('name'));
$product->setSku($this->getRequest()->getParam('sku'));
$product->setDescription($this->getRequest()->getParam('description'));
$product->setShortDescription($this->getRequest()->getParam('short_description'));
$product->setPrice($this->getRequest()->getParam('price'));
$product->setWeight($this->getRequest()->getParam('weight'));
$product->setStock($this->getRequest()->getParam('stock'));
$product->save();
if ( isset($_FILES) && count($_FILES) > 0 ) {
foreach($_FILES as $image ) {
if ( $image['tmp_name'] != '' ) {
if ( ( $error = $this->uploadImage($image, $id) ) !== true ) {
$errors[] = $error;
}
}
}
}
if ( empty($errors) ) {
$this->_getSession()->addSuccess($this->__('Your product was successfully updated'));
} else {
$this->_getSession()->addError('Product info was saved but was imposible to save the image');
foreach ($errors as $message) {
$this->_getSession()->addError($message);
}
}
$this->_redirect('customer/products/');
}
}
}
as well as a form that on submit is supposed to update the product attributes and images but the page reloads on submit and shows successful saved message but the attributes are not updated and going back to the edit form (for each product created) for that product the values in the update form have the values of the update we just submitted, bet yet the products attributes are not updated in the catalog either (they remain the same values as entered in the create new process)
don't no if to continue to figure out what is going wrong or just move to either use api or direct sql to get the job done.
see this post Magento 1.7: Non-system product attribute not saving in PHP script the problem maybe different but the solution can be found in that post
updated to a new action to call in .phtml see below as it seems to be updating the product data as needed, still wanting to improve..
called in form using /frontendname/editApprovedPost/
public function editApprovedPostAction() {
$id = $this->getRequest()->getParam('productid');
$idproduct = $this->getRequest()->getParam('product_id');
if ( $id !== false ) {
list($data, $errors) = $this->validatePost();
if ( !empty($errors) ) {
foreach ($errors as $message) {
$this->_getSession()->addError($message);
}
$this->_redirect('customer/products/edit/', array(
'id' => $id
));
} else {
- now added more php code to action (in this order) after the } else {...
require_once 'app/Mage.php';
then add admin store for frontend product updates...
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
then get the customer id...
$customerId = Mage::getSingleton('customer/session')->getCustomerId();
then use the forms product Id to get the Product Id to update...
$product = Mage::getModel('catalog/product')->load("".$idproduct."");
then use setName() to update/save the attribute value grabbed from the forms input value...
$product->setName($this->getRequest()->getParam('name'));//use whatever attributes need (only text and text area tested so far)
then save/update product data with...
$product->save();
then add to run through errors...
if ( empty($errors) ) {
$this->_getSession()->addSuccess($this->__('Your product was successfully updated'));
} else {
$this->_getSession()->addError('Product info was saved but was imposible to save the image');
foreach ($errors as $message) {
$this->_getSession()->addError($message);
}
}
$this->_redirect('customer/products/');
}
}
}
then with a form to submit in frontend with customer logged in and customer group config
custom form only visible to Customer Group 2 (default is Wholesale)
form below....
sorry cant paste form to much work to paste the code here, any way using the
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
which i have read in some posts is that to update product in frontend you need to be "admin", which this seems to do just fine. As Noted before, the script was not updating and it was because it is trying to save to a different models data when the data to be updated was an actual product (that has been approved and created using the different models data) and it was updating using
$product = Mage::getResourceModel('customerpartner/customerpartner_product_collection')
would be good to here anyone else's comments
hope this helps someone because was think time to close this build.