Search code examples
validationyiiscenarios

how to combine scenarios in yii


I have an form that requires different scenarios based on selections on the form. For example: the user can choose to add a delivery address in a shop that's different from the billing-address (this is simple, in reality, I'll have like 3 or 4 different scenarios).

So, when validating the form, depending on the user's selection, I need to combine two scenarios (the one for the billing address and the one for the delivery address).

How would I combine the two scenarios?


Solution

  • You can't group scenarios the the rules configuration. Instead you create a list of rules one by one.

    You are able to apply more than one scenario to a set of fields.

    For example :

    public function rules()
    {
    
        return array(
            // For purchases, supply the delivery address
            // For registration, supply the postal address
            // For payment, supply the delivery address and postal address
    
            array('delivery_address', 'required', 'on' => array('purchase', 'payment'),
            array('postal_address', 'required', 'on' => array('register', 'payment'),
                     // :
    
        );
    }
    

    You cannot have 'conditional' scenarios. To implemented conditional rules, look at implementing custom validations.

    public function rules()
    {
        return array(
           array('postal_address', 'validateAddresses'),
        );
    }
    
    public function validateAddresses($attribute,$params) {
      if (!$this->deliveryAddressSameAsPostal) {
          if ((empty($this->delivery_address)) {
            $this->addError($attribute, 'Please supply a delivery address!');
          }
      }
    }