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

Kap*_*pur 3 php scenarios yii

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


模型:

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'),
    );
}
Run Code Online (Sandbox Code Playgroud)

控制器:

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

Jur*_*rik 9

关于文件:

首先,需要注意的是,未分配方案的任何规则都将应用于所有方案.

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

要么

您有这样的规则的一个方案,如下所示:

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'),
    );
}
Run Code Online (Sandbox Code Playgroud)

在你的控制器中你只需写:

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

编辑:
关于这个文档,我只是看到你只想要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'),
Run Code Online (Sandbox Code Playgroud)

这是不可能的.您不能混合规则验证功能和默认验证match.

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

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

使用这样的默认验证:

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