Hello,
I have made a nested form using the method 'embedRelation'. In a main form I have twelve child forms.
EDIT :
$subForm = new sfForm();
for ($i = 0; $i < 12; $i++){
$enfant = new Enfant();
$enfant->Locataire = $this->getObject();
$form = new EnfantForm($enfant);
$subForm->embedForm($i, $form);
}
$this->embedForm('newEnfant', $subForm);
I want make a post validator to ignore the childs not filled.
But my validator does nothing : all the childs are saved in the database.
I have put the validator in lib/validator/sfValidatorEnfants.class.php
class sfValidatorEnfants extends sfValidatorBase {
protected function configure($options = array(), $messages = array()) {
$this->addMessage('sexe', 'Le sexe est requis.');
$this->addMessage('datenaissance', 'La date de naissance est requise.');
}
protected function doClean($values) {
$errorSchema = new sfValidatorErrorSchema($this);
foreach($values as $key => $value) {
$errorSchemaLocal = new sfValidatorErrorSchema($this);
// La date de naissance est renseignée mais pas le sexe
if (!$value['sexe'] && $value['datenaissance']) {
$errorSchemaLocal->addError(new sfValidatorError($this, 'required'), 'sexe');
}
// Le sexe est renseigné mais pas la date de naissance
if ($value['sexe'] && !$value['datenaissance']) {
$errorSchemaLocal->addError(new sfValidatorError($this, 'required'), 'datenaissance');
}
// Pas de sexe ni de date de naissance renseigné, suppression des valeurs vides
if (!$value['sexe'] || !$value['datenaissance'] || empty($value['datenaissance']) || empty($value['sexe'])) {
unset($values[$key]);
}
if (count($errorSchemaLocal)) {
$errorSchema->addError($errorSchemaLocal, (string) $key);
}
}
if (count($errorSchema)) {
throw new sfValidatorErrorSchema($this, $errorSchema);
}
return $values;
}
}
I call it in EnfantForm.class.php (the class of my child forms) :
$this->mergePostValidator(new sfValidatorEnfants());
EDIT :
My method saveEmbeddedForms() :
public function saveEmbeddedForms($con = null, $forms = null) {
if (null === $forms) {
$enfants = $this->getValue('newEnfant');
$forms = $this->embeddedForms;
foreach ($this->embeddedForms['newEnfant'] as $name => $form) {
if (!isset($enfants[$name])) {
unset($forms['newEnfant'][$name]);
}
}
}
return parent::saveEmbeddedForms($con, $forms);
}