为什么多个场景在Yii中不起作用?

时间:2014-04-25 08:45:11

标签: php yii scenarios

我在我的应用程序中使用了多个场景,但遇到的问题是每次最后一个场景都会覆盖第一个场景。


型号:

public function rules()
{
    return array(
      [...]
      array('cost_spares', 'cost_spare_func', 'match',
        'pattern' => '/^[a-zA-Z]+$/',
        'message' => 'Do not enter zero or/and characters for Spare parts!',
        'on' => 'cost_spare_func'),
      array('cost_labour', 'cost_labour_func', 'match',
        'pattern' => '/^[a-zA-Z]+$/',
        'message' => 'Do not enter zero or/and characters for Labour Charges!',
        'on' => 'cost_labour_func'),
    );
}

控制器:

public function actionUpdate ($id)
{ 
  if (isset($_POST['TblEnquiry']))
  {
     [...]
     $model->setScenario('cost_spare_func');
     $model->setScenario('cost_labour_func');
  }
}

1 个答案:

答案 0 :(得分:9)

关于documents

  

首先,请务必注意,未分配方案的任何规则都将应用于所有方案。

所以我认为你可能不需要一个场景,只需使用通用规则/验证。

您的规则有一个这样的场景:

public function rules()
{
    return array(
      [...]
      array('cost_spares','numerical',
        'integerOnly' => true,
        'min' => 1,
        'max' => 250,
        'tooSmall' => 'You must order at least 1 piece',
        'tooBig' => 'You cannot order more than 250 pieces at once',
        'message' => 'Do not enter zero or/and characters for Spare parts!',
        'on' => 'myScenario'),
      array('cost_labour','numerical',
        'integerOnly' => true,
        'min' => 1,
        'max' => 250,
        'tooSmall' => 'You must order at least 1 piece',
        'tooBig' => 'You cannot order more than 250 pieces at once',
        'message' => 'Do not enter zero or/and characters for Labour Charges!',
        'on' => 'myScenario'),
    );
}

在您的控制器中,您只需写下:

public function actionUpdate ($id)
{ 
  if (isset($_POST['TblEnquiry']))
  {
     [...]
     $model->setScenario('myScenario');
  }
}

修改
关于this document,我只看到您只想输入numerical。所以这可能更适合您的需求。由于两者都进行了相同的检查,您可以只进行一次检查并稍后将消息传递给它。但就目前而言,这应该有效。

<强>附加
你写的规则中还有另一个错误。

  array('cost_spares', 'cost_spare_func', 'match',
    'pattern' => '/^[a-zA-Z]+$/',
    'message' => 'Do not enter zero or/and characters for Spare parts!',
    'on' => 'cost_spare_func'),

这是不可能的。您不能混合使用规则验证功能和match等默认验证。

这意味着您只能定义validation function,如下所示:

  array('cost_spares', 'cost_spare_func',
    'message' => 'Do not enter zero or/and characters for Spare parts!',
    'on' => 'cost_spare_func'),

OR 使用如下默认验证:

  array('cost_spares', 'match',
    'pattern' => '/^[a-zA-Z]+$/',
    'message' => 'Do not enter zero or/and characters for Spare parts!',
    'on' => 'cost_spare_func'),