简体   繁体   English

在 Yii2 框架中使用 ActiveForm 的文件上传字段不起作用

[英]File Upload field using ActiveForm in Yii2 framework does not work

I want to add a File Upload field in an ActiveForm in Yii2 framework, but it's not working, the file is not uploaded nor the name of the file is stored in the database column 'company_cover'.我想在 Yii2 框架的 ActiveForm 中添加一个文件上传字段,但它不起作用,文件没有上传,文件名也存储在数据库列“company_cover”中。

If someone could help me find my mistake.如果有人能帮我找出我的错误。 Thanks in advance.提前致谢。

The VIEW风景

 <div class="block-body collapse" id="company-block">
                            <?php $form = ActiveForm::begin([
                                'id'        => 'form-change-company',
                                'method'    => 'post',
                                'action'    => ['account/update-company'],
                                'enableAjaxValidation' => false,
                                'options'   => ['enctype' => 'multipart/form-data'],
                            ]); 


                            ?>
                            <div class="row">
                                <div class="col-lg-2 col-md-2 col-sm-2 col-xs-12">
                                    <?= $form->field($modelAbout, 'group_id', [
                                        'template'      => '{input} {error}',
                                    ])->dropDownList([2 => t('app','Enable'), 1 => t('app','Disable')])->label(false);
                                    ?>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                                    <?= $form->field($modelCompany, 'store_name', [
                                        'template'      => '{input} {error}',
                                    ])->textInput([ 'placeholder' => t('app','Store Name'), 'class' => ''])->label(false); ?>
                                </div>
                                <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                                    <?= $form->field($modelCompany, 'company_name', [
                                        'template'      => '{input} {error}',
                                    ])->textInput([ 'placeholder' => t('app','Company Name'), 'class' => ''])->label(false); ?>
                                </div>
                                <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                                    <?= $form->field($modelCompany, 'company_mail', [
                                        'template'      => '{input} {error}',
                                    ])->textInput([ 'placeholder' => t('app','Company E-Mail'), 'class' => ''])->label(false); ?>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                                    <?= $form->field($modelCompany, 'company_no', [
                                        'template'      => '{input} {error}',
                                    ])->textInput([ 'placeholder' => t('app','Company No'), 'class' => ''])->label(false); ?>
                                </div>
                                <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                                    <?= $form->field($modelCompany, 'vat', [
                                        'template'      => '{input} {error}',
                                    ])->textInput([ 'placeholder' => t('app','VAT'), 'class' => ''])->label(false); ?>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                                </div>
                            </div>

                                <div class="row">
                                <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                                    <?= $form->field($modelCompany, 'company_lat', [
                                        'template'      => '{input} {error}',
                                    ])->textInput([ 'placeholder' => t('app','Company Latitude'), 'class' => ''])->label(false); ?>
                                </div>
                                <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                                    <?= $form->field($modelCompany, 'company_lng', [
                                        'template'      => '{input} {error}',
                                    ])->textInput([ 'placeholder' => t('app','Company Longitude'), 'class' => ''])->label(false); ?>
                                </div>
                            </div>
                           <div class="row">
                                <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">

                                <?= $form->field($modelCompany, 'file')->fileInput([ 'placeholder' => t('app','Company Cover'), 'class' => '']) ?>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                                    <button type="submit" id="submit-company-info" class="btn-as" value="Submit"><?=t('app','Submit');?></button>
                                </div>
                            </div>
                            <?php ActiveForm::end(); ?>
                        </div>
                    </div>

The MODEL该模型

class CustomerStore extends \app\models\auto\CustomerStore
{
    // when inactive model
    const STATUS_INACTIVE = 'inactive';

    // when active model
    const STATUS_ACTIVE = 'active';

    // when deactivated
    const STATUS_DEACTIVATED = 'deactivated';

    public $file;
    public function rules()
    {
        return [
            [['store_name', 'company_name', 'company_mail', 'company_lat', 'company_lng', 'company_no', 'vat'], 'trim'],
            [['store_name', 'company_name'], 'required'],
            [['file'], 'file'],
            [['store_name', 'company_name'], 'string', 'max' => 30],
            [['company_no', 'vat'], 'string', 'max' => 20],

            [['status'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors[] = [
            'class'     => SluggableBehavior::className(),
            'value' => [$this, 'getSlug'] //https://github.com/yiisoft/yii2/issues/7773
        ];
        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return ArrayHelper::merge(parent::attributeLabels(), [
            'store_id'      => t('app', 'Store ID'),
            'customer_id'   => t('app', 'Customer'),
            'store_name'    => t('app', 'Store Name'),
            'company_name'  => t('app', 'Company Name'),
            'company_mail'  => t('app', 'Company E-Mail'),
            'company_no'    => t('app', 'Company No'),
            'vat'           => t('app', 'VAT'),
            'status'        => t('app', 'Status'),
            'company_lat'   => t('app', 'Company Latitude'),
            'company_lng'   => t('app', 'Company Longitude'),
            'company_cover' => t('app', 'Company Cover'),
            'created_at'    => t('app', 'Created At'),
            'updated_at'    => t('app', 'Updated At'),
        ]);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['customer_id' => 'customer_id']);
    }

    /**
     * @return bool
     */
    public function deactivate()
    {
        $this->status = self::STATUS_INACTIVE;
        $this->save(false);
        return true;
    }

    /**
     * @return bool
     */
    public function activate()
    {
        if($this->status == self::STATUS_DEACTIVATED || $this->status == self::STATUS_INACTIVE) {
            $this->status = self::STATUS_ACTIVE;
            $this->save(false);
        }
        return true;
    }

    /**
     * @param $slug
     * @return array|null|\yii\db\ActiveRecord
     */
    public function findBySlug($slug)
    {
        return $this->find()->where(array(
            'slug' => $slug,
        ))->one();
    }

    /**
     * @param $event
     * @return string
     * //https://github.com/yiisoft/yii2/issues/7773
     */
    public function getSlug($event)
    {
        if(!empty($event->sender->slug)) {
            return $event->sender->slug;
        }
        return Inflector::slug($event->sender->store_name);
    }
}

The CONTROLLER (the controller is quite long so i just paste the part for the file upload field)控制器(控制器很长,所以我只是粘贴文件上传字段的部分)

 public function actionUpload()
{
    $modelCompany = new CustomerStore();

    if (Yii::$app->request->isPost) {
        $modelCompany->file = UploadedFile::getInstance($modelCompany, 'file');

        if ($modelCompany->validate()) {                
            $modelCompany->file->saveAs('/' . $modelCompany->file->baseName . '.' . $modelCompany->file->extension);
        }
    }

    return $this->render('upload', ['model' => $modelCompany]);
}

I think you must to load post data to the model.我认为您必须将发布数据加载到模型中。 You can try do like this你可以尝试这样做

if ($modelCompany->load(Yii::$app->request->post())) {
    $modelCompany->file = UploadedFile::getInstance($modelCompany, 'file');

    if ($modelCompany->validate()) {                
        $modelCompany->file->saveAs('/' . $modelCompany->file->baseName . '.' . $modelCompany->file->extension);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM