1

I'm having a problem with uploading multiple files names in postgresql with Yii2, I have a table named "i006t_factura" with an iD, a foreign key named "id_obra" and a "ruta" which is where I want to save the image file, but if I have multiple files, then I have to save multiple names for that "id_obra", so this is my code for my model:

<?php

namespace app\models;

use Yii;

/**
* This is the model class for table "i006t_factura".
*
* @property integer $id
* @property integer $id_obra
* @property string $ruta
*
* @property C004tObraSocial $idObra
*/
class Factura extends \yii\db\ActiveRecord
{
    public $ruta;
/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'i006t_factura';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['id'], 'required'],
        [['id_obra'], 'required'],
        [['id_obra'], 'integer'],
        [['ruta'], 'safe'],
        [['ruta'], 'file', 'extensions'=>'jpg, gif, png',
            'maxFiles' => 8,],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id_obra' => 'Id Obra',
        'ruta' => 'Ruta',
    ];
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getIdObra()
{
    return $this->hasOne(C004tObraSocial::className(), ['id' => 'id_obra']);
}

public function afterSave($insert, $changedAttributes)
{
    if(isset($this->ruta)){
        $this->ruta=UploadedFiles::getInstance($this,'ruta');
        if(is_object($this->ruta)){
            $path=Yii::$app->basePath . '/archivos/';  //set directory path to save image
            $this->ruta->saveAs($path.$this->id_obra."_".$this->ruta);   //saving img in folder
            $this->ruta = $this->id_obra."_".$this->ruta;    //appending id to image name            
            \Yii::$app->db->createCommand()
            ->update('organization', ['ruta' => $this->ruta], 'id = "'.$this->id_obra.'"')
            ->execute(); //manually update image name to db
        }
    }
}

}

My controller

<?php

namespace app\controllers;

use Yii;
use app\models\Factura;
use app\models\FacturaSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
* FacturaController implements the CRUD actions for Factura model.
*/
class FacturaController extends Controller
{
    public function behaviors()
    {
        return [
               'verbs' => [
                   'class' => VerbFilter::className(),
                   'actions' => [
                   'delete' => ['post'],
                    ],
               ],
       ];
   }

/**
 * Lists all Factura models.
 * @return mixed
 */
public function actionIndex()
{
    $searchModel = new FacturaSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

/**
 * Displays a single Factura model.
 * @param integer $id
 * @param integer $id_obra
 * @return mixed
 */
public function actionView($id_obra)
{
    return $this->render('view', [
        'model' => $this->findModel($id_obra),
    ]);
}

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

    if ($model->load(Yii::$app->request->post()) &&($model->save()) ) {
        $model->ruta = UploadedFile::getInstances($model, 'ruta');
        if($model->ruta){
            $imagepath = 'archivos/'; // Create folder under web/uploads/logo
            $model->ruta = $imagepath .rand(10,100).'-'.$model->ruta->name;
        }
        if($model->ruta){
            $model->ruta->saveAs($model->ruta);
        }
        return $this->redirect(['view','id'=>$model->id, 'id_obra' => $model->id_obra]);

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

    }
}

/**
 * Updates an existing Factura model.
 * If update is successful, the browser will be redirected to the 'view' page.
 * @param integer $id
 * @param integer $id_obra
 * @return mixed
 */
public function actionUpdate($id_obra)
{
    $model = $this->findModel($id_obra);

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        $model->ruta = UploadedFile::getInstances($model, 'ruta');

        if($model->file){
            $imagepath = 'archivos/';
            $model->ruta = $imagepath .rand(10,100).'-'.$model->ruta->name;
        }

        if($model->ruta){
            $model->file->saveAs($model->logo);
            return $this->redirect(['view','id'=>$model->id, 'id_obra' => $model->id_obra]);
        }
    }  else {
        return $this->render('update', [
            'model' => $model,
        ]);
    }
}

public function actionDeleteimg($id_obra)
{

    $ruta = Factura::find()-where(['id'=>$id_obra])->one()->ruta;
    if($ruta){
        if (!unlink($ruta)) {
        return false;
    }
}

    $factura = Factura::findOne($id_obra);
    $factura->ruta = NULL;
    $factura->update();

    return $this->redirect(['update', 'id_obra' => $id_obra]);
}

/**
 * Deletes an existing Factura model.
 * If deletion is successful, the browser will be redirected to the 'index' page.
 * @param integer $id
 * @param integer $id_obra
 * @return mixed
 */
public function actionDelete($id,$id_obra)
{
    $this->findModel($id)->delete();
    $this->findModel($id_obra)->delete();

    return $this->redirect(['index']);
}

/**
 * Finds the Factura model based on its primary key value.
 * If the model is not found, a 404 HTTP exception will be thrown.
 * @param integer $id
 * @param integer $id_obra
 * @return Factura the loaded model
 * @throws NotFoundHttpException if the model cannot be found
 */
 protected function findModel($id_obra)
 {
     if (($model = Factura::findOne(['id_obra' => $id_obra])) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
       }
 }
}

And my _form.php

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Factura */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="factura-form">

     <?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>

     <?= $form->field($model, 'id')->textInput() ?>

     <?= $form->field($model, 'id_obra')->textInput() ?>

     <?= $form->field($model, "ruta[]")->fileInput( ['multiple'=>true])?>
     <?php
     if ($model->ruta) {
          echo '<img src="'.\Yii::$app->request->BaseUrl.'/'.$model->ruta.'"   width="90px">&nbsp;&nbsp;&nbsp;';
          echo Html::a('Delete Logo', ['deleteimg', 'id'=>$model->id, 'field'=> 'ruta'], ['class'=>'btn btn-danger']).'<p>';
     }
     ?>


    <div class="form-group">
         <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

    </div>

The error is when it want to upload an image, where "ruta" is null because it's not detecting the URL, I don't know if I need an iterative cycle in some part of my code!

Thanks for the answer!

1 Answer 1

0

Well, I resolved part of the problem, which is save the image url, but for ONE image! When I try to use the getInstances for multiple images, still have an error!

This is the actionCreate() from my controller:

public function actionCreate()
{
    $model = new Factura();

    if ($model->load(Yii::$app->request->post())) {
        // Here is where I obtain the image 
        $model->file = UploadedFile::getInstance($model, 'file');
        if($model->file){
            $imagepath = 'archivos/'; 
            $model->ruta = $imagepath .rand(10,100).'-'.$model->file->name;
        }

        if($model->save()){
            if($model->file){
                $model->file->saveAs($model->ruta);
            }   
             return $this->redirect(['view', 'id' => $model->id, 'id_obra' => $model->id_obra]);
        }
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

And this is my updated _form.php:

 <div class="factura-form">

<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>

<?= $form->field($model, 'id')->textInput() ?>

<?= $form->field($model, 'id_obra')->textInput() ?>
//Where I submit my image
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

So, still have the multiple images problem... don't know it has to do with the db table...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.