我创建了两个存储库,用于将工资核算周(数据库中已有一周)与工资核算期(用户输入的2周)相匹配。但不断收到错误消息,表示即使匹配也不匹配。工资核算周和工资核算期应完全匹配。
自定义存储库
public function findBystartdateAndenddate($startdate, $enddate)
{
$repository=$this->getEntityManager()->getRepository('comtwclagripayrollBundle:Payrollweek');
//$startdate='startdate';
//$enddate='enddate';
$qb=$repository->createQueryBuilder('pw');
$qb->select('pw');
$qb->where('pw.startdate=:startdate');
$qb->Andwhere('pw.enddate=:enddate');
$qb->setParameter('startdate', $startdate);
$qb->setParameter('enddate', $enddate);
$qb->getquery()->getResult();
}
public function countBystartdateAndenddate($startdate, $enddate)
{
$qb = $this->createQueryBuilder('pw');
$qb->select('count(pw.id)');
$qb->where('pw.startdate=:startdate');
$qb->Andwhere('pw.enddate=:enddate');
$qb->setParameter('startdate', $startdate);
$qb->setParameter('enddate', $enddate);
return $qb->getQuery()->getResult();
}
控制器
public function createAction(Request $request)
{
$entity = new Payrollperiod();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$payrollperiod = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')->findOneBy(['startdate'=>$form->get('startDate')->getData(), 'enddate'=>$form->get('endDate')->getData()]);
$payrollweek = $em->getRepository('comtwclagripayrollBundle:Payrollweek')->findBystartdateAndenddate($entity->getStartDate() , $entity->getEndDate());
$counter = $em->getRepository('comtwclagripayrollBundle:Payrollweek')->countBystartdateAndenddate($entity->getStartDate() , $entity->getEndDate());
if($counter){
//If entity exists
if ($payrollperiod){
$this->addFlash('error', 'Error: A payroll period is already present with the same start and end date.');
return $this->redirect($this->generateUrl('payrollperiod'));
}
//If PayrollWeek matches the Payrollperiod entered
elseif ( $payrollweek){
foreach ($payrollweek as $pWeek) {
$pWeek->setPayrollperiodid($entity);
$em->persist($pWeek);
}
$em->persist($entity);
$em->flush();
$this->addFlash('success', 'Payroll Period was added.');
$this->addFlash('success', 'Payroll week was updated.');
return $this->redirect($this->generateUrl('payrollperiod'));
//return $this->redirect($this->generateUrl('payrollperiod_show', array('payrollperiodid' => $entity->getpayrollperiodid())));
}
else{
$this->addFlash('error', 'Payroll Period does not match a payroll week.');
return $this->redirect($this->generateUrl('payrollperiod'));
}
}
//return $this->render('comtwclagripayrollBundle::new.html.twig',array('form' => $form->createView()));
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
}