How to effectively pass data from my controller to repository, Symfony - php

I'm working on a Symfony project that makes use of a
Repository file in which I have declared and created an instance of a query builder
(repository1)
$mk = $this->createQueryBuilder('up');
$later = date("Y-m-d", strtotime("-3 months"));
$today = date("Y-m-d");
$mk->andWhere('up.period BETWEEN :start AND :end');
$mk->setParameter('start', $later);
$mk->setParameter('end', $today);
return $mk->getQuery()->getResult();
automatically this generates data for my page between the above dates.
Now I want to create a form where I can make a search between two dates.
with the intention of passing the posted data from this form to my controller into my method below
My controller below (controller1)
protected function getData(EntityManagerInterface $entityManager,Request $request) {
// this code to get data from repository
$entityManager->getRepository(repository1::class)->getName()
// receive posted data
$date1 = $request->get('date');
$date2 = $request->get('date');
// now how to pass data to my repository1
}
Please how do I edit what I have to post data from within my controller to my (repository1)
so then it would be
$mk = $this->createQueryBuilder('up');
$later = $date1;
$today = $date2;
$mk->andWhere('up.period BETWEEN :start AND :end');
$mk->setParameter('start', $later);
$mk->setParameter('end', $today);
return $mk->getQuery()->getResult();
is this even possible, or im over thinking it?

RepositoryClass
public function getByStartEndDate(DateTimeInterface $start, DateTimeInterface $end)
{
return $this->createQueryBuilder('up')
->andWhere('up.period BETWEEN :start AND :end')
->setParameter('start', $start)
->setParameter('end', $end)
->getQuery()
->getResult()
;
}
Controller Class
private function getData(Request $request, RepositoryClass $repo)
{
// May need to convert these to DateTime objects
$start = $request->get('start');
$end = $request->get('end');
$records = $repo->getByStartEndDate($start, $end);
// do what you want with the records here
}

You can give the dates as parameters to your method.
Controller Class:
protected function getData(EntityManagerInterface $entityManager,Request $request) {
$start = $request->get('start') ? new \DateTime($request->get('start')) : null;
$end = $request->get('end') ? new \DateTime($request->get('end')) : null;
$result = $entityManager->getRepository(Entity::class)->getName($start, $end);
// do with result as desired
}
Repository Class:
public function getName(\DateTimeInterface $start, \DateTimeInterface $end)
{
return $this->createQueryBuilder('up')
->andWhere('up.period BETWEEN :start AND :end')
->setParameter('start', $start)
->setParameter('end', $end)
->getQuery()
->getResult()
;
}

Related

Datetime range won't select specific date

I have a method to return results from db from startDate to endDate passing in like parameters in postman.
Everything seems to be working fine but it returns all results from database.
I think that problem could be with parameters..
public function getInvoices($fromDate = null, $toDate = null)
{
$query = $this->entityManager->getRepository(Invoice::class)
->createQueryBuilder('ur')
->select('ur')
->orderBy('ur.invoiceDate', 'ASC');
if($fromDate) {
$query
->andWhere('t.invoiceDate >= :startDate')
->setParameter('startDate', new \DateTime($fromDate));
}
if($toDate) {
$query
->andWhere('t.invoiceDate <= :endDate')
->setParameter('endDate', new \DateTime($toDate));
}
return $query->getQuery()->getResult();
}
And I am calling this method in my controller like:
$data = [];
$responseData = $this->invoiceService->getInvoices(
#$this->data['startDate'],
#$this->data['endDate']
);
I pass this two parameters via postman and it returns all results:
Here is an image: here

How to get the selected one instead of latest in laravel

I have a Leave Application that checks when the users request a leave and after approval, it removes the days from the total amount they have left in the database the problem is the leave is taken only the latest so if 2 people were requesting at the same time it would take it for both the same amount because it's only taking it from the latest which is here in the User Model
public function leaveBalance($id)
{
$leave =new Leave;
$daysUsed= $leave->numberOfDays($id);
$days_granted = User::where('id', $id)
->latest()->first();
$leave_days_granted = $days_granted->leave_days_granted;
return $leave_days_granted - $daysUsed;
}
And here in the Leave Model
protected $dates = ['from', 'to'];
public function numberOfDays($id)
{
$datesx =Leave::where('user_id', $id)
->latest()->first();
$from =$datesx->from;
$to =$datesx->to;
$datetime1 = new DateTime($from);
$datetime2 = new DateTime($to);
$interval = $datetime1->diff($datetime2);
$days = $interval->format('%a');//now do whatever you like with $days
return $days;
}
As you can see it's taking it from the ->latest()->first(); but I don't know another way to select it and thus why I need help I would appreciate any suggestion
User::where('id', $id)->first();

fatfree framework, bug pr misuse?

i have this db function in f3 framework
public function sumOfAmount($startdate, $enddate) {
$this->amount = 'price*quantity';
$this->sumamount = 'SUM(price*quantity)';
$this->load(array('createon > ? AND createon < ?', $startdate, $enddate));
//return $this->query;
return $this->cast();
}
it seem that sumamount is not correct , from the f3 log i have this query executed
SELECT `idproduct`,`idtransaction`,`idline`,`name`,`code`,`price`,`quantity`,`createon`,(price * quantity) AS `amount`,(SUM(price * quantity)) AS `sumamount` FROM `qrysales`
but if i run that query in phpmyadmin result is ok
Any idea??
it seems that i forgot group by clause
public function sumOfAmount($startdate, $enddate) {
$this->amount = 'price*quantity';
$this->sumamount = 'SUM(price*quantity)';
$this->load(array('createon > ? AND createon < ?', $startdate, $enddate,'group' => 'idline'));
//return $this->query;
return $this->cast();
}

PHP check date difference for backward date

I have checked that the input date is a valid date, now need to check for backward date where date_start must be before date_end.
I have tried several other option to no avail, I really dont want to compare the substring of the input if possible.
The input are from html5 date using chrome with format dd/mm/yyyy
class MY_Form_validation extends CI_Form_validation {
public $CI;
public function date_format($date) {
if (($timestamp = strtotime($date)) === false) {
return false;
}
}
//error message stored in caller module language folder
public function backward_date($date_start, $date_end) {
$date_1 = new DateTime($date_start);
$date_2 = new DateTime($date_end);
if ($date_1 > $date_2 == true) {
return false;
}
else {
return true;
}
}
}
try this one
public function backward_date($date_start, $date_end) {
$ts1 = strtotime($date_start);
$ts2 = strtotime($date_end);
$seconds_diff = $ts2 - $ts1;
return ($seconds_diff>0) ? true : false;
}
The problem here is that DateTime is not able to parse the string from 'dd/mm/yyyy' to a valid DateTime Object.
Here is the received error :
PHP Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (27/10/2017)
In order to fix this, you could use the createFromFormat() method from the DateTime model to parse your string with a specified format.
$date_1 = DateTime::createFromFormat('d/m/Y', $date_start);
So your method would be like :
public function backward_date($date_start, $date_end)
{
$date_1 = DateTime::createFromFormat('d/m/Y', $date_start);
$date_2 = DateTime::createFromFormat('d/m/Y', $date_end);
return $date_1 <= $date_2;
}
Hope it helps.
Try to this ... Working for me.
function date_calculate($start_date, $end_date) {
$dStart = new DateTime($start_date);
$dEnd = new DateTime($end_date);
$days=0;
if ($dStart < $dEnd) {
$dDiff = $dStart->diff($dEnd);
$dDiff->format('%R');
$days = $dDiff->days;
return $days;
} else {
return $days;
}
}

Doctrine and Function YEAR()

Hello i'm working in project with Symfony 2.4 i want to make a select using QueryBuilder but i have a exception :
FatalErrorException: Error: Call to undefined method getEntityManager()
This is my code :
$session=$this->get('session');
$id_client=$session->get('client');
$emConfig = $this->getEntityManager()->getConfiguration();
$emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
$qb = $this->createQueryBuilder('f');
$qb->select('SUM(f.montantTtc)');
$qb->from('factureBundle:Facture', 'f');
$qb->where('f.client = :id_client');
$qb->groupBy('YEAR(f.dateEdition)');
$qb->setParameter('id_client', $id_client);
$factures_by_years=$qb->getQuery()->getResult();
plz help me
here is the topic :
https://simukti.net/blog/2012/04/05/how-to-select-year-month-day-in-doctrine2.html
and this is the code :
<?php
// .........
// Doctrine2 repository class for entity 'Post'
// .........
public function findOneByYearMonthDay($year, $month, $day)
{
$emConfig = $this->getEntityManager()->getConfiguration();
$emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
$emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\Query\Mysql\Month');
$emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\Query\Mysql\Day');
$qb = $this->createQueryBuilder('p');
$qb->select('p')
->where('YEAR(p.postDate) = :year')
->andWhere('MONTH(p.postDate) = :month')
->andWhere('DAY(p.postDate) = :day');
$qb->setParameter('year', $year)
->setParameter('month', $month)
->setParameter('day', $day);
$post = $qb->getQuery()->getSingleResult();
return $post;
}

Categories