コード例 #1
0
 public function actionProfile()
 {
     YiiBase::beginProfile(1);
     Yii::app()->user->setFlash('infomsg', "You now editing profile");
     $model = TblProfile::model()->with('photos')->findByAttributes(array('user_id' => Yii::app()->user->getId()));
     if (!$model) {
         $model = new TblProfile();
     }
     $model->setScenario('create');
     MyClass::dump($model);
     $img_add = new TblProfilePhotos();
     // uncomment the following code to enable ajax-based validation
     if (isset($_POST['ajax']) && $_POST['ajax'] === 'tbl-profile-profile-form') {
         $model->setScenario('ajax');
         echo CActiveForm::validate($model);
         Yii::app()->end();
     } elseif (isset($_POST['TblProfile'])) {
         //MyClass::dump($_FILES); exit();
         $model->attributes = $_POST['TblProfile'];
         $model->setAttribute('user_id', Yii::app()->user->getId());
         if ($model->validate()) {
             // form inputs are valid, do something here
             $model->save();
         }
         if ($_FILES['images']) {
             $images = CUploadedFile::getInstancesByName('images');
             foreach ($images as $img => $pic) {
                 if ($pic->saveAs(Yii::getPathOfAlias('webroot') . '/assets/files/' . $pic->name)) {
                     $img_add = new TblProfilePhotos();
                     $img_add->setAttribute('image', $pic);
                     $img_add->setAttribute('name', $pic->name);
                     //it might be $img_add->name for you, filename is just what I chose to call it in my model
                     $img_add->setAttribute('profile_id', $model->id);
                     // this links your picture model to the main model (like your user, or profile model)
                     if ($img_add->validate()) {
                         $img_add->save();
                         // DONE
                     } else {
                         break;
                     }
                 }
             }
             /* вариант напрямик
                $builder=Yii::app()->db->schema->commandBuilder;
                $command=$builder->createMultipleInsertCommand('tbl_user_photos',
                    array_map(function($arr){
                        return array('name' => $arr, 'profile_id' => $model->attributes->id);
                    }, $_FILES['TblProfile']['name']['photos'])
                );
                $command->execute();
                */
         }
     }
     YiiBase::endProfile(1);
     $this->render('profile', array('model' => $model, 'photosModel' => isset($img_add) ? $img_add : null));
 }