Silverstripe 3 - Disable field validation for CMS delete operations only

时间:2019-01-09 21:50:06

标签: silverstripe

I have a custom field type that contains a small validator. It is used all over the place on the Frontend, so for convenience we also use it in the CMS.

class MyTextField extends TextField {

    public function Type() {
        return 'text';
    }

    public function getAttributes() {
        return array_merge(
                parent::getAttributes(),
                array(
                        'type' => 'text'
                )
        );
    }
    public function validate($validator) {
        $this->value = trim($this->value);
        $maxLength = empty($this->getMaxLength())?50:$this->getMaxLength();

       if(strlen($this->value)>$maxLength) {
            $validator->validationError(
                    $this->name,
                    'Exceeded max length '.$maxLength,
                    "validation"
            );
            return false;

        }else{
                return true;
            }
        }

    }
}

Field works fine. If a create a new instance using it, and that constructor doesn't include a maxlength property, it defaults to 50.

The issue I am having is that a change to a frontend field "MyText" was set to 100, while the version of this field in getCMSFields was not, and thus defaulted to a max length of 50. Obviously validation failure.

Of course this should and has been rectified, but the issue came up as a CMS user could not delete a record. And I don't really disagree with the user in that validation should be ignored when you discarding the data anyway. It would make sense for add/edit, but not really delete.

Anyone know of a way of disabling validation for a delete operation inside getCMSFields? Here is an excerpt of my getCMSFields in case a refactor is required.

function getCMSFields() {

    $detailBlock = CompositeField::create(
        MyTextField::create('MyTextField','CustomField', '', 255),
    );

    // Build the fieldlist for the form.
    $fields = FieldList::create (
            TabSet::create (
                    "Root",
                    Tab::create (
                            "Main Content",
                            $detailBlock
                    )
            )
    );

    return $fields;
}

EDIT: I have just discovered that I need a way to bypass getCMSValidator for delete operations too. There are required fields set in here that can trigger a validation error on delete too. It doesn't really make sense that you would need to put a record in a valid state just to delete it.

0 个答案:

没有答案