StefGuev
StefGuev

Reputation: 649

Silverstripe form image validation after submit failed

I have a little problem to handle the validate of an image after a form submit. There is my form submit function :

public function FormAjouterSubmit($data, $form) {

    ....

    Session::clear("PageAuteur.FormAjouterSubmit");

    $texte = "Veuillez remplir ce champ";

    if (!$data['ImageID']) {
        Session::set("PageAuteur. FormAjouterSubmit", $data);
        $form->addErrorMessage('Image', $texte, 'bad');
        return $this->redirectBack();
    }   

    ....

}

I have tried !$data['ImageID'] and !$data['Image'] and the form return back and clear my session data. What i'm doing wrong?

Upvotes: 0

Views: 139

Answers (1)

bummzack
bummzack

Reputation: 5875

You can use RequiredFields to validate required form-fields. The Form constructor takes a fifth parameter, where you can supply the required fields validator.

Example:

$form = Form::create(
    $this, 
    'FormAjouter', 
     $fields, 
     $actions, 
     RequiredFields::create(['Image'])
);

The easiest way to customize the validation message is to use i18n. If your default locale is french, crate a file named mysite/lang/fr.yml where you can put something like this:

Form:
  FIELDISREQUIRED: 'Veuillez remplir le champ {name}'

{name} will be substituted with your actual field title. Of course you can also omit the placeholder.

If you need different text for individual form-fields, you can use setCustomValidationMessage on each field that requires a custom error message.

Example:

$uploadField = FileField::create('Image');
$uploadField->setCustomValidationMessage('Please upload a file');

Upvotes: 1

Related Questions