Yii2: the Eimage holder does not work on the server



  • Model:

    namespace app\models;
    

    class TestModel extends \yii\base\Model
    {
    public $myImage;

    public function rules()
    {
        return [
            ['myImage', 'image', ],
        ];
    }
    

    }


    Introduction:

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

    /* @var $this object yii\web\View /
    /
    @var $form object yii\widgets\ActiveForm /
    /
    @var $model object app\models\TestModel */

    $form = ActiveForm::begin(['enableClientValidation' => false, ]);

    echo $form->field($model, 'myImage')->fileInput();

    echo Html::submitButton();

    ActiveForm::end();


    I've turned off the client's bond:

    'enableClientValidation' => false,

    To check on the server, as the client's side is working well, but the server doesn't work, so any files are missing? ♪ ♪


    Controller:

    namespace app\controllers;

    use Yii;
    use yii\web\UploadedFile;
    use app\models\TestModel;

    class TestController extends \yii\web\Controller
    {

    public function actionIndex()
    {
        $model = new TestModel();
    
        if (
            $model->load(Yii::$app->request->post())
                &&
            $model->validate()
        ) {
            die('Model is valid!');
        }
    
        return $this->render('index', [
            'model' => $model,
        ]);
    }
    

    }



  • So, as usual, ignorant! And reluctance to understand!


    This is about the counteraller...

    As is well known, PHP server arrival files are not available $_POST$_FILES... So, actually, we can't download the model. Total so:

    $model->load(Yii::$app->request->post());
    

    We need to download the attributes that are files like this:

    $model->myImage = UploadedFile::getInstance($model, 'myImage');
    

    It's like before the validation, the model needs to be completely downloaded:

    public function actionIndex()
    {
        $model = new TestModel();
    
    if ($model->load(Yii::$app->request->post())) {
    
        $model->myImage = UploadedFile::getInstance($model, 'myImage');
    
        if ($model->validate()) {
    
            die('Model is valid!');
    
        }
    
    }
    
    return $this->render('index', [
        'model' => $model,
    ]);
    

    }


    I'll add that it's necessary to assign attributes (which are files) after the call. $model->load()because they will otherwise be overloaded (because the POST request will also include this attribute but empty).


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2