/** * Validate data from form post * it's must making before saving into database * @param mixed $postData */ public function validatePortfolio($postData) { $arrayPortfolio = array(); foreach ($_POST['FileForm'] as $gallery_idx => $postPortfolio) { if (empty($postPortfolio['gallery_id'])) { $portfolio = new Portfolio(); } else { $portfolio_id = $postPortfolio['gallery_id']; $portfolio = Portfolio::model()->with('photos')->findByPk($portfolio_id); if (!isset($portfolio)) { $portfolio = new Portfolio(); } } $portfolio->attributes = $postPortfolio; //assign attributes $valOK = $portfolio->validate(); $arrayPhotosIds = array(); //additional array for deleted photos search $deletedPhotos = array(); //array for deleted photos $photos = array(); //array of edited photos of portfolio $isTopPresent = false; //process photos array if (isset($postPortfolio['photos'])) { foreach ($postPortfolio['photos'] as $idx => $postPhoto) { $photo_id = $postPhoto['photo_id']; $isNewPhoto = empty($photo_id); $photo = $isNewPhoto ? new Photo() : Photo::model()->findByPk($photo_id); if ($isNewPhoto = !isset($photo)) { $photo = new Photo(); } $photo->attributes = $postPhoto; $photo->gallery_id = $portfolio->gallery_id; $photo->is_top = isset($postPortfolio['is_top']) && $idx == $postPortfolio['is_top'] ? Photo::POSITION_IS_TOP : Photo::POSITION_NO_TOP; if ($photo->is_top) { $isTopPresent = true; } //mark is_top present $valOK = $photo->validate() && $valOK; $arrayPhotosIds[$idx] = $postPhoto['photo_id']; //add item to search array $photos[$idx] = $photo; } } //validate photos (count) if ($postPortfolio['gallery_type'] == 1) { if (!count($photos)) { $portfolio->addError('is_top', Yii::t('main', 'Portfolio must have photos')); } else { if (!$isTopPresent) { $portfolio->addError('is_top', Yii::t('main', 'In photo portfolio one of photo must be in top')); } } } //search for deleted photos if (isset($portfolio->photos)) { foreach ($portfolio->photos as $photo) { if (!in_array($photo->photo_id, $arrayPhotosIds)) { $portfolio->deletedPhotos[] = $photo; } } } $portfolio->photos = $photos; //add photo items to portfolio model $arrayPortfolio[] = $portfolio; //add instance of portfolio to returning array } return $arrayPortfolio; //returning result array of portfolio instances }