Domanda

I have a form which has multiple actions e.g. Create Order & Create Quote.

Depending on what action is clicked I need to apply different validation. e.g. Order Ref is not required for a quote.

Is this possible within Silverstripe? If not how would I got about it?

public function Order($request=null) {
 $form = Form::create(
    $this,
    __FUNCTION__,
    FieldList::create(
        TextField::create('Name', 'Your Full Name'),
    TextField::create('OrderRef', 'Purchase Order #')
    ),
    FieldList::create(
        LiteralField::create('Cancel', '<a class="cancel button alert">Don\'t save</a>'),
        FormAction::create('saveQuote', 'Save Quote'),
        FormAction::create('saveOrder', 'Save Order')->addExtraClass('success')
    ),
    RequiredFields::create('Name', 'OrderRef')
);

return $form;
}
È stato utile?

Soluzione

To do this, you will probably need to create a custom RequiredFields subclass to conditionally set which fields are required:

class CustomValidator extends RequiredFields {
    public function php($data) {
        if($this->form->buttonClicked()->actionName() == 'saveQuote') {
            $this->addRequiredField('FieldName'); // ...
        } else {
            $this->addRequiredField('OtherFieldName'); // ...
        }

        return parent::php($data);
    }
}

You then use this in your form like:

$form = new Form(
    $this, 'FormName', $fields, $actions, new CustomValidator()
);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top