user7978226
user7978226

Reputation:

Yii2 How to save file with custom file name?

How to save a file using a custom file name? I used gii generator for my website and i have a file input in my form now i want is after saving the file the name is get from report_id which is my primary key. For example, 1_.docx the 1 is my report_id. I have also a doc_name field, Yes i can save my file and get the name in doc_name. For example, sample.docx. But my problem is when i used the report_id and for example save the data the name of the file is .docx only.

This is my controller:

  public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post())) 
{      
    $project= $model->doc_name;
    $model->upload_file= UploadedFile::getInstance($model,'doc_file');
    $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
    $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
    $model->doc_name=$project.'.'.$model->upload_file->extension;
    $model->save();

    Yii::$app->getSession()->setFlash('success','Data saved!');
    return $this->redirect(['view','id'=> $model->report_id]);
    } 

    else {

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

}

As you can see, $project=$model->doc_name; this the codes when i save a data, the name of the file will get from the doc_name but if i change it into report_id, when i save it the result is blank or .docx only.

This is my _form:

  <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
     &nbsp;&nbsp;&nbsp;<?= Html::button('<i class="fa fa-plus"></i>&nbsp;Add Person', ['value' => Url::to('index.php?r=name/create'), 'class' => 'btn btn-custom-pos btn-success', 'id' => 'officialsfor']) ?>
        </br>  
        </br> 
  <?php Pjax::begin(['id' => 'for_from']) ?>
      <div class="col-sm-6">
     <?= $form->field($model, 'doc_for')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
            'name_id',
            function($model, $defaultValue){
              return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
             ],
            ]); ?>
      </div>
      <div class="col-sm-6">
    <?= $form->field($model, 'doc_from')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
           'name_id',
            function($model, $defaultValue){
            return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
            ],
            ]); ?>
 <?php Pjax::end(); ?>
      </div>
        </br>
        </br></br></br>
      <div class="broder" style=" border-radius: 5px; padding: 12px; ">    
      </div>
  <div class="col-sm-6">
      <?= $form->field($model, 'user_id')->textInput(['type' => 'hidden','style'=>'width:500px;','placeholder' => 'Enter a Reference No....','value' =>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name)]) ?>
       <?= Html::activeLabel($model, 'user_id', ['label'=>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name),'style' => 'font-size: 21px;','class' => 'color']) ?>
      <br>
      <br>
      <?= $form->field($model, 'reference_no')->textInput(['style'=>'width:500px','placeholder' => 'Enter a Reference No....']) ?>
      <?= $form->field($model, 'subject')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Subject....']) ?>
    <?= $form->field($model, 'doc_date')->widget(
        DatePicker::className(), [
            'inline' => false,
            'options' => ['placeholder' => 'Choose a Entry Date ...'],
            'clientOptions' => [
            'autoclose' => true,
            'format' => 'yyyy-mm-dd'
              ]
             ]);?>
  </div>
  <div class="col-sm-6" style="padding-top: 14px; ">
         </br>
         </br>
         </br></br>
    <?= $form->field($model, 'drawer_id')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Drawer ID....', ]) ?>
    <?= $form->field($model, 'doc_name')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Document Name....']) ?>
      <?= $form->field($model, 'doc_file')-> widget(
        FileInput::classname(),[
      'name' => 'doc_file',
      'options' => ['accept' => '.docx','.doc','.docs'],
      'pluginOptions' => [
          'showPreview' => false,
          'showCaption' => true,
          'showRemove' => true,
          'showUpload' => false
            ]
        ]);
      ?> 
  </div>
</div>
</br>
<div class="row">
  <div class="col-sm-12 text-center">
    <div class="form-group">
      <?= Html::submitButton($model->isNewRecord ? '<i class="fa fa-plus"></i>&nbsp;Create' : '<i class="fa fa-pencil"></i>&nbsp;Update', ['class' => $model->isNewRecord ? 'btn btn-success'  : 'btn btn-success','style' => 'padding:10px 60px;']) ?>
    </div>
  </div>
</div>
<?php ActiveForm::end(); ?>

Upvotes: 0

Views: 3648

Answers (1)

Irfan Ali
Irfan Ali

Reputation: 2258

as you said report_id is primary key, so you won't get it before save the new record in db.

as per your logic, insertion is happing with new record. so you need to updated your code like below. check it.

public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post())) 
    {      
        $project= $model->doc_name;
        $model->upload_file = UploadedFile::getInstance($model,'doc_file');
        $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
        $model->doc_name=$project.'.'.$model->upload_file->extension;
        $model->save();

        // after save you will get report_id
        rename('uploads/'.$project.'.'.$model->upload_file->extension, 'uploads/'.$model->report_id.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$model->report_id.'.'.$model->upload_file->extension;
        $model->doc_name=$model->report_id.'.'.$model->upload_file->extension;
        $model->save();


        Yii::$app->getSession()->setFlash('success','Data saved!');
        return $this->redirect(['view','id'=> $model->report_id]);
    } 

    else {

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

}

Upvotes: 1

Related Questions