Reputation: 19
I have a date field of type Date. I want to take that value of the year. thank you for giving me help. because I searched the internet but I did not find the solution. thanks for your understanding.
this is the format of date that i use : $date = $form->get('date')->getData(); $date->format('Y-m-d') this is my repository:
public function findEnglishByTags($date, $categorie, $tags) {
$tags_values = $tags->getValues();
array_walk($tags_values, function (&$item) {
$item = $item->getId();
});
$qb = $this->createQueryBuilder('english');
$qb->where('english.date = :date')
->andWhere('english.Categorie IN (:categories)')
->leftjoin('english.tags', 't')
->andWhere('t.id IN (:tags)')
->setParameters(array('date' => $date, 'categories' => $categorie->getId(), 'tags' => $tags))
;
return $qb->getQuery()->getResult();
}
my controller:
public function searchAction()
{
$form = $this->createForm('MDWEB\FrontBundle\Form\InEnglishFrontType');
$request = $this->container->get('request_stack')->getCurrentRequest();
$form->handleRequest($request);
$date = $form->get('date')->getData();
$categorie = $form->get('categorie')->getData();
$tags = $form->get('tags')->getData();
$em = $this->getDoctrine()->getManager();
$listEnglishs = $em->getRepository('MDWEBInEnglishBundle:InEnglish')
->findEnglishBytags(new \DateTime($date->format('Y')), $categorie, $tags);
return $this->render('MDWEBFrontBundle:InEnglish:list.html.twig', array(
'form' => $form->createView(),
'listEnglishs' => $listEnglishs
));
}
i want to change date by Year knowing that i haven't a field named Year in my entity.
Upvotes: 0
Views: 1535
Reputation: 4582
The problem is the query you use in your repository. Since you have a Date field in your database and you want to check if this date belongs to a specific year, you have to do something like this:
$startDate = $date->format('Y-01-01');
$endDate = $date->format('Y-12-31');
$qb = $this->createQueryBuilder('english');
$qb->where('english.date BETWEEN :startDate AND :endDate')
->andWhere('english.Categorie IN (:categories)')
->leftjoin('english.tags', 't')
->andWhere('t.id IN (:tags)')
->setParameters(array('startDate' => $startDate, 'endDate' => $endDate,
'categories' => $categorie->getId(), 'tags' => $tags))
;
In fact most SQLs have a native YEAR function but Doctrine hasn't implemented it. You could install doctrine extensions so you can use it.
Upvotes: 2
Reputation: 20201
The new \DateTime($date->format('Y'))
won't work because there is no such constructor of \DateTime
class. The one that exists, looks like this:
public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
I am a bit confused by you code, so please help me understand it:
date
field\DateTime
object\DateTime
and pass it to your repositorySo, is your "date" columns really of type "date"?
Upvotes: 0