1

如何将 Yii 中外部操作的值传递给它的父控制器?

例如:外部动作如下:

<?php
 class uploadAction extends CAction
{
/**
* Runs the action.
* This method is invoked by the controller owning this action.
*/
public function run()
{
    .....

        $fileName=$result['filename'];//GETTING FILE NAME

        $this->controller->image = $fileName; // this line does not work!!  

}
  }

当我尝试在父控制器中获取图像的值时,没有任何返回!任何帮助我都会感激。

更新:我正在使用扩展来上传文件 .. eajaxupload

有很长的形式..有很多领域,其中之一是图像。我想在提交整个表单之前通过 Ajax 上传该图像。当然,在用户单击创建按钮后..控制器必须将所有字段加上图像名称存储在数据库中。风景 ..

<div class="elem">
            <?php echo $form->labelEx($model,'username'); ?>
            <?php echo $form->textField($model,'username',array('class'=>'inputbox grid-11-12','maxlength'=>45)); ?>
            <?php echo $form->error($model,'username'); ?>
        </div>

        <div class="elem">
            <?php echo $form->labelEx($model,'password1'); ?>
            <?php echo $form->passwordField($model,'password1',array('class'=>'inputbox grid-11-12')); ?>
            <?php echo $form->error($model,'password1'); ?>
        </div>

        <div class="elem">
            <?php echo $form->labelEx($model,'password2'); ?>
            <?php echo $form->passwordField($model,'password2',array('class'=>'inputbox grid-11-12')); ?>
            <?php echo $form->error($model,'password2'); ?>
        </div>

        <div class="elem">
            <?php echo $form->labelEx($model,'email'); ?>
            <?php echo $form->textField($model,'email',array('class'=>'inputbox grid-11-12','maxlength'=>45)); ?>
            <?php echo $form->error($model,'email'); ?>
        </div>

        <div class="elem">
            <label for="content">User Image:</label>
        <?php $this->widget('ext.EAjaxUpload.EAjaxUpload',
            array(
            'id'=>'uploadFile',
            'config'=>array(
                   'action'=>Yii::app()->request->baseUrl .'/backend.php/user/upload',
                   'allowedExtensions'=>array("jpg"),//array("jpg","jpeg","gif","exe","mov" and etc...
                   'sizeLimit'=>3*1024*1024,// maximum file size in bytes
                   'minSizeLimit'=>50*1024,// minimum file size in bytes
                   'multiple'=>false,
                   //'onComplete'=>Yii::app()->request->baseUrl .'/backend.php/user/saveStuff/?fn='. "js:function(id, fileName, responseJSON){ alert(fileName); }",
                   //'messages'=>array(
                   //                  'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
                   //                  'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
                   //                  'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
                   //                  'emptyError'=>"{file} is empty, please select files again without it.",
                   //                  'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
                   //                 ),
                   //'showMessage'=>"js:function(message){ alert(message); }"
          )
            )); ?>
        </div>

这是控制器..

    <?php

    class UserController extends Controller
    {
/**
 * @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/column1';
public $image;

.......


public function actions()
{
    return array(
        'upload' => array(
        'class' => 'ext.actions.uploadAction',
        ),
        );
}

........


public function actionCreate()
{
    $model=new User;
    $profile=new UserProfile;
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['User']))
    {
        $model->attributes=$_POST['User'];
        $profile->attributes=$_POST['UserProfile'];

        if(!$this->saveUser($model, $profile))
            Yii::app()->user->setFlash('error', 'Not Saved :)!');

    }

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

public function saveUser($model, $profile)
{
    $userValid  = $model->validate();
    $profileValid  = $profile->validate();
    $valid = $userValid && $profileValid;
    if($valid)
    {
        $model->save(false);
        $profile->user_id = $model->id;
        $profile->image = !is_null($this->image)?  $this->image : null; // name of image file which uploaded 
        $profile->save(false);

        Yii::app()->user->setFlash('success', 'Saved :)!');
        $this->redirect(array('index'));
        return true;
    }
    return false;
}

}

详细的外部操作是:

 <?php
 class uploadAction extends CAction
 {
/**
* Runs the action.
* This method is invoked by the controller owning this action.
*/
public function run()
{
    Yii::import("ext.EAjaxUpload.qqFileUploader");
        // make the directory to store the pic:
        $folder=Yii::getPathOfAlias('webroot') .'/images/' . $this->controller->id . '/';// folder for uploaded files
        if(!is_dir($folder))
        {
           mkdir($folder);
           chmod($folder, 0755); 
           // the default implementation makes it under 777 permission, which you could possibly change 
            //recursively before deployment, but here's less of a headache in case you don't
        }

        $allowedExtensions = array("jpg");//array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);
        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);

        $fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
        $fileName=$result['filename'];//GETTING FILE NAME

        $this->controller->image = $fileName; // ??????

        echo $return;// it's array



}
}
4

2 回答 2

0

我使用回调做了类似的事情。

所以在我的控制器操作()配置中,我有一行:

'onSuccessCallback' => 'myCallback'

在我的动作课中,在 run() 结束时,我有:

call_user_func( array($this->getController(),$this->onSuccessCallback), $fileName);

在控制器中我有

function myCallback($fileName)
{
this->image = $fileName;
}

然后我可以通过控制器从控制器访问该属性

$这个->图像

于 2012-10-06T15:52:44.790 回答
0

做这个:

$this->controller->image = $fileName; // this line does not work!!  
$this->controller->renderText($this->controller->image);

我敢打赌这将显示 $fileName。

您在哪里尝试访问控制器图像属性?

请求之间不保留值。

于 2012-04-24T07:14:26.210 回答