Now the next question:
How can I validate the nested objects (Location and LocationBrands) in actionUpdate and in actionCreate, without having the code in two places?
What I want to do,is the following:
-
First should be the "Location" be validated
-
if data for "Location" is valid, the data for "LocationBrand" should be validated
public function actionUpdate()
{
$location = $this->loadLocation();
$booValid = true;
if (isset($_POST['Location']))
{
$location->attributes = $_POST['Location'];
$booValid = $location->validate();
if (isset($_POST['LocationBrand'])) {
$arrLocationBrand = array();
foreach ($_POST['LocationBrand'] as $i => $arrItem) {
if (intVal($arrItem['idBrand']) > 0)
{
$objLocationBrand = new LocationBrand();
$objLocationBrand->idLocation = $location->id;
$objLocationBrand->idBrand = $arrItem['idBrand'];
$objLocationBrand->strUrl = $arrItem['strUrl'];
$booValid = $objLocationBrand->validate() && $booValid;
array_push($arrLocationBrand, $objLocationBrand);
}
}
}
if ($booValid && $location->save())
{
Yii::app()->db->createCommand('DELETE FROM LocationBrand WHERE idLocation='.$location->id)->execute();
foreach ($arrLocationBrand as $i => $arrItem) {
$arrItem->save();
}
}
}
else {
$arrLocationBrand = $location->arrLocationBrand;
}
$this->render('update', array('location' => $location, 'locationBrand' => $arrLocationBrand));
}
this works, but now I have to put the same code into actionCreate. Is there another way for doing this?
EDIT:
I've tried to move validation an saving of LocationBrand into "afterSave" method, of "Location" model so the code could be used by "actionCreate" and "actionUpdate", but if I do this, I can't show errors accoured in "LocationBrand" in the form, because "afterSave" only returns true or false, and not the models of "LocationBrand" 