Hello, I’m new to Yii and maybe I’m missing something there.
Let’s say I have a basic table called videos with ID_video and video_url as fields. As a single model instance I would like to validate inputs, let’s say that video_url is required and I want to apply a url type validator. That’s fine and ok with normal rules() function in the model.
public function rules() {
return array(
array('video_url', 'required'),
array('video_url', 'length', 'max'=>200),
array('ID_video, video_url', 'safe', 'on'=>'search'),
);
}
I would like to create a controller action to let users input in a single form 5 video links. In this specific scenario I would only need that at least one of the 5 inputs apply to the rules. If the other 4 are blank that’s fine by me.
I followed a wiki page that describe how to do tabular inputs and as long as the validation pass (all the 5 inputs are entered and correct) it works beautifully, I can do insert, update and deletes in a single step.
public function actionBatchUpdate($id)
{
// LOGIC TO HANDLE $items array
//
if(isset($_POST['Videos']))
{
$valid=true;
foreach($items as $i=>$item)
{
if(isset($_POST['Videos'][$i]))
{
$item->attributes=$_POST['Videos'][$i];
}
$valid=$item->validate() && $valid;
//echo $item->scenario;
}
if($valid) {
foreach($items as $i=>$item)
{
if ($item->attributes["ID_video"])
{
// Caso di update o cancellazione
if ($item->attributes["video_url"])
{
$item->isNewRecord = false;
$item->save(false);
}
else
$item->delete();
}
else
{
$item->isNewRecord = true;
$item->save(false);
}
}
$this->redirect(array('index'));
}
}
// displays the view to collect tabular input
$this->render('batchUpdate',array('items'=>$items));
}
But still I cannot figure out how I can define a global validation that stick to the scenario above. From what I understand validation applies to a single instance of a model. Also if I declare the input as safe in a custom scenario (‘batchUpdate’) and declare my $item instances with this scenario, still the validation rules belonging to this scenario aren’t taken into account.
I have to do a manual validation in my controller and set $valid to true if at least one of the input is ok?