Method setFrom is deprecated in Magento 2.4.5 - magento2

Method setFrom is deprecated
Is Magento 2.4.5 any alternative?

With new implementation, magento 2.4.5 is recommended setFromByScope as an alternative.
Change:
->setFrom($this->contactsConfig->emailSender())
To
->setFromByScope($this->contactsConfig->emailSender())
<?php
declare(strict_types=1);
namespace Module\Test\Model;
use Magento\Framework\Mail\Template\TransportBuilder;
/**
* #var TransportBuilder
*/
private $transportBuilder;
class Main implements MailInterface
{
/**
* Initialize dependencies.
* #param TransportBuilder $transportBuilder
*/
public function __construct(
TransportBuilder $transportBuilder
) {
$this->transportBuilder = $transportBuilder;
}
public function send($replyTo, array $variables)
{
...
try {
$transportBuilder = $this->transportBuilder
...
->setFromByScope($this->contactsConfig->emailSender())
...
$transportBuilder->sendMessage();
} finally {
...
}
}
}

Related

In magento 2, how to store observer value in session

Example:
I have 2 observer classes.
1- category.php
2- product.php
I want to store the category.php data in a session variable, like $_SESSION['category']= $data; and call that session in product.php class.
Like this:
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Checkout\Model\Session as CheckoutSession;
class MyOberver implements ObserverInterface
{
protected $checkoutSession;
public function __construct(
CheckoutSession $checkoutSession
) {
$this->_checkoutSession = $checkoutSession;
}
/**
* #param EventObserver $observer
* #return $this
*/
public function execute(EventObserver $observer)
{
$setValue = $this->_checkoutSession->setVar('dit is een sessie test hoppa');
$getValue = $this->_checkoutSession->getVar();
return $this;
}
}

Zend Framework 2 call TableGateway in Service

I'm new to ZF2. After few days of trying to figure out how all this stuff should work I was unable to figure out how should I call TableGateway Model from Service.
So I have Controller:
class SubscriberController extends AbstractActionController
{
/**
* #var \Subscriber\Service\SubscriberServiceInterface
*/
private $subscriberService;
/**
* #param $subscriberService
*/
public function __construct(SubscriberServiceInterface $subscriberService)
{
$this->subscriberService = $subscriberService;
}
Factroy for this Controller:
class SubscriberControllerFactory implements FactoryInterface
{
/**
* Returns ArchiveController instance.
*
* #param ServiceLocatorInterface $serviceLocator
* #return SubscriberController
* #override
**/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$sm = $serviceLocator->getServiceLocator();
return new SubscriberController(
$sm->get('Subscriber\Service\SubscriberServiceInterface')
);
}
Some SubscriberTable:
class SubscriberTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
And Service in which I want to get SubscriberTable instance and make some logic. But I can't figure out how should I call this instance in SubscriberService and set the DbAdapter for SubscriberTable
First implement servicelocator interface and define get and set locator functions to your service like this.
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class Yourservice implements ServiceLocatorAwareInterface{
function test(){
$this->getSubscriberTable->fetchAll(); // call to subscriber table functions
}
/**
* #table gateway Call
**/
public function getSubscriberTable()
{
if (!$this->SubscriberTable) {
$sm = $this->getServiceLocator();
$this->SubscriberTable = $sm->get('Application\Model\SubscriberTable');
}
return $this->SubscriberTable;
}
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
}
Hope it will help you.

How get basepath from model or helper en Zend Framework 3

I recently decided to use Zend Framework 3 after 3 years of using Zend Framework 1. This decision has given me headaches, Zend 3 instead of making things easier made things more difficult.
In Zend 1, I customize the url for the selected template in the database as follows:
public function getUrl(string $file = '')
{
if($this->_helperBaseUrl === null) {
$this->_helperBaseUrl = new Zend_View_Helper_BaseUrl();
}
return $this->_helperBaseUrl->baseUrl($file);
}
public function getSkinUrl(string $file = '')
{
$themePath = 'themes/my-theme/'; //get from database
return $this->getUrl($themePath . ltrim($file, '/\\'));
}
Then in any part of the application (models, helpers, plugins and views) I can access this function like this:
//view/scripts/index/index.phtml
$url_logo = My::app()->getSkinUrl('logo.jpg');
//this return http://example.com/themes/my-theme/logo.jpg
In Zend 3 it has been very difficult for me. Does anyone know of any way to do it in Zend 3? Or How to get the baseUrl from a model in Zend 3?
In Zend Framework 2/3 you can inject almost any class into another. For example if you need basePath plugin (which is available in view context) you can inject this plugin into your model/service or controller class. This is the recommended way:
This is class where you need this plugin or any other service
use Zend\View\Helper\BasePath;
class MyService
{
/**
* #var BasePath
*/
protected $plugin;
/**
* MyService constructor.
*
* #param BasePath $basePath
*/
public function __construct(BasePath $basePath)
{
$this->plugin = $basePath;
}
/**
* #return BasePath
*/
public function getPlugin()
{
return $this->plugin;
}
/**
* #param BasePath $plugin
*/
public function setPlugin($plugin)
{
$this->plugin = $plugin;
}
}
Now, you need to factory to inject one dependency into another
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use MyNamespace\Service\MyService;
class MyServiceFactory implements FactoryInterface
{
/**
*
* #param ContainerInterface $container
* #param string $requestedName
* #param null|array $options
* #return MyService
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$class = $requestedName ? $requestedName : MyService::class;
$plugin = $container->get('ViewHelperManager')->get('BasePath'); // inject this class
$myService = new $class($plugin); // into this class
return $myService;
}
/**
* Provided for backwards compatibility; proxies to __invoke().
*
* #param ContainerInterface|ServiceLocatorInterface $container
* #return MyService
*/
public function createService(ServiceLocatorInterface $container)
{
return $this($container, MyService::class);
}
}
Ok, now MyService has basePath plugin, but to use it in controller you have to inject your service into controller. So...
IndexController
use MyNamespace\Service\MyService;
use Zend\Mvc\Controller\AbstractActionController;
class IndexController extends AbstractActionController
{
/**
* #var MyService
*/
protected $service;
/**
* IndexController constructor.
*
* #param MyService $service
*/
public function __construct(MyService $service)
{
$this->service = $service;
}
public function indexAction()
{
$plugin = $this->service->getPlugin(); // Zend\View\Helper\BasePath object
//...
}
}
... and factory for our controller...
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use MyNamespace\Controller\IndexController;
class IndexControllerFactory implements FactoryInterface
{
/**
*
* #param ContainerInterface $container
* #param string $requestedName
* #param null|array $options
* #return IndexController
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$class = $requestedName ? $requestedName : IndexController::class;
$myService = $container->getServiceLocator()->get('MyNamespace\Service\MyService');
$controller = new $class($myService);
return $controller;
}
/**
* Provided for backwards compatibility; proxies to __invoke().
*
* #param ContainerInterface|ServiceLocatorInterface $container
* #return IndexController
*/
public function createService(ServiceLocatorInterface $container)
{
return $this($container, IndexController::class);
}
}
It's almost done. Last step is to set configuration in module.config.php file
use MyNamespace\Controller;
use MyNamespace\Factory;
return [
//...
'service_manager' => [
'factories' => [
Service\MyService::class => Factory\Service\MyServiceFactory::class
]
],
'controllers' => [
'factories' => [
Controller\IndexController::class => Factory\Controller\IndexControllerFactory::class
],
],
]
Easy, isn't it?
If you need plugin in controller, but not in your model/service class, you can skip MyService part of this "tutorial" and inject plugin directly into controller class

TYPO3 Extbase - Failing to render json via typnum

TYPO3 Extbase - Failing to render json via typnum
Next to list/edit/new/remove action (which work) I tried to render the output in json. But no values render. If I do a simple ...
$data = array('value'=>'001');
return json_encode($data);
It does return ...
{"value":"001"}
What am I missing?
Edit: With using and referencing to the same repository its working:
JSONController.php
<?php
namespace Vendor\Lei\Controller;
use Vendor\Lei\Domain\Model\Lei;
/**
* JSONController
*/
class JSONController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController {
/**
* leiRepository
*
* #var \Vendor\Lei\Domain\Repository\LeiRepository
* #inject
*/
protected $leiRepository;
/**
* #var string
*/
protected $defaultViewObjectName = 'TYPO3\CMS\Extbase\Mvc\View\JsonView';
/**
* action jsonRequest
*
* #return void
*/
public function jsonRequestAction() {
//$data = array('value'=>'001');
//return json_encode($data);
$this->view->setVariablesToRender(array('records'));
$this->view->assign('records', $this->leiRepository->jsonRequest());
}
}
LeiRepository.php
<?php
namespace Vendor\Lei\Domain\Repository;
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
class LeiRepository extends \TYPO3\CMS\Extbase\Persistence\Repository {
...
public function jsonRequest() {
$query = $this->createQuery();
$result = $query->setLimit(100)->execute();
return $result;
}
}
If you inject and use a JsonRepository extbase expexts a domain object called Json. If you just want to render already existing domain objects as their JSON representation, just use the same repositories you used in your listAction() and detailAction().
Have a look at my example: https://usetypo3.com/json-view.html
Also, a debug after the return like you did in your repository will never be executed.

Symfony 3.0.4 Circular reference detected during serialization with FOSRestBundle

I'm using FOSRestBundle in a Symfony project. When it I try to handle a view, it fails during the serialization of my data with the Symfony serializer as well as with the JMSSerializer.
This is the method rendering the response:
DefaultController.php
$em = $this->getDoctrine()->getManager('magellan');
$qb = $em->createQueryBuilder();
$query = $qb->select('h')
->from('DataBundle:Holding', 'h')
->where($qb->expr()->eq('h.id', ':holding_id'))
->setParameter('holding_id', $holding_id)
->getQuery();
$results = $query->getResult();
$view = $this->view($results, 200);
// Everything's ok up to this point
return $this->handleview($view);
And these are my entities:
Holding.php
class Holding
{
...
/**
* #ORM\OneToMany(targetEntity="Subsidiary", mappedBy="holding")
*/
private $subsidiaries;
}
Subsidiary.php
class Subsidiary
{
...
/**
* #ORM\ManyToOne(targetEntity="Holding", inversedBy="subsidiaries")
* #ORM\JoinColumn(name="id_holding", referencedColumnName="id_holding")
*/
private $holding;
/**
* #ORM\OneToMany(targetEntity="Brand", mappedBy="subsidiary")
*/
private $brands;
}
Brand.php
class Brand
{
...
/**
* #ORM\ManyToOne(targetEntity="Subsidiary", inversedBy="brands")
* #ORM\JoinColumn(name="id_subsidiary", referencedColumnName="id_subsidiary")
*/
private $subsidiary;
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="brand")
*/
private $products;
}
Product.php
class Product
{
...
/**
* #ORM\ManyToOne(targetEntity="Brand", inversedBy="products")
* #ORM\JoinColumn(name="id_brand", referencedColumnName="id_brand")
*/
private $brand;
/**
* #ORM\ManyToOne(targetEntity="Sector", inversedBy="products")
* #ORM\JoinColumn(name="id_sector", referencedColumnName="id_sector")
*/
private $sector;
/**
* #ORM\OneToMany(targetEntity="Commercial", mappedBy="product")
*/
private $commercials;
}
Commercial.php
class Commercial
{
...
/**
* #ORM\ManyToOne(targetEntity="Product", inversedBy="commercials")
* #ORM\JoinColumn(name="id_product", referencedColumnName="id_product")
*/
private $product;
/**
* #ORM\OneToMany(targetEntity="CommercialReport", mappedBy="commercial")
*/
private $reports;
CommercialReport.php
class CommercialReport
{
...
/**
* #ORM\ManyToOne(targetEntity="Commercial", inversedBy="reports")
* #ORM\JoinColumn(name="id_commercial", referencedColumnName="id_commercial")
*/
private $commercial;
}
Sector.php
class Sector
{
...
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="sector")
*/
private $products;
}
When using the default symfony serializer, I get the following error:
"message":"A circular reference has been detected (configured limit:
1).","class":"Symfony\Component\Serializer\Exception\CircularReferenceException"
And when using the JMSSerializer, when I go to the corresponding page of the controller, the page just never finishes loading. At the same time in the dev.log file new Doctrine.debug entries with requests to my DB are added every second.
$normalizers->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
Just add it after you make the instance if your objectNormalizer()
it worl perfectly for me
If you use FosRestBundle, you can use the GROUPS for the serializer. There is an annotation given by FosRestBundle : #FOS\RestBundle\Controller\Annotations\View(serializerGroups={"user"})
Your group can exclude the circular property.
Another idea you can do this. In your app/config/services.yml
circular_reference_handler:
public: false
class: callback
factory: [AppBundle\Serializer\CircularHandlerFactory, getId]
serializer.normalizer.object:
class: Symfony\Component\Serializer\Normalizer\ObjectNormalizer
arguments: ["#serializer.mapping.class_metadata_factory", null, "#serializer.property_accessor"]
public: false
tags: [serializer.normalizer]
calls:
- method: setCircularReferenceLimit
arguments: [1]
- method: setCircularReferenceHandler
arguments: ["#circular_reference_handler"]
The factory can be like this:
namespace AppBundle\Serializer;
class CircularHandlerFactory
{
/**
* #return \Closure
*/
public static function getId()
{
return function ($object) {
return $object->getId();
};
}
}