Claire
Claire

Reputation: 3773

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!

Upvotes: 0

Views: 142

Answers (3)

Dziamid
Dziamid

Reputation: 11571

I'd go with embedded forms and let symfony handle the saving correctly.

Upvotes: 0

Burgi
Burgi

Reputation: 1382

The cleaner solution would be to set all your validation rules in the /lib/form/*Form.class.php file itself (rather than manipulating it in your action).

$this->validatorSchema['patient_id'] = new sf*Validator(array(
  'required' => false
), array());

If you just want to let a form field completely unvalidated, use

$this->validatorSchema['patient_id'] = sfValidatorPass()

Upvotes: 1

SnatchFrigate
SnatchFrigate

Reputation: 372

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

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

Upvotes: 2

Related Questions