I have created a method to query to database for all joining table in repository. I also have read the documentation from How to create custom repository. The method is working properly, but in PhpStorm there is a yellow warning
Method 'findAllDetail' not found.
How do I fix this warning?
Below is my entity:
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="App\Repository\InvoiceRepository")
*/
class Invoice
{
and here is the InvoiceRepository:
namespace App\Repository;
use App\Entity\Invoice;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* #method Invoice|null find($id, $lockMode = null, $lockVersion = null)
* #method Invoice|null findOneBy(array $criteria, array $orderBy = null)
* #method Invoice[] findAll()
* #method Invoice[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class InvoiceRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Invoice::class);
}
/**
* #param $value
* #return Invoice[] Returns an array of Invoice objects
*/
public function findAllDetail($value)
{
$qb = $this->createQueryBuilder('i')
/* .... */
;
return $qb->execute();
}
and here is the controller:
/**
* #Route("/invoice/review/{idInvoice}", name="submitToReview", requirements={"idInvoice"="\d+"})
* #param $idInvoice
* #return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function submitToReview($idInvoice, \Swift_Mailer $mailer)
{
$invoice = $this->getDoctrine()->getRepository(Invoice::class)->findAllDetail($idInvoice);
/* #var $item \App\Entity\Invoice */
For those people who get the same warning, below is how i fix it (based on M. Kebza Comment)
put your repository in controller and pass repository as parameter in the controller
in controller
...
use App\Repository\InvoiceRepository;
/**
* #Route("/invoice/review/{idInvoice}", name="submitToReview", requirements={"idInvoice"="\d+"})
* #param $idInvoice
* #return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function submitToReview($idInvoice, \Swift_Mailer $mailer, InvoiceRepository $repository )
{
$invoice = $repository->findAllDetail($idInvoice);
/* #var $item \App\Entity\Invoice */
Basically when you do
$this->getDoctrine()->getRepository()
It returns a Doctrine EntityRepository. So that's normal if phpstorm is complaining about your findAllDetails method because EntityRepository does not know it.
From the documentation:
By default the EntityManager returns a default implementation of Doctrine\ORM\EntityRepository when you call EntityManager#getRepository($entityClass).
So even if you override this behavior as suggested in the doc, I suppose that phpstorm keeps reference to the default.
Repository class make public in services.yaml file and call in controller
$invoiceRepository = $this->get(InvoiceRepository::class);
or
/** #var InvoiceRepository $invoiceRepository **/
$invoiceRepository = $this->getDoctrine()->getRepository(Invoice::class);
$invoice = $invoiceRepository->findAllDetail($idInvoice);
I would construct the controller with the repository (and the mailer) rather than put it into the action - the autowiring will sort the injection, there's no uri parameter confusion, and it's good to be explicit - your future self will thank you:
# Controller.php
/**
* #var InvoiceRepository
*/
private $invoiceRepo;
/**
* #var \Swift_Mailer
*/
private $mailer;
/**
* #param InvoiceRepository $invoiceRepo
* #param \Swift_Mailer $mailer
*/
public function __construct(InvoiceRepository $invoiceRepo, \Swift_Mailer $mailer)
{
$this->invoiceRepo = $invoiceRepo;
$this->mailer = $mailer;
}
/**
* #Route("/invoice/review/{idInvoice}", name="submitToReview", requirements={"idInvoice"="\d+"})
* #param $idInvoice
* #return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function submitToReview($idInvoice)
{
$invoice = $this->invoiceRepo->findAllDetail($idInvoice);
...
}
Related
im learning symfony. I have a twig using twig extension and i found that i cannot call a function from other controller inside twig extension.
so i have decide to use a service since the twig extension is using the service.
so i tried to call a function from controller in the service and call the function from the service in the twig extension.
Then, i have an error message that [Call to a member function has() on null], where $doct = $this->getDoctrine()->getManager(); in the controller.
this is the function in the controller that i'm trying to use
edited
namespace Customize\Controller;
use Customize\Entity\CustomRing;
use Customize\Entity\Ring;
use Customize\Repository\CustomProductRepository;
use Eccube\Controller\AbstractController;
use Eccube\Entity\BaseInfo;
use Eccube\Entity\Product;
use Eccube\Entity\ProductClass;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Eccube\Repository\BaseInfoRepository;
use Eccube\Repository\ProductClassRepository;
use Eccube\Service\CartService;
use Eccube\Service\OrderHelper;
use Eccube\Service\PurchaseFlow\PurchaseContext;
use Eccube\Service\PurchaseFlow\PurchaseFlow;
use Eccube\Service\PurchaseFlow\PurchaseFlowResult;
use Google\Service\Monitoring\Custom;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class CartController extends AbstractController
{
/**
* #var ProductClassRepository
*/
protected $productClassRepository;
/**
* #var CartService
*/
protected $cartService;
/**
* #var PurchaseFlow
*/
protected $purchaseFlow;
/**
* #var BaseInfo
*/
protected $baseInfo;
/**
* #var CustomProductRepository
*/
protected $customProductRepository;
/**
* CartController constructor.
*
* #param ProductClassRepository $productClassRepository
* #param CartService $cartService
* #param PurchaseFlow $cartPurchaseFlow
* #param BaseInfoRepository $baseInfoRepository
* #param CustomProductRepository $customProductRepository
*/
public function __construct(
ProductClassRepository $productClassRepository,
CartService $cartService,
PurchaseFlow $cartPurchaseFlow,
BaseInfoRepository $baseInfoRepository,
CustomProductRepository $customProductRepository
) {
$this->productClassRepository = $productClassRepository;
$this->cartService = $cartService;
$this->purchaseFlow = $cartPurchaseFlow;
$this->baseInfo = $baseInfoRepository->get();
$this->customProductRepository = $customProductRepository;
}
public function image_route(){
$Carts = $this->cartService->getCarts();
$doct = $this->getDoctrine()->getManager();
$custom_images = array();
$Custom_product = $this->customProductRepository->customProductFindByName();
$Product = $doct->getRepository(Product::class)->find($Custom_product[0]->getId());
foreach ($Carts as $Cart) {
$items = $Cart->getCartItems();
foreach($items as $item ){
if($item->getProductClass()->getProduct()->getId() == $Product->getId()){
$custom = $item->getProductClass()->getCode();
$custom = $doct->getRepository(CustomRing::class)->find($custom);
$ring = $doct->getRepository(Ring::class)->find($custom->getRingBaseId());
$upload_directory= $this->getParameter('uploads_directory');
$ring_shape = $ring->getRingShape();
$ring_type = $ring->getRingType();
$upload = $upload_directory.'/customRing/ring/'.$ring_shape.'/'.$ring_type.'/';
$images = glob($upload."*.{jpg,png,jpeg,JPG,JPEG,PNG}", GLOB_BRACE);
for($i=0;$i<count($images);$i++){
$aa = explode('save_image/', $images[$i]);
$images[$i] = $aa[1];
}
array_push($custom_images,$images[0]);
}
}
}
return $custom_images;
use Customize\Controller\CartController;
/**
* #var CartController
*/
protected $cartController;
public function __construct(
SessionInterface $session,
EntityManagerInterface $entityManager,
ProductClassRepository $productClassRepository,
CartRepository $cartRepository,
CartItemComparator $cartItemComparator,
CartItemAllocator $cartItemAllocator,
OrderRepository $orderRepository,
TokenStorageInterface $tokenStorage,
AuthorizationCheckerInterface $authorizationChecker,
CartController $CartController
) {
$this->session = $session;
$this->entityManager = $entityManager;
$this->productClassRepository = $productClassRepository;
$this->cartRepository = $cartRepository;
$this->cartItemComparator = $cartItemComparator;
$this->cartItemAllocator = $cartItemAllocator;
$this->orderRepository = $orderRepository;
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $authorizationChecker;
$this->cartController = $CartController;
}
/*other functions
.
.
*/
public function imagess(){
$temp = $this->cartController->image_route();
return $temp;
}
and this is the twig extension
use Eccube\Service\CartService;
class CartServiceExtension extends AbstractExtension
{
/**
* #var CartService
*/
protected $cartService;
public function get_image_route(){
$t = $this->cartService->imagess();
return $t;
//return ['11', '12'];
}
}
The line i got error in controller is
$doct = $this->getDoctrine()->getManager();
and when go inside getDoctrine()
trait ControllerTrait{
/**
* Shortcut to return the Doctrine Registry service.
*
* #return ManagerRegistry
*
* #throws \LogicException If DoctrineBundle is not available
*
* #final
*/
protected function getDoctrine()
{
if (!$this->container->has('doctrine')) {
throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
}
return $this->container->get('doctrine');
}
I don't know why but it seems has() function inside getDoctrine() returns null
how can i use the function from the controller so that i can pass the values of $custom_images into the twig?
To get Doctrine in any controller action, you can do away with that function/trait entirely and just inject the EntityManagerInterface into your action.
For example:
class SomeCustomController extends AbstractController
{
public function someControllerAction(Request $request, EntityManagerInterface $em): Response
{
// business logic
}
}
Technical stack :
php 7.4.28
symfony 5.4.5
doctrine/orm 2.11
I have a simple entity which consist of only two fields :
<?php
namespace App\Entity\Pro;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\Pro\MarketRepository")
* #ORM\Table()
*/
class Market
{
/**
* #ORM\Id()
* #ORM\Column(name="listing_date", type="custom_datetime", options={"default": "0000-00-00"})
*/
private $listingDate;
/**
* #ORM\Column(type="text")
*/
private $payload;
/**
* #return \DateTime
*/
public function getListingDate(): \DateTime
{
return new \DateTime($this->listingDate);
}
/**
* #param \DateTime $listingDate
* #return self
*/
public function setListingDate(\DateTime $listingDate): self
{
$this->listingDate = $listingDate->format('Y-m-d');
return $this;
}
/**
* #return string
*/
public function getPayload(): string
{
return $this->payload;
}
/**
* #param string $payload
* #return self
*/
public function setPayload(string $payload): self
{
$this->payload = $payload;
return $this;
}
}
The payload field contain a huge JSON field (I think it's where the problem is), I can't really do anything about it because we're getting it from an external service.
I need to loop through those records and do some actions with the payload, so I made a simple repository with an Iterator :
<?php
namespace App\Repository\Pro;
use App\Entity\Pro\Instrument;
use App\Entity\Pro\Market;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Query;
use Doctrine\Persistence\ManagerRegistry;
/**
* #method Market|null find($id, $lockMode = null, $lockVersion = null)
* #method Market|null findOneBy(array $criteria, array $orderBy = null)
* #method Market[] findAll()
* #method Market[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class MarketRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Market::class);
}
public function findForGraph($types): array
{
$qb = $this->createQueryBuilder('m')
->orderBy('m.listingDate', 'ASC');
$iterator = $qb->getQuery()->toIterable();
echo 'Memory usage before looping: '.round((memory_get_usage() / 1024 / 1024), 2)." mb\n";
foreach ($iterator as $result) {
// doing stuff here
$this->_em->detach($result[0]);
}
return $graphsConfigs;
}
}
The memory usage echo actually shows a memory usage of 800 mb.
It stays constant during the loop, but how is it possible than simply the call of the toIterable method is using this much ? Is there any solution possible without going pure PDO / DBAL mode ?
I'm currently experiencing issues when trying to filter my results when using an external API source (Stripe) in API-Platform.
What I need to be able to do, is return a list of subscriptions for a specified customer. So going to http://localhost/api/subscriptions?customer=123foo would return all records matched to this customer.
Now, the code below is throwing an error because of the ORM\Filter and would be functional without it, as the actual filtering is performed on Stripes API, not by me, BUT, I really want the Swagger-API GUI to have the filter box.
In short, how do I get the Annotations in my Entity to display, searchable fields within the Swagger UI when using an external data source.
What I have is an Entity as below (simplified for example purposes):
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Annotation\ApiProperty;
use Symfony\Component\Serializer\Annotation\Groups;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
use ApiPlatform\Core\Annotation\ApiFilter;
/**
* Subscriptions allow you to charge a customer on a recurring basis. A subscription ties a customer to a particular plan you've created.
* #ApiResource()
* #ApiFilter(SearchFilter::class, properties={"customer": "exact"})
* #package App\Entity
*/
class Subscription
{
/**
* Unique identifier for the object.
* #ApiProperty(identifier=true)
* #var string | null
*/
protected $id;
/**
* ID of the customer who owns the subscription.
* #var string | null
*/
protected $customer;
// Plus a bunch more properties and their Getters & Setters
}
And the SubscriptionCollectionDataProvider:
<?php
namespace App\DataProvider;
use App\Entity\Subscription;
use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use App\Controller\BaseController;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Class SubscriptionCollectionDataProvider
* #package App\DataProvider
* #author dhayward
*/
final class SubscriptionCollectionDataProvider extends BaseController implements CollectionDataProviderInterface, RestrictedDataProviderInterface
{
protected $requestStack;
/**
* SubscriptionCollectionDataProvider constructor.
* #param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
$this->request = $requestStack->getCurrentRequest();
}
/**
* #param string $resourceClass
* #param string|null $operationName
* #param array $context
* #return bool
*/
public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
{
return Subscription::class === $resourceClass;
}
/**
* #param string $resourceClass
* #param string|null $operationName
* #return \Generator
* #throws \Stripe\Error\Api
*/
public function getCollection(string $resourceClass, string $operationName = null): \Generator
{
$customer = $this->request->get("customer");
$data = \Stripe\Subscription::all(["customer" => $customer]);
foreach($data['data'] as $subscriptionObject){
$this->serializer()->deserialize(json_encode($subscriptionObject), Subscription::class, 'json', array('object_to_populate' => $subscription = new Subscription()));
yield $subscription;
}
}
}
Error result, which is presumably because I'm using an ORM/Filter without any ORM setup:
Call to a member function getClassMetadata() on null
Any pointers would be greatly appreciated.
So I finally managed to work it out. It was as simple as creating my own version of the SearchFilter, implementing ApiPlatform\Core\Api\FilterInterface.
<?php
namespace App\Filter;
use ApiPlatform\Core\Api\FilterInterface;
/**
* Class SearchFilter
* #package App\Filter
*/
class SearchFilter implements FilterInterface
{
/**
* #var string Exact matching
*/
const STRATEGY_EXACT = 'exact';
/**
* #var string The value must be contained in the field
*/
const STRATEGY_PARTIAL = 'partial';
/**
* #var string Finds fields that are starting with the value
*/
const STRATEGY_START = 'start';
/**
* #var string Finds fields that are ending with the value
*/
const STRATEGY_END = 'end';
/**
* #var string Finds fields that are starting with the word
*/
const STRATEGY_WORD_START = 'word_start';
protected $properties;
/**
* SearchFilter constructor.
* #param array|null $properties
*/
public function __construct(array $properties = null)
{
$this->properties = $properties;
}
/**
* {#inheritdoc}
*/
public function getDescription(string $resourceClass): array
{
$description = [];
$properties = $this->properties;
foreach ($properties as $property => $strategy) {
$filterParameterNames = [
$property,
$property.'[]',
];
foreach ($filterParameterNames as $filterParameterName) {
$description[$filterParameterName] = [
'property' => $property,
'type' => 'string',
'required' => false,
'strategy' => self::STRATEGY_EXACT,
'is_collection' => '[]' === substr($filterParameterName, -2),
];
}
}
return $description;
}
}
I am trying to insert data into db ,but it shows some error like this
My model Entity
Request.php
is here `<?php
namespace EvolisClientRequest\Model\Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class Request
{
/**
* #var \Ramsey\Uuid\Uuid
* #ORM\Id
* #ORM\Column(type="uuid")
* #ORM\GeneratedValue(strategy="CUSTOM")
* #ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="Salesperson", inversedBy="request")
* #ORM\JoinTable(name="request_salesperson")
* #var Salesperson
*/
private $salesperson;
/**
* #ORM\ManyToOne(targetEntity="Client", inversedBy="request")
* #var Client
*/
private $client;
/**
* #ORM\ManyToMany(targetEntity="Status", inversedBy="request")
* #ORM\JoinTable(name="request_status")
* #var Status
*/
private $status;
/**
* #ORM\Column(type="integer")
* #var Qualification
*/
private $qualification;
/**
* #return \Ramsey\Uuid\Uuid
*/
public function getId()
{
return $this->id;
}
/**
* #return Salesperson
*/
public function getSalesperson()
{
return $this->salesperson;
}
/**
* #param Salesperson $salesperson
*/
public function setSalesperson($salesperson)
{
$this->salesperson = $salesperson;
}
/**
* #return Client
*/
public function getClient()
{
return $this->client;
}
/**
* #param Client $client
*/
public function setClient($client)
{
$this->client = $client;
}
/**
* #return Status
*/
public function getStatus()
{
return $this->status;
}
/**
* #param Status $status
*/
public function setStatus($status)
{
$this->status = $status;
}
/**
* #return Qualification
*/
public function getQualification()
{
return $this->qualification;
}
/**
* #param Qualification $qualification
*/
public function setQualification($qualification)
{
$this->qualification = $qualification;
}
public function __construct($salesperson, $client, $status, $qualification) {
$this->salesperson = $salesperson;
$this->client = $client;
$this->status = $status;
$this->qualification = $qualification;
}
}`
Also my
DAO "RequestBaseDao.php" is here,which is automatically generated.
<?php
/*
* This file has been automatically generated by Mouf/ORM.
* DO NOT edit this file, as it might be overwritten.
* If you need to perform changes, edit the RequestDao class instead!
*/
namespace EvolisClientRequest\Model\DAOs;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NonUniqueResultException;
use Mouf\Doctrine\ORM\Event\SaveListenerInterface;
use EvolisClientRequest\Model\Entities\Request;
/**
* The RequestBaseDao class will maintain the persistence of Request class into the request table.
*
* #method Request findByQualification($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneByQualification($fieldValue, $orderBy = null)
* #method Request findBySurfaceMin($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneBySurfaceMin($fieldValue, $orderBy = null)
* #method Request findBySurfaceMax($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneBySurfaceMax($fieldValue, $orderBy = null)
* #method Request findByPriceMin($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneByPriceMin($fieldValue, $orderBy = null)
* #method Request findByPriceMax($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneByPriceMax($fieldValue, $orderBy = null)
* #method Request findByRequestDate($fieldValue, $orderBy = null, $limit = null, $offset = null)
* #method Request findOneByRequestDate($fieldValue, $orderBy = null)
*/
class RequestBaseDao extends EntityRepository
{
/**
* #var SaveListenerInterface[]
*/
private $saveListenerCollection;
/**
* #param EntityManagerInterface $entityManager
* #param SaveListenerInterface[] $saveListenerCollection
*/
public function __construct(EntityManagerInterface $entityManager, array $saveListenerCollection = [])
{
parent::__construct($entityManager, $entityManager->getClassMetadata('EvolisClientRequest\Model\Entities\Request'));
$this->saveListenerCollection = $saveListenerCollection;
}
/**
* Get a new persistent entity
* #param ...$params
* #return Request
*/
public function create(...$params) : Request
{
$entity = new Request(...$params);
$this->getEntityManager()->persist($entity);
return $entity;
}
/**
* Peforms a flush on the entity.
*
* #param Request
* #throws \Exception
*/
public function save(Request $entity)
{
foreach ($this->saveListenerCollection as $saveListener) {
$saveListener->preSave($entity);
}
$this->getEntityManager()->flush($entity);
foreach ($this->saveListenerCollection as $saveListener) {
$saveListener->postSave($entity);
}
}
/**
* Peforms remove on the entity.
*
* #param Request $entity
*/
public function remove(Request $entity)
{
$this->getEntityManager()->remove($entity);
}
/**
* Finds only one entity. The criteria must contain all the elements needed to find a unique entity.
* Throw an exception if more than one entity was found.
*
* #param array $criteria
*
* #return Request
*/
public function findUniqueBy(array $criteria) : Request
{
$result = $this->findBy($criteria);
if (count($result) === 1) {
return $result[0];
} elseif (count($result) > 1) {
throw new NonUniqueResultException('More than one Request was found');
} else {
return;
}
}
/**
* Finds only one entity by Qualification.
* Throw an exception if more than one entity was found.
*
* #param mixed $fieldValue the value of the filtered field
*
* #return Request
*/
public function findUniqueByQualification($fieldValue)
{
return $this->findUniqueBy(array('qualification' => $fieldValue));
}
}
My RequestDao.php where i can write queries.
<?php
namespace EvolisClientRequest\Model\DAOs;
use EvolisClientRequest\Model\Entities\Request;
/**
* The RequestDao class will maintain the persistence of Request class into the request table.
*/
class RequestDao extends RequestBaseDao {
/*** PUT YOUR SPECIFIC QUERIES HERE !! ***/
public function setdata()
{
/*$product = new Request();
$product->setStatus('Keyboard');
$product->setClient('000000001ae10dda000000003c4667a6');
$product->setSalesperson('Ergonomic and stylish!');
$product->setQualification('1111');
//var_dump($r);die();
$em = $this->getEntityManager();
$em->persist($product);
$em->flush();*/
$product= $this->create('Keyboard','000000001ae10dda000000003c4667a6','Ergonomic and stylish!','1111');
$this->save($product);
}
}
Finally my Controller "ContactController.php"
<?php
namespace EvolisClientRequest\Controllers;
use EvolisClientRequest\Model\DAOs\ClientDao;
use EvolisClientRequest\Model\Entities\Client;
use EvolisClientRequest\Model\Entities\Clients;
use EvolisClientRequest\Model\DAOs\RequestDao;
use EvolisClientRequest\Model\Entities\Request;
use EvolisClientRequest\Model\Entities\Requests;
use EvolisClientRequest\Model\DAOs\SalespersonDao;
use EvolisClientRequest\Model\Entities\Salesperson;
use EvolisClientRequest\Model\Entities\Salespersons;
use Mouf\Mvc\Splash\Annotations\Get;
use Mouf\Mvc\Splash\Annotations\Post;
use Mouf\Mvc\Splash\Annotations\Put;
use Mouf\Mvc\Splash\Annotations\Delete;
use Mouf\Mvc\Splash\Annotations\URL;
use Mouf\Html\Template\TemplateInterface;
use Mouf\Html\HtmlElement\HtmlBlock;
use Psr\Log\LoggerInterface;
use \Twig_Environment;
use Mouf\Html\Renderer\Twig\TwigTemplate;
use Mouf\Mvc\Splash\HtmlResponse;
use Doctrine\DBAL\DriverManager;
use Zend\Diactoros\Response\JsonResponse;
use Doctrine\Common\Collections\ArrayCollection;
/**
* TODO: write controller comment
*/
class ContactController {
/**
* The logger used by this controller.
* #var LoggerInterface
*/
private $logger;
/**
* The template used by this controller.
* #var TemplateInterface
*/
private $template;
/**
* The header of the page.
* #var HtmlBlock
*/
private $header;
/**
* The main content block of the page.
* #var HtmlBlock
*/
private $content;
/**
* The Twig environment (used to render Twig templates).
* #var Twig_Environment
*/
private $twig;
/**
* Controller's constructor.
* #param LoggerInterface $logger The logger
* #param TemplateInterface $template The template used by this controller
* #param HtmlBlock $content The main content block of the page
* #param Twig_Environment $twig The Twig environment (used to render Twig templates)
*/
public function __construct(LoggerInterface $logger, TemplateInterface $template, HtmlBlock $content, HtmlBlock $header, Twig_Environment $twig, ClientDao $clientDao, RequestDao $requestDao, SalespersonDao $salespersonDao) {
$this->logger = $logger;
$this->template = $template;
$this->content = $content;
$this->twig = $twig;
$this->header = $header;
$this->clientDao = $clientDao;
$this->requestDao = $requestDao;
$this->salespersonDao = $salespersonDao;
}
/**
* #URL("new.html")
*/
public function new() {
// TODO: write content of action here
// Let's add the twig file to the template.
$this->content->addHtmlElement(new TwigTemplate($this->twig, 'views/contact/new.twig', array("message"=>"world")));
$this->header->addHtmlElement(new TwigTemplate($this->twig, 'views/root/header.twig', array("message"=>"world")));
return new HtmlResponse($this->template);
}
/**
* #URL("saveData")
* For Saving the data
*/
public function saveData()
{
/*$newClient = $this->clientDao->create('hello', 'sarathchandran#122.com','8907263949');
$this->clientDao->save($newClient);*/
//$data = array();
//$data['salespersonDao']['salesperson'] = 'example#sales.com';
//$data['request']['qualification'] = 'abcdefgh';
//$newClient = $this->requestDao->create($data);
//$newClient = $this->requestDao->setQualification('Keyboard');
// $this->requestDao->save($newClient);
$user_data=$this->requestDao->setdata();
//return new JsonResponse([ "status"=>0 ]);
}
}
I am using Mouf framework.I am stuck with this problem.Someone Please help me to solve this problem.
Thanks in advance
As advised by #rokas, you should really start reading more about Doctrine. This is not a Mouf issue, this is clearly a Doctrine ORM issue so the appropriate doc is here: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/index.html
Here are a few tips:
Your controller calls the setdata method
$user_data=$this->requestDao->setdata();
The setdata method calls:
$product= $this->create('Keyboard','000000001ae10dda000000003c4667a6','Ergonomic and stylish!','1111');
Now, the create method is:
public function create(...$params) : Request
{
$entity = new Request(...$params);
$this->getEntityManager()->persist($entity);
return $entity;
}
This means that it will call the Request constructor with this parameters:
$entity = new Request('Keyboard','000000001ae10dda000000003c4667a6','Ergonomic and stylish!','1111');
Have a look at the Request constructor:
public function __construct($salesperson, $client, $status, $qualification) {
$this->salesperson = $salesperson;
$this->client = $client;
$this->status = $status;
$this->qualification = $qualification;
}
As you can see, the first parameter is $salesperson. You try to put the value "Keyboard" here. The $salesperson attribute is defined this way:
/**
* #ORM\ManyToMany(targetEntity="Salesperson", inversedBy="request")
* #ORM\JoinTable(name="request_salesperson")
* #var Salesperson
*/
private $salesperson;
/**
* #param Salesperson $salesperson
*/
public function setSalesperson($salesperson)
{
$this->salesperson = $salesperson;
}
Now, here is your problem I think.
The $salesperson property is defined as a "ManyToMany" association. So you really cannot put a string in here, it is a collection of Salesperson. By the way, you should not "set" anything either. The setter should be completely removed.
Instead, you should consider using it as per the documentation here: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html
For instance:
$request->getSalesPersons()->add($someObjectRepresentingAPerson);
Also, notice that since the $salesperson represents a collection of Salesperson object, your should really name it $salesPersons (plural form)
So I am working on a page in Laravel that generates invite codes upon email submission. I have run into this issue, every time when I enter my email into the form, it is supposed to generate an invite code an input it into my DB then redirect me. Instead I get this error code:
Argument 1 passed to myapp\Repositories\Invite\EloquentInviteRepository::__construct()
must be an instance of Illuminate\Database\Eloquent\Model, instance of
Illuminate\Foundation\Application given, called in /var/www/laravel/bootstrap/compiled.php
on line 4259 and defined
This is my EloquentInviteRepository.php file, apparently line 21 is the line in error:
<?php namespace myapp\Repositories\Invite;
use myapp\Repositories\Crudable;
use Illuminate\Support\MessageBag;
use myapp\Repositories\Repository;
use Illuminate\Database\Eloquent\Model;
use myapp\Repositories\AbstractRepository;
class EloquentInviteRepository extends AbstractRepository implements Repository, Crudable, InviteRepository {
/**
* #var Illuminate\Database\Eloquent\Model
*/
protected $model;
/**
* Construct
*
* #param Illuminate\Database\Eloquent\Model $user
*/
public function __construct(Model $model)
{
parent::__construct(new MessageBag);
$this->model = $model;
}
/**
* Find a valid invite by a code
*
* #param string $code
* #return Illuminate\Database\Eloquent\Model
*/
public function getValidInviteByCode($code)
{
return $this->model->where('code', '=', $code)
->where('claimed_at', '=', null)
->first();
}
/**
* Create
*
* #param array $data
* #return Illuminate\Database\Eloquent\Model
*/
public function create(array $data)
{
$data['code'] = bin2hex(openssl_random_pseudo_bytes(16));
return $this->model->create($data);
}
/**
* Update
*
* #param array $data
* #return Illuminate\Database\Eloquent\Model
*/
public function update(array $data){}
/**
* Delete
*
* #param int $id
* #return boolean
*/
public function delete($id){}
}
In case anyone was curious; the __construct() interface from Illuminate\Database\Eloquent\Model.php:
/**
* Create a new Eloquent model instance.
*
* #param array $attributes
* #return void
*/
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
and Illuminate\Foundation\Application.php:
/**
* Create a new Illuminate application instance.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
public function __construct(Request $request = null)
{
$this->registerBaseBindings($request ?: $this->createNewRequest());
$this->registerBaseServiceProviders();
$this->registerBaseMiddlewares();
}
In case these help in debugging the issue!
As per request I have included my controller element used during the post function, this is the part that seems to activate the repository and prompt the error:
<?php
use myapp\Repositories\Invite\InviteRepository;
class InviteController extends BaseController {
/**
* InviteRepository
*
* #var myapp\Repositories\Invite\InviteRepository
*/
protected $repository;
/**
* Create a new instance of the InviteController
*
* #param myapp\Repositories\Invite\InviteRepository
*/
public function __construct(InviteRepository $repository)
{
$this->repository = $repository;
}
/**
* Create a new invite
*
* #return Response
*/
public function store()
{
$invite = $this->repository->create(Input::all());
}
}
RepositoryServiceProvider.php
<?php namespace myapp\Repositories;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider {
/**
* Register
*/
public function register()
{
$this->registerInviteRepository();
}
/**
* Register the Invite Repository
*
* #return void
*/
public function registerInviteRepository()
{
$this->app->bind('myapp\Repositories\Invite\InviteRepository', function($app)
{
return new EloquentInviteRepository( new Invite );
});
}
}
Any idea's as to what I am missing?
Thanks for the help guys,
You've been a great resource so far!
In the file RepositoryServiceProvider.php, replace this
$this->app->bind('myapp\Repositories\Invite\InviteRepository', function($app)
{
return new EloquentInviteRepository( new Invite );
});
With this:
$this->app->bind('myapp\Repositories\Invite\InviteRepository',
'myapp\Repositories\Invite\EloquentInviteRepository');