Yii:管理员无法从管理面板更新内容

时间:2016-01-03 07:53:33

标签: php yii

我是一个Yiibie,我遇到一个问题,当管理员试图更新Ngo的个人资料时,它只是没有得到更新,当进行更改并且提交按下它进入视图文件但不显示更新。请帮我解决一下这个。这是我的NgoController

的代码
   <?php

class NgoController extends RController
{
    /**
    * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
    * using two-column layout. See 'protected/views/layouts/column2.php'.
    */
    public $layout='//layouts/admin';
        public $pageOwner;
    /**
    * @return array action filters
    */
    public function filters()
    {
        return array(
//          'accessControl', // perform access control for CRUD operations
//          'postOnly + delete', // we only allow deletion via POST request

                    'rights',
                );
    }

    /**
    * Specifies the access control rules.
    * This method is used by the 'accessControl' filter.
    * @return array access control rules
    */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    /**
    * Displays a particular model.
    * @param integer $id the ID of the model to be displayed
    */
    public function actionView($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }
        public function actionNgopage($id)
    {         
               $this->layout='main';
               $model2=new UserRateReviewNgo();
        $this->render('ngopage',array(
            'model'=>$this->loadModel($id),
                         'reviewmodel'=>$model2// This is for rate and reviewing
        ));
    }
       public function actionAllngo()
{
    $allmodels= Ngo::model()->findAll(array('order'=>'id DESC'));
    $this->layout='main';
    $this->render('allngo',array('allmodels'=>$allmodels));

}
public function actionEditcomment()
{

//               $this->layout='main';            //render main layout
//                $model2=new UserRateReviewNgo();   //new objecct of table ratereviewngo
//              $this->render('editcomment',array(
//          'model'=>$this->loadModel($id),   //model+reviewmodel as a object 
//                  'reviewmodel'=>$model2// This is for rate and reviewing
//                        ));

               //Yahan se hum ne kaam shuru kia he comment wala
              $this->layout='main';
                    $rbmodel=  UserRateReviewNgo::model()->findAll();
                    $u_id = Yii::app()->user->id;
                    $biz_id=$_GET['ngo_id'];
                    $rev_id=$_GET['rbid'];
                  //select rating,review from review_business where user_id=1 and id=6
                  $results = Yii::app()->db->createCommand()
                ->select('r.rate,r.review,r.id,r.user_id')
                ->from('user_rate_review_ngo r')
                ->where('r.user_id='.$u_id) //checking/comparing the current user
                ->andWhere('r.id='.$rev_id)//matching the review here 
                ->queryAll();
              $this->render('editcomment',array(
        "u_id"=>$u_id,"biz_id"=>$biz_id,"results"=>$results,"rev_id"=>$rev_id,"rbmodel"=>$rbmodel,

        )); 
    }  




    /**
    * Creates a new model.
    * If creation is successful, the browser will be redirected to the 'view' page.
    */
    public function actionCreate()
    {
        $model=new Ngo;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Ngo']))
        {
                     $rnd = rand(0,9999);  // generate random number between 0-9999
            $model->attributes=$_POST['Ngo'];
                        $uploadedFile=CUploadedFile::getInstance($model,'image');
            $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
            $model->image = $fileName;
            if($model->save())
                            {
                $uploadedFile->saveAs(Yii::app()->basePath.'/../img/'.$fileName);  // image will uplode to rootDirectory/event/
                $this->redirect(array('admin'));
            }
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
        'model'=>$model,
        ));
    }

/**
 * Updates a particular model.
 * If update is successful, the browser will be redirected to the 'view' page.
 * @param integer $id the ID of the model to be updated
 */
public function actionUpdate($id)
{
    $this->layout='owner';
    $model=$this->loadModel($id);
    $claimed=1;                      
    $current_user=YII::app()->user->id;
    $results = Yii::app()->db->createCommand()
       ->select('b.user_id,b.ngo_id,b.claimed')
       ->from('claimed_ngo b')
       ->where('b.user_id='.$current_user) 
       ->andWhere('b.claimed='.$claimed)
        ->queryALL();

    if(isset($_POST['Ngo'])) {
       $_POST['NGO']['image'] = $model->image;
       $model->attributes=$_POST['NGO'];
       $uploadedFile=CUploadedFile::getInstance($model,'image');
       $fileName = "{$uploadedFile}";  
       $model->image = $fileName;           
       if($model->save()) {
            if(!empty($uploadedFile)) {
                uploadedFile->saveAs(Yii::app()->basePath.'/../img/'.$model->image);
            }
            $this->redirect(array('admin'));
        }
        $this->redirect(array('view','id'=>$model->id));
    }           
    if($results=='') {     
        $this->pageOwner=$results[0]['ngo_id'];                   
        $this->render('update',array('model'=>$model, 'results'=>$results));           
    } else { 
       $this->pageOwner=$id;
       $this->render('update',array('model'=>$model, 'results'=>$results));
    }
}

    /**
    * Deletes a particular model.
    * If deletion is successful, the browser will be redirected to the 'admin' page.
    * @param integer $id the ID of the model to be deleted
    */
    public function actionDelete($id)
{
    if(Yii::app()->request->isPostRequest)
    {
        // we only allow deletion via POST request
        $modelUserNgo = ClaimedNgo::model()->findAllByAttributes( array('ngo_id'=>$id));
        if (isset($modelUserNgo))
            {
            foreach($modelUserNgo as $child)
                {
                $child->delete();
            }
        }
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

    }  
    else
        throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');


}


    /**
    * Lists all models.
    */
    public function actionIndex()
    {
        $dataProvider=new CActiveDataProvider('Ngo');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
    * Manages all models.
    */
    public function actionAdmin()
    {
        $model=new Ngo('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Ngo']))
            $model->attributes=$_GET['Ngo'];

        $this->render('admin',array(
            'model'=>$model,
        ));
    }

    /**
    * Returns the data model based on the primary key given in the GET variable.
    * If the data model is not found, an HTTP exception will be raised.
    * @param integer $id the ID of the model to be loaded
    * @return Ngo the loaded model
    * @throws CHttpException
    */
    public function loadModel($id)
    {
        $model=Ngo::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
    * Performs the AJAX validation.
    * @param Ngo $model the model to be validated
    */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='ngo-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}

这是视图文件(_form.php)

<?php
/* @var $this NgoController */
/* @var $model Ngo */
/* @var $form BSActiveForm */
?>

<?php $form=$this->beginWidget('bootstrap.widgets.BsActiveForm', array(
    'id'=>'ngo-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation'=>false,
    'htmlOptions' => array(
        'enctype' => 'multipart/form-data',
    ),
)); ?>

    <p class="help-block">Fields with <span class="required">*</span> are required.</p>

    <?php echo $form->errorSummary($model); ?>

    <?php echo $form->textFieldControlGroup($model,'ngo_name',array('maxlength'=>45)); ?>
    <?php echo $form->textFieldControlGroup($model,'email',array('maxlength'=>45)); ?>
    <?php echo $form->textFieldControlGroup($model,'address',array('maxlength'=>100)); ?>
    <?php //echo $form->textFieldControlGroup($model,'image',array('maxlength'=>45)); ?>
     <div class="row">
        <?php echo $form->labelEx($model,'image'); ?>
        <?php echo CHtml::activeFileField($model, 'image'); ?>  <!--by this we can upload image-->
        <?php echo $form->error($model,'image'); ?>
</div>
    <?php if($model->isNewRecord!='1') ?>
    <div class="row">
     <?php echo CHtml::image(Yii::app()->request->baseUrl.'/img/'.$model->image,"image",array("width"=>200)); ?>  <!--Image shown here if page is update page-->
</div>
    <br>
    <?php echo $form->textFieldControlGroup($model,'requirement',array('maxlength'=>200)); ?>

    <?php echo BsHtml::submitButton('Submit', array('color' => BsHtml::BUTTON_COLOR_PRIMARY)); ?>

<?php $this->endWidget(); ?>

这是Ngo model

<?php

/**
 * This is the model class for table "ngo".
 *
 * The followings are the available columns in table 'ngo':
 * @property integer $id
 * @property string $ngo_name
 * @property string $email
 * @property string $address
 * @property string $image
 * @property string $requirement
 *
 * The followings are the available model relations:
 * @property ClaimedNgo[] $claimedNgos
 * @property UserRateReviewNgo[] $userRateReviewNgos
 */
class Ngo extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Ngo the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'ngo';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('ngo_name, email, address, image, requirement', 'required'),
            array('ngo_name, email, image', 'length', 'max'=>45),
            array('address', 'length', 'max'=>100),
            array('requirement', 'length', 'max'=>500),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, ngo_name, email, address, image, requirement', 'safe', 'on'=>'search'),
                array('image', 'length', 'max'=>255, 'on'=>'insert,update'),
                    );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'claimedNgos' => array(self::HAS_MANY, 'ClaimedNgo', 'ngo_id'),
            'userRateReviewNgos' => array(self::HAS_MANY, 'UserRateReviewNgo', 'ngo_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'ngo_name' => 'Ngo Name',
            'email' => 'Email',
            'address' => 'Address',
            'image' => 'Image',
            'requirement' => 'Requirement',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('ngo_name',$this->ngo_name,true);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('address',$this->address,true);
        $criteria->compare('image',$this->image,true);
        $criteria->compare('requirement',$this->requirement,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }
}

2 个答案:

答案 0 :(得分:1)

如果您重定向到查看但更新的值未保存,则表示保存操作中的某些内容不起作用

您可以尝试(仅用于调试)以使用

 if($model->save(false)) {

以这种方式,您可以看到是否未经验证,模型已保存,程序将重定向到管理员。

像@fal建议你可以正确检查$ modelgetErrors(),例如

var_dump($model->getErrors());  //for evaluate the eventual error 

如果问题是这(与验证有关),则提供正确的验证或正确的值。

答案 1 :(得分:0)

尝试在Controller中检查$ model-&gt; save()或$ model-&gt; getErrors()的结果。希望这会有所帮助:)