Reputation: 654
I have a module named attendance but value in it is comes from other tables with some conditions. so how can i get id of other tables. my code is like below:
models are:
if($type == 2)
{
$model = new Supplier();
}
elseif($type==3)
{
$model = new TruckingCompany();
}
elseif($type==4)
{
$model = new ServiceProvider();
}
elseif($type==5)
{
$model = new Landowner();
}
elseif($type==6)
{
$model = new Refiner();
}
elseif($type==8)
{
$model = new Worker();
}
elseif($type==9)
{
$model = new Trainer();
}
now i want to update this record
array(
'header'=>'Action',
'class' => 'CButtonColumn',
'template'=>'{update}',
'updateButtonUrl'=>'Yii::app()->createUrl("attendance/update", array("id"=>$data->id))',
);
now i want to get id of these diffent table for update record and these are different in all tables. i can get it by below line:
'updateButtonUrl'=> 'Yii::app()->createUrl("attendance/update", array("id"=>$data->supplier_master_id))';
but it is not a proper way to define by these for all tables so what to do in this case... any idea... i am new in yii.
Upvotes: 1
Views: 97
Reputation: 875
In addition to let me see's answer. I would put it in array
form:
$types = array(
1 => array("modelName"=>"Supplier","url"=>'Yii::app()->createUrl("attendance/update", array("id"=>$data->id))'),
2 => array("modelName"=>"TruckingCompany","url"=>'Yii::app()->createUrl("attendance/update", array("id"=>$data->supplier_master_id))'),
);
Of course you can improve on this by dividing the "url" key for example like this:
"url"=>array(
"route"=>"attendance/update",
"params"=>'"id"=>$data->id',
)
This way you can pass it like this:
if(array_key_exists($type,$types)){ //Checks if you've defined the type.
$this->render('view',array(
'updateUrl'=>$types[$type]['url'],
'model'=>new $types[$type]['modelName'](), //Creates your object.
)
);
return; //just to be sure.
}
throw new CHTTPException(404, "Type not Found!");
Your view would look something like this with the improved "url" key:
array(
'header'=>'Action',
'class' => 'CButtonColumn',
'template'=>'{update}',
'updateButtonUrl'=>'Yii::app()->createUrl(' . $updateUrl['route'] . ', array(' . $updateUrl['params'] . '))',
);
This clears up your code a bit and gets rid of the huge if statement/switch.
The createUrl string
is still a bit ugly, so you can improve on that further if you would like.
Upvotes: 1
Reputation: 5094
Why do not you create the URL along with the models like
if($type == 2)
{
$model = new Supplier();
$updateUrl = 'Yii::app()->createUrl("attendance/update", array("id"=>$data->id))';
}
elseif($type==3)
{
$model = new TruckingCompany();
$updateUrl = 'Yii::app()->createUrl("attendance/update", array("id"=>$data->supplier_master_id))';
}
Pass it to the view while rendering
$this->render('view',array('updateUrl'=>$updateUrl));
And then finally use it in view file like
array(
'header'=>'Action',
'class' => 'CButtonColumn',
'template'=>'{update}',
'updateButtonUrl'=>$updateUrl,
);
Upvotes: 2