$ form-> isValid()在Symfony3.4中首次提交后始终返回false

时间:2018-06-22 04:59:45

标签: symfony symfony-forms

以下是将生成的控制器的代码:

  1. 如果未提及则输入工作代码的表格。
  2. 生成用于在工作卡中输入值的表单(如果存在工作代码)。
  3. 提交2中提到的表格后,将Jobcard生成为PDF。

问题:第一次提交表单(在2中提到)时,控制器将按预期工作。但是问题从那以后开始。上述提交的表格如下:

  1. $ form_jobcard-> isSubmitted()为true。
  2. $ form_jobcard-> isValid()为假。

`

use AppBundle\Entity\Job;
use AppBundle\Entity\ActivityLog;
use AppBundle\Entity\Complaint;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DocumentController extends Controller
{
    /**
     * @Route("/admin/jobcard/{jobcode}", name="jobcard", defaults={"jobcode" = null})
     */
    public function generateJobCardAction($jobcode, Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        if($jobcode === null){
            $form_jc = $this->createFormBuilder()
            ->setAction($this->generateUrl('jobcard'))
            ->setMethod('POST')
            ->add('JobCode', TextType::class)
            ->add('submit', SubmitType::class, [
              'label' => 'Submit'
            ])
            ->getForm();
            $form_jc->handleRequest($request);
            if ($form_jc->isSubmitted() && $form_jc->isValid()) {
                $errors = 0;
                if (!isset($form_jc->getData()["JobCode"]) 
                        || $form_jc->getData()["JobCode"] === "" 
                        || 1 !== preg_match('/^[0-9]{6}-[SCREWTH]$/', strtoupper($form_jc->getData()["JobCode"]))){
                    $errors++;
                    $form_jc->addError(new FormError("Invalid JobCode.")); //Jobcode pattern doesn't match.
                } else if (1 == preg_match('/^[0-9]{6}-[SCREWTH]$/', strtoupper($form_jc->getData()["JobCode"]))){
                    $jcode = strtoupper($form_jc->getData()["JobCode"]);
                    $job = $em->getRepository(Job::class)->findOneBy(array('complaint' => (int)$jcode, 'section' => substr($jcode, 7, 1)));
                    if ($job == NULL){
                        $errors++;
                        $form_jc->addError(new FormError("Invalid JobCode.")); //Job doesn't exist.
                    }
                }
                if (!$errors){
                    return $this->redirectToRoute('jobcard', array("jobcode" => $form_jc->getData()["JobCode"]));
                }
            }
            return $this->render('document/jobcard.html.twig', array("formJobCode" => $form_jc->createView()));
        }
        $jcode = strtoupper($jobcode);
        $job = $em->getRepository(Job::class)->findOneBy(array('complaint' => (int)$jcode, 'section' => substr($jcode, 7, 1)));
        $act = $em->getRepository(ActivityLog::class)->createQueryBuilder('a')
                ->where('a.job = :jobid')
                ->setParameter('jobid', $job->getId())
                ->andWhere('a.activityDesc LIKE :activity')
                ->setParameter('activity', '%Jobcard Generated%')
                ->getQuery()
                ->getResult();
        $complaint = $em->getRepository(Complaint::class)->findOneBy(array('id' => (int)$jcode));
        $timestamp = (json_decode($complaint->getDatetimeIpJson()))->timestamp;
        $refDate_timestamp = time();
        $location = $complaint->getLocation();
        if(count($act) == 0){
            //if(!isset($jobcardformparams)){$jobcardformparams = null;}
            $form_jobcard = $this->createFormBuilder() //$jobcardformparams, array('allow_extra_fields' => true))
            ->setAction($this->generateUrl('jobcard',array('jobcode'=> $jcode)))
            ->setMethod('POST')
            ->add('JobReference', TextType::class)
            ->add('Location', TextType::class, array(
                'data' => $location
               ))
            ->add('JobDescription', TextareaType::class)
            ->add('submit', SubmitType::class, [
              'label' => 'Submit'
            ])
            ->getForm();
            $form_jobcard->handleRequest($request);
            if ($form_jobcard->isSubmitted() && $form_jobcard->isValid()) {
                $errors = 0;
                if (!isset($form_jobcard->getData()["JobReference"]) || $form_jobcard->getData()["JobReference"] === ""){$errors++;$form->addError(new FormError("Invalid Job Reference No."));}
                if (!isset($form_jobcard->getData()["Location"]) || $form_jobcard->getData()["Location"] === ""){$errors++;$form->addError(new FormError("Invalid Location."));}
                if (!isset($form_jobcard->getData()["JobDescription"]) || $form_jobcard->getData()["JobDescription"] === ""){$errors++;$form->addError(new FormError("Invalid Job Description."));}
                if (!$errors){
                    $jobcardParamArray = array(
                        "JobReference" => $form_jobcard->getData()["JobReference"],
                        "ReferenceDate" => date('d.m.Y', $refDate_timestamp),
                        "ComplaintDate" => date('d.m.Y', $timestamp),
                        "Location" => $form_jobcard->getData()["Location"],
                        "JobDescription" => $form_jobcard->getData()["JobDescription"]
                    );
                    $jobcardParamArray = json_encode(array("activity" => "Jobcard Generated", "document_data" => $jobcardParamArray));
                    $thejob = $em->getRepository(Job::class)->findOneBy(array('id' => $jcode));
                    $activityLogEntry = new ActivityLog();
                    $activityLogEntry->setJob($thejob);
                    $activityLogEntry->setTimestamp(new \DateTime());
                    $activityLogEntry->setUser($this->getUser());
                    $activityLogEntry->setActivityDesc($jobcardParamArray);
                    $em->clear();
                    $em->merge($activityLogEntry);
                    $em->flush();
                    return $this->redirect($this->generateUrl('jobcard',array('jobcode'=> $jcode)));
                }
            }
            return $this->render('document/jobcard.html.twig', array("formJobCard" => $form_jobcard->createView(), "ComplaintDate" => date('d.m.Y', $timestamp)));
        } else {
            //var_dump(json_decode($act[0]->getActivityDesc(),true));exit();
            $doc_html = $this->renderView('document/jobcard.html.twig', array('jobcardParam' => json_decode($act[0]->getActivityDesc(),true)));
        return new PdfResponse(
            $this->get('knp_snappy.pdf')->getOutputFromHtml($doc_html),
            'jobid-'.$jobcode.'.pdf'
        );
        }
    }
}

1 个答案:

答案 0 :(得分:0)

始终将实体提供给createFormBuilder

$job = new Job();
$form = $this->createFormBuilder($job)
        // You code
        ->getForm();

检查:https://symfony.com/doc/current/forms.html#building-the-form