0
votes

I need a clean solution to set data after submit a page from being populated by :

$form->loadDataFrom( $Page );

There is my code :

public function FormUpdate() {

    $error="Required";

    $fields = new FieldList(
        TextField::create('Title', 'Title')->setCustomValidationMessage($error),
        TextField::create('Description', 'Description')->setCustomValidationMessage($error),
        TextField::create('Subject', 'Description')->setCustomValidationMessage($error),
    );

    $actions = new FieldList(
        FormAction::create("FormUpdateSubmit")->setTitle('Update')
    );

    $Page=Versioned::get_by_stage('Page', 'Live')->filter( array('SecureCode' => $_REQUEST['id'] ))->First();

    $fields->push( HiddenField::create('id','SecureCode', $Page->SecureCode ));
    $fields->push( CheckboxField::create('Approbation', "Approbation")->setCustomValidationMessage($error) );  ),

    $required = new RequiredFields(array(
        'Title','Subject','Description'
    ));

    $form = new Form($this, 'FormModifier', $fields, $actions, $required);

    $form->loadDataFrom( $Page );
    $form->setAttribute('novalidate', 'novalidate');

    return $form;

}

The problem... If I change Title and Description and I empty Subject field, i'm redirected back to the form page with the error message below Subject but, All fields are reloaded from $form->loadDataFrom($Page); That wasn't good. I must prevent that data to be reloaded. In this case, datas posted must replace $Page. What I have missing?

2

2 Answers

1
votes

I generally use loadDataFrom on the action that called the form (rather than inside the form function). So for example:

... 
public function index()
{
    $form =$this->Form();
    $form->loadDataFrom($this);

    $this->customise(array("Form" => $form));

    return $this->renderWith("Page");
}

...

That way the function only returns the base form and you alter it as and when required.

0
votes

Your form will be called once when adding it in the template, and once via request. Since all actions on a controller get the request as parameter, you can modify your form function like so:

public function FormUpdate($request = null) {

Then inside your function, only populate the form if it's not called via a request, eg.

if (!$request) {
    $form->loadDataFrom($Page);
}