验证扩展字段UserDefinedForm

时间:2015-01-17 11:42:11

标签: silverstripe

我在UserDefinedForm(模块用户表单)上进行了扩展。这很好用,但我无法弄清楚如何在这个额外的字段上设置验证。这是我的代码(的一部分):

class UserDefinedPaymentForm_Controller extends UserDefinedForm_Controller {
    private static $allowed_actions = array(
        "finished",
        "complete",
        "error"
    );

    public function getFormFields() {
        //Payment fields
        $supported_methods = PaymentProcessor::get_supported_methods();

        $gateways = array();
        foreach ($supported_methods as $methodName) {
            $methodConfig = PaymentFactory::get_factory_config($methodName);
            $gateways[$methodName] = $methodConfig['title'];
        }


        $fields = parent::getFormFields();

        $fields->add(new NumericField("PaymentAmount", _t('UserDefinedPaymentForm.PAYMENT_AMOUNT', 'Payment Amount')));
        $fields->add(new Literalfield("literalfield", _t('UserDefinedPaymentForm.PAY', '<h2>Pay</h2>')));
        $fields->add(new Literalfield("literalfield", _t('UserDefinedPaymentForm.PAY_INSTRUCTIONS', '<p>Choose your prefered payment method and click Pay:</p>')));
        $fields->add(new DropdownField("PaymentMethod", _t('UserDefinedPaymentForm.PAYMENT_METHOD', 'Payment Method'), $gateways));

        return $fields;
    }
}

现在我要验证字段PaymentAmount,此字段的值必须为2或更多。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

我猜(我还没有测试过)你最好的办法是创建一个UserFormValidator的子类并覆盖php($data)方法。 然后,在UserDefinedPaymentForm_Controller中,您还需要覆盖Form方法。

class PaymentAmountUserFormValidator extends UserFormValidator {

    public function php($data) {
        $result = parent::php($data);
        if ($result === true) {
             // verify your PaymentAmount here and return true or false, accordingly
        }
        return $result;
    }
class UserDefinedPaymentForm_Controller {
 ... 
    public function Form()
    {
        $form = UserForm::create($this);

        // Generate required field validator
        $requiredNames = $this
            ->getController()
            ->Fields()
            ->filter('Required', true)
            ->column('Name');

        $validator = new PaymentAmountUserFormValidator($requiredNames);
        $form->setValidator($validator);
        $this->generateConditionalJavascript();
        return $form;
    }

...

}