accessing repository in symfony - symfony

I am using symfony and am inside the controller trying to return a set of records by using a range (rangeUpper, rangeLower).
I am passing the parameters in the request object fine. But when going to route in the controller and trying to access the repository class I am at a loss. My repository looks like;
public function findAllByParams (Request $request)
{
$criteria = $request->query->get('uniflytebundle_material-stock_select');
$criteria = ($request->get('materialId') == 0 ? [] : ['materialId' => $request->get('materialId')]);
$criteria = array_merge(($request->get('gaugeId') == 0 ? [] : ['gaugeId' => $request->get('gaugeId')]), $criteria);
$criteria = array_merge(($request->get('rangeUpper') == 0 ? [] : ['rangeUpper' => $request->get('rangeUpper')]), $criteria);
$criteria = array_merge(($request->get('rangeLower') == 0 ? [] : ['rangeLower' => $request->get('rangeLower')]), $criteria);
$criteria = array_filter($criteria);
$query = $this->createQueryBuilder('ms');
if (!empty($criteria)) {
if (!empty($criteria['materialId']) && !empty($criteria['gaugeId']) && !empty($criteria['rangeUpper']) && !empty($criteria['rangeLower'])) {
$query
->where('ms.material = :materialId')
->andWhere('ms.gauge = :gaugeId')
->andWhere('ms.widthDecimal <= :upperIdentifier')
->andWhere('ms.widthDecimal >= :lowerIdentifier')
->setParameter('materialId', $criteria['materialId'])
->setParameter('gaugeId', $criteria['gaugeId'])
->setParameter('upperIdentifier', $criteria['rangeUpper'])
->setParameter('lowerIdentifier', $criteria['rangeLower'])
;
}
}
$query->orderBy('ms.widthDecimal', 'DESC');
return $query->getQuery()->getResult();
}
My current controller looks like
public function selectStripWidthAction (Request $request)
{
$em = $this->getDoctrine()->getManager();
$materialId = $request->get('materialId');
$gaugeId = $request->get('gaugeId');
$materialStocks = $em->getRepository('UniflyteBundle:MaterialStock')->findAllByParams($request);
return $this->render('materialstock/dialog/select.html.twig', [
'MaterialStocks' => $materialStocks,
]);
}
In the Repository I have the query setup to accept and query by the Range. How do I pass the request object and retrieve the result set from the Repository? FindAllByParams call in the controller is not working.
Undefined method 'findAllByParams'. The method name must start with either findBy or findOneBy!
Thanks in advance for your time and effort.

Check that your MaterialStock have annotation for repository.
<?php
namespace UniflyteBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* MaterialStock
*
* #ORM\Table(name="material_stock")
* #ORM\Entity(repositoryClass="UniflyteBundle\Repository\MaterialStockRepository")
*/
class MaterialStock{
// [...]
}

Related

Or on symfony findOneBy

Is possible to make a request by one filed or another using the orm on symfony
$user_test = $em->getRepository("AppBundle:UserTest")->findOneBy([
'hash' => $data->user_data->hash,
'code' => $data->user_data->hash],
);
to get something like WHERE hash = 'foo' OR code = 'foo'
you have to define the method in the entity UserTest repository
// UserTestRepository.php
public function getUserTestByHashOrCode($hash, $code){
return $this->createQueryBuilder('u')
->where('hash = :hash')
->orWhere('code = :code')
->setParameter('hash', $hash)
->setParameter('code', $code)
->getQuery()
->getOneOrNullResult();
and then
$user_test = $em->getRepository("AppBundle:UserTest")->getUserTestByHashOrCode($data->user_data->hash, $data->user_data->hash);

Doctrine DQL query produces Error: Expected Literal, got end of string

I am currently trying to build a blog website following a course that uses
Symfony 2.5.2. (PHP -v 7.0)
To retrieve a post I am using a following Controller
/**
* #Route(
* "/{slug}",
* name = "blog_post"
* )
* #Template()
*/
public function postAction($slug)
{
$PostRepo = $this->getDoctrine()->getRepository('AniaBlogBundle:Post');
$Post = $PostRepo->getPublishedPost($slug);
if(null === $Post){
throw $this->createNotFoundException('Post not found');
}
return array(
'post'=> $Post
);
}
and here is my getPublishedPost function :
public function getPublishedPost($slug){
$qb = $this->getQueryBuilder(array(
'status' => 'published'
));
$qb->andWhere('p.slug = :slug')
->setParameter('slug', $slug);
return $qb->getQuery()->getOneOrNullResult();
}
and getQueryBuilder function :
public function getQueryBuilder(array $params = array()){
$qb = $this->createQueryBuilder('p')
->select('p, c, t')
->leftJoin('p.category', 'c')
->leftJoin('p.tags', 't');
if(!empty($params['status'])){
if('published' == $params['status']){
$qb->where('p.publishedDate <= :currDate AND p.publishedDate IS NOT NULL')
->setParameter('currDate', new \DateTime());
}else if('unpublished' == $params['status']) {
$qb->where('p.publishedDate > :currDate OR p.publishedDate IS NULL')
->setParameter('currDate', new \DateTime());
}
}
if(!empty($params['orderBy'])){
$orderDir = !empty($params['orderDir']) ? $params['orderDir'] : NULL;
$qb->orderBy($params['orderBy'], $orderDir);
}
if(!empty($params['categorySlug'])){
$qb->andWhere('c.slug = :categorySlug')
->setParameter('categorySlug', $params['categorySlug']);
}
if(!empty($params['tagSlug'])){
$qb->andWhere('t.slug = :tagSlug')
->setParameter('tagSlug', $params['tagSlug']);
}
if(!empty($params['search'])) {
$searchParam = '%'.$params['search'].'%';
$qb->andWhere('p.title LIKE :searchParam OR p.content LIKE :searchParam')
->setParameter('searchParam', $searchParam);
}
return $qb;
}
}
However i get the 500 error saying : [Syntax Error] line 0, col -1: Error: Expected Literal, got end of string.
Thank you in advance for any suggestions!

Callback Constraint doesn't show paylod (Symfony Validator Component)

My controller code:
public function postFilesAction(Request $request)
{
$validator = $this->get('validator');
$requestCredentials = RequestCredentials::fromRequest($request);
$errors = $validator->validate($requestCredentials);
...
validate method in RequestCredentials (Callback constraint).
/**
* #Assert\Callback(payload = {"errorCode" = "FILE_FILE_URL"})
*/
public function validate(ExecutionContextInterface $context)
{
if (! ($this->fileExistsAndValid() || $this->fileUrlExistsAndValid())) {
$context->buildViolation('Neither file nor file_url is present.')->addViolation();
}
}
Callback works as expected, but the value of $constraintViolation->$constraint->$payload is null.
When I'm trying to use payload in other Constraints (NotBlank, for example), it works (I can see it in ConstraintViolation object).
Is it Symfony bug or am I doing somethings wrong? Should I use some other solution to my problem? (I need to check if there's at least one of two fields (file or file_url) present in request).
In Symfony 3.0 you cannot easily access the payload in the callback when using the Callback constraint. Starting with Symfony 3.1, the payload will be passed as an additional argument to the callback (see https://github.com/symfony/symfony/issues/15092 and https://github.com/symfony/symfony/pull/16909).
I managed to solve this problem with following code in the assertion:
/**
* #Assert\Callback(payload = {"error_code" = "1"}, callback = "validate", groups = {"Default", "RequestCredentials"})
*/
public function validate(ExecutionContextInterface $context)
{
// some validation code
}
I think the problem was because of the Symfony Callback constraint constructor:
public function __construct($options = null)
{
// Invocation through annotations with an array parameter only
if (is_array($options) && 1 === count($options) && isset($options['value'])) {
$options = $options['value'];
}
if (is_array($options) && !isset($options['callback']) && !isset($options['groups'])) {
$options = array('callback' => $options);
}
parent::__construct($options);
}
When it is given $options = ['payload' => [...]] (what happened in my case) it turns it into $options = ['callback' => ['payload' => [...]]]
and then '$payload' data becomes inacessable in ConstraintViolation object.
But I'm still not sure whether it's Symfony imperfection or me not getting something and using it wrong.

how to access annotation of an property(class,mappedBy,inversedBy)

Good morning,
Is it exist an function where I pass an entity and the propertyName and return me the mappedBy,inversedBy and absoluteClassName of an Entity.
The goal is to use the __call to create automatic getteur/setteur and addFucntion bidirectionnal.
I don't want to use generates Entities I want all getteur,setteur and add Function use __call.
But i can"t do an addBirectionnal if i don't know if the relation is many to many or one to many and if i don't know the name of the mappedBy.
my code:
public function __get($p){
return $this->$p;
}
public function __set($p,$v){
$this->$p = $v;
return $this;
}
public function __call($name,$arguments){
if(substr($name,1,3)=='et')
$name2 = substr(3);
if($name[0] == 'g'){
return $this->$name2;
}else{//substr($name,0,1) == 's'
$this->$name2 = $arguments[0];
/*for a one to one*/
/*$mappedByName= getmappedByOrInversedBy(get_class($name),$name2);
if($mappedByName){
$this->$name->$mappedByName = $this;/
}*/
return $this;
}
}
}
I need getmappedByOrInversedBy, thanks.
edit: I try this
public function test(){
$str = "AppBundle\Entity\Group";
$mapping = new \Doctrine\ORM\Mapping\ClassMetadataInfo($str);
$d = $mapping->getAssociationMappedByTargetField('trad');
var_dump($d);
return $this->render('default/index.html.twig', array(
'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..'),
));
}
class Group
{
...
/**
* #ORM\OneToOne(targetEntity="Traduction",inversedBy="grp")
*/
protected $trad;
}
Result : Undefined index: trad
The ClassMetadataInfo is what you are looking for.
Creates an instance with the entityName :
$mapping = new \Doctrine\ORM\Mapping\ClassMetadataInfo($entityNamespaceOrAlias);
Then, get the informations you want :
Get all association names: $mapping->getAssociationNames();
Get the join column of an association:
$mapping->getSingleAssociationJoinColumnName($fieldName);
Get the mappedBy column of an association:
$mapping->getAssociationMappedByTargetField($fieldName);
...
Look at the class to know which method you can access.
Hopes it's what you expect.
EDIT
As you can access the EntityManager (i.e. from a controller), use :
$em = $this->getDoctrine()->getManager();
$metadata = $em->getClassMetadata('AppBundle:Group');
To be sure there is no problem with your entity namespace, try :
print $metadata->getTableName();
To retrieve the associations of the entity, use :
$metadata->getAssociationNames();
And to get the mapping informations of an existing association, use :
$metadata->getAssociationMapping($fieldName);
And to get all the association mappings of your entity, use:
$metadata->getAssociationMappings();

stack at Doctrine PostPersist event listener

its my VisitorController Class
public function chooseVisitor($zone)
{
$em = $this->getDoctrine()->getManager();
$lvisitor = $em->getRepository('EMRSabaBundle:Personel')->findOneBy(array('status' => '1', 'lastv' => '1', 'zone' => $zone));
$id = $lvisitor->getId();
$lvisitor->setLastv(0);
$newvisitorid = $em->getRepository('EMRSabaBundle:Personel')->findNewVisitor($id);
$newvisitorid = $newvisitorid[0];
$newvisitor = $em->getRepository('EMRSabaBundle:Personel')->find($newvisitorid);
$newvisitor->setLastv(1);
$em->flush();
return $newvisitor;
}
public function defineZone($Customer)
{
$phone = substr($Customer,1);
switch ($phone)
{
case 2:
$zone = 1;
break;
case 4:
$zone = 1;
break;
case 8:
$zone = 2;
break;
case 7:
$zone = 3;
break;
}
return $zone;
}
my EventListener
namespace EMR\SabaBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use EMR\SabaBundle\Entity\Orders;
use EMR\SabaBundle\Entity\Visit;
use EMR\SabaBundle\Controller\VisitController;
class EntityListener {
public function postPersist(LifecycleEventArgs $args)
{
$orders = $args->getEntity();
$em = $args->getEntityManager();
if ($orders instanceof Orders){
if ($orders->getStatus() == 1){
$VC = new VisitController();
$zone = $VC->defineZone($orders->getCustomer()->getId());
$personel = $VC->chooseVisitor($zone);
$visit = new Visit();
$visit->setDate(new \DateTime());
$visit->setStatus(0);
$visit->setOrders($orders);
$visit->setPersonel($personel);
$em->persist($visit);
$em->flush();
}
}
}
}
& my services.yml
entity.listener:
class: EMR\SabaBundle\EventListener\EntityListener
tags:
- { name: doctrine.event_listener, event: postPersist }
i want to create & persist new visit when order entity status is 1
i dont know where is the problem & how to debug the event listener
Could anyone give me a hand to accomplish this job
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#postupdate-postremove-postpersist
postUpdate, postRemove, postPersist
The three post events are called inside EntityManager#flush(). Changes
in here are not relevant to the persistence in the database, but you
can use these events to alter non-persistable items, like non-mapped
fields, logging or even associated classes that are directly mapped by
Doctrine.
Try prePersist event.

Resources