Search code examples
phpsymfony1

How do I make a form field not neccessray for validation in Symfony?


I have 2 forms: $patientForm and $investigationForm.

They are both combined into one view, so the user fills in the fields and 2 records are created in Patient table and Investigation table. Investigation table has a foreign key - to the patient name. So one patient can have many investigations.

So I obviously need the patient id to add it to an investigation record as a foreign key. However, the patient id isn't created until the patient form is saved.

So I have devised the following function:

protected function processPatientInvestigation(sfWebRequest $request, sfForm $investigationForm, sfForm $patientForm)
{
    $patientForm->bind($request->getParameter($patientForm->getName()), $request->getFiles($patientForm->getName()));

    if ($patientForm->isValid() && $investigationForm->isValid() ) {        
        $patientForm->save();       
        $values = $request->getParameter($investigationForm->getName());
        $values['patient_id'] = $patientForm->getObject()->getId();
        $investigationForm->bind($values, $request->getFiles($investigationForm->getName()));
        $investigationForm->save();     
    }

The if statement always fails because $investigationForm isn't valid until I give its form field a patient_id value. So this value is empty at this point. However, if I just took the isValid() check out for $investigation form and put it down later on after the $patientForm is saved. This means that if it failed validation and the user had missed a field, when they don't click submit again, the whole function would run again meaning we'd have duplicate patient records.

So what I think the answer is, is making the patient_id field not be validated, so it can be empty and still pass the isValid() function.

Please let me know if this isn't clear. Hope you can advise!


Solution

  • Try the following though this should really be done in the forms configure method.

    $patientForm->getValidator('patient_id')->addOption('required', false);