I have function
/**
* My function
*
* #FOS\View()
* #FOS\Get("/myfunction/?param1={p1}¶m2={p2}¶mn={pn}")
*
* #param integer $param1
* #param integer $param2
* #param integer $paramn
* #return mixed
*/
public function getMyFunction($param1, $param2, $paramn)
{
return new Response($param1. ' ' . $param1. ' ' . $paramn);
}
But when I call http://host/myfunction/?param1=1¶m1=2¶mn=3 dosen't work.
What is wrong in definition of function?
UPDATE: New function
/**
* My function
*
* #FOS\View()
* #FOS\Get("/myfunction/")
*
* Request $request
* #return mixed
*/
public function getMyFunction(Request $request)
{
$requestParams = $request->request->all();
return new Response($requestParams['param1']);
}
And, now I call http://host/myfunctin/?param1=1, but still, dosen't work.
Error: "Notice: Undefined index: param1"
Request for get parameters isn't good?
Thanks!
You have to remove the query string parameters from the route.
To get them you have to inject a Request object in the function signature and the use $request->get('parametername') to retrieve then.
Related
I create three query build queries, I try to combine them into a single query doctrine but I do not know how to achieve
the purpose of creating a single request is to eliminate the round-trip client server. please how can I get one request?
this is my request 1
/**
* #param Analyse $analyse
* #return mixed
* #throws \Doctrine\ORM\NonUniqueResultException
*/
public function countTotalErrorByIdAnalyse(Analyse $analyse)
{
return $this->createQueryBuilder('a')
->select('count(a)')
->innerJoin('a.analyse', 'analyse')
->where('analyse.id = :analyse')
->setParameter('analyse', $analyse->getId())
->getQuery()
->getSingleScalarResult();
}
this is my Resquest 2
/**
* #param Analyse $analyse
* #param string $severity
* #return mixed
* #throws \Doctrine\ORM\NonUniqueResultException
*/
public function countTypeError(Analyse $analyse, string $severity){
return $this->createQueryBuilder('a')
->select('count(a)')
->innerJoin('a.analyse', 'analyse')
->innerJoin('a.rule', 'rule')
->where('rule.severity = :error')
->setParameter('error', $severity)
->getQuery()
->getSingleScalarResult();
}
this is my request 3
/**
* #param Analyse $analyse
* #return mixed
* #throws \Doctrine\ORM\NonUniqueResultException
*/
public function listTypeError(Analyse $analyse){
return $this->createQueryBuilder('a')
->select('rule.message')
->innerJoin('a.analyse', 'analyse')
->innerJoin('a.rule', 'rule')
->where('rule.severity = :error')
->setParameter('error', 'ERROR')
->getQuery()
->getResult();
}
I want to get some data from an entity class. I tried to use try/catch to handle problems but it is not working (still gives me the Exception screen).
Error: Call to a member function getGroup() on a non-object in
/var/www/html/system/src/Project/SomeBundle/Entity/MyEntity.php line
139
500 Internal Server Error - FatalErrorException Stack Trace
How can I do something like that in an entity?
Code/Entity:
<?php
namespace Project\SomeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* MyEntity
*
* #ORM\Table(name="my_entity")
* #ORM\Entity(repositoryClass="Project\SomeBundle\Entity\Repository\MyEntityRepository")
*/
class MyEntity
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #Assert\Length(max="255")
*/
private $name;
/**
* #var Item[]|Collection
*
* #ORM\OneToMany(targetEntity="Project\SomeBundle\Entity\Item", mappedBy="itemType", cascade={"remove"}, fetch="EXTRA_LAZY")
*/
protected $items;
// [...]
/**
* Get some data
*
* #return string
*/
public function getSomeData()
{
$result = null;
try {
$result = $this->getName() . ' - ' . $this->getItems()->last()->getGroup()->getCode();
}
catch(\Exception $exception) {
$result = $this->getName();
$logFile = fopen('/tmp/error.log', 'a');
fwrite($logFile, $exception->getMessage());
fclose($logFile);
}
return $result;
}
}
Thanks in advance...
The error message Error: Call to a member function getGroup() on a non-object in... has very little to do with where you're receiving it. It means that you are trying to call a function on something that isn't an object.
It seems likely that $this->getItems()->last() is somehow returning null (because there are no items), and then you're calling getGroup() on null which is a non-object.
Try to debug the object on which you're calling getGroup() and see what value it holds just before you call it.
If you want to catch that error you must write try catch as following
try {
$result = $this->getName() . ' - ' . $this->getItems()->last()->getGroup()->getCode();
}
catch(\Symfony\Component\Debug\Exception\FatalErrorException $exception) {
$result = $this->getName();
$logFile = fopen('/tmp/error.log', 'a');
fwrite($logFile, $exception->getMessage());
fclose($logFile);
}
You can see I have changed \Exception to \Symfony\Component\Debug\Exception\FatalErrorException in above code block
I'm trying to save a datetime value using an input but I keep getting the error
Call to a member function format() on string
This is how I've been trying to save the value.
/**
* #var \DateTime
*
* #ORM\Column(name="end_date", type="datetime", nullable=true)
*/
private $endDate;
/**
* Set endDate
*
* #param \DateTime $endDate
*
* #return voorstellingen
*/
public function setEndDate($endDate)
{
$time = new \DateTime($this->endDate = $endDate);
$time->format('Y-m-d');
return $time;
}
I'm not sure where I'm going wrong. Can anyone help me?
edit: changing my setter to
/**
* Set endDate
*
* #param \DateTime $endDate
*
* #return voorstellingen
*/
public function setEndDate($endDate)
{
$this->endDate = new \DateTime($endDate);
return $this;
}
solved the issue.
Like jbafford said setters in Symfony Should return $this.
I am working with form aimed at uploading the file and updating the database in Symfony2. I want to manually set value of book_id field and not to allow user to change it in the form. Thus in my controller before using doctrine to persist document I am calling:
$documents->setBookId('1');
Unluckilly I get error which indicates that the doctrine does not recognise the above hard coded value input.
An exception occurred while executing 'INSERT INTO Documents (book_id, marker, document_date, link, notes) VALUES (?, ?, ?, ?, ?)' with params [null, "fdd", "2015-04-04", null, "test"]:
To my mind this may be connected with the fact that book_id field is related to Books. Therefore probably I should use setBook function instead. Could you please advice how to do this properly?
My controler file looks like this:
/**
* This code is aimed at checking if the book is chosen and therefore whether any further works may be carried out
*/
$session = new Session();
if(!$session->get("App_Books_Chosen_Lp")) return new RedirectResponse($this->generateUrl('app_listbooks'));
// Authorization goes here
$documents = new Documents();
$form = $this->createForm(new DocumentsType(), $documents);
$form->add('save', 'submit', array('label' => 'Dodaj dokument'));
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$documents->upload();
$documents->setBookId('1');
$em->persist($documents);
$em->flush();
}
return $this->render('AppBundle:Documents:adddocuments.html.twig', array('form' => $form->createView()));
Document class:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* #ORM\Entity
* #ORM\Table(name="Documents")
* #ORM\HasLifecycleCallbacks
*/
class Documents
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Books", inversedBy="documents")
* #ORM\JoinColumn(name="book_id", referencedColumnName="id")
*/
protected $book;
/**
* #ORM\Column(type="integer")
*/
protected $book_id;
/**
* #ORM\Column(type="string", length=220)
*/
protected $marker;
/**
* #ORM\Column(type="date", length=220)
*/
protected $document_date;
/**
* #ORM\Column(type="string", length=220)
* #Assert\File(maxSize="6000000")
*/
protected $link;
/**
* #ORM\Column(type="text")
*/
protected $notes;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set book_id
*
* #param integer $bookId
* #return Documents
*/
public function setBookId($bookId)
{
$this->book_id = $bookId;
return $this;
}
/**
* Get book_id
*
* #return integer
*/
public function getBookId()
{
return $this->book_id;
}
/**
* Set marker
*
* #param string $marker
* #return Documents
*/
public function setMarker($marker)
{
$this->marker = $marker;
return $this;
}
/**
* Get marker
*
* #return string
*/
public function getMarker()
{
return $this->marker;
}
/**
* Set document_date
*
* #param \DateTime $documentDate
* #return Documents
*/
public function setDocumentDate($documentDate)
{
$this->document_date = $documentDate;
return $this;
}
/**
* Get document_date
*
* #return \DateTime
*/
public function getDocumentDate()
{
return $this->document_date;
}
/**
* Set link
*
* #param string $link
* #return Documents
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set notes
*
* #param string $notes
* #return Documents
*/
public function setNotes($notes)
{
$this->notes = $notes;
return $this;
}
/**
* Get notes
*
* #return string
*/
public function getNotes()
{
return $this->notes;
}
/**
* Set book
*
* #param \AppBundle\Entity\Books $book
* #return Documents
*/
public function setBook(\AppBundle\Entity\Books $book = null)
{
$this->book = $book;
return $this;
}
/**
* Get book
*
* #return \AppBundle\Entity\Books
*/
public function getBook()
{
return $this->book;
}
/*
* ### FILE UPLOAD PROCESS ###
*/
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
public function getAbsolutePath()
{
return null === $this->path
? null
: $this->getUploadRootDir().'/'.$this->path;
}
public function getWebPath()
{
return null === $this->path
? null
: $this->getUploadDir().'/'.$this->path;
}
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
// documents should be saved
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir()
{
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'uploads/documents';
}
public function upload()
{
// the file property can be empty if the field is not required
if (null === $this->getFile()) {
return;
}
// use the original file name here but you should
// sanitize it at least to avoid any security issues
// move takes the target directory and then the
// target filename to move to
$this->getFile()->move(
$this->getUploadRootDir(),
$this->getFile()->getClientOriginalName()
);
// set the path property to the filename where you've saved the file
$this->path = $this->getFile()->getClientOriginalName();
// clean up the file property as you won't need it anymore
$this->file = null;
}
}
Okay, first since you're using ManyToOne relation, you don't actually need another property refering to the book - book_id. You can remove that and leave book only.
Then in your controller you have to query the database for that Book and set the that object your Document.
You can do it like this:
$bookId = 1; // Following your example, let's say tou already know the book ID.
$book = $em->getReference('AppBundle:Books', $bookId);
// Check if we actually found a record and then set it to Documents
// Looking at your entity mapping, your reference to Book can not be null,
// but doing an extra check never hurts, since this is just an example.
if( $book ) {
$documents->setBook($book);
}
-Update-
If you want to directly insert the bookID, then what is the purpose of having ManyToOne reference in your entity? Eventually you're going to have to start using doctrine's relations and objects properly. Also, the cool thing about getReference method is that you are getting a reference to an entity, without having to load the entity from the database - you get the so called Proxy objects.
The method EntityManager#getReference($entityName, $identifier) lets you obtain a reference to an entity for which the identifier is known, without loading that entity from the database. This is useful, for example, as a performance enhancement, when you want to establish an association to an entity for which you have the identifier
You can read further about this here.
Simple example, we've got
/**
* #ORM\Column(name="api_keyID", type="integer", nullable=false)
*/
private $api_keyID;
/**
* #return integer
*/
public function getApi_keyID()
{
return $this->api_keyID;
}
/**
* #param integer $api_keyID
* #return object
*/
public function setApi_keyID($data)
{
$this->api_keyID = $data;
return $this;
}
Look at method name and column name. When i try
//...
->findOneByApi_keyID($some);
I'm getting an error like
Entity 'entity\path' has no field 'apiKeyID'. You can therefore not call 'findOneByApi_keyID' on the entities' repository
So doctrine\symfony eats underscore? О.о And i cannot use it in column name?
is the way out
$repository->findBy(array('is_enabled' => true));
Founded here
Magic Doctrine2 finders when field has underscore?