D
D
Damir Shaniyazov2021-02-10 10:45:59
Yii
Damir Shaniyazov, 2021-02-10 10:45:59

How to upload a profile photo?

I needed to upload a profile photo. The table was supposed to store a link to the file, so photo_link , as text.
I created such an MVC.

<?php

namespace app\models;

use Yii;
use yii\web\UploadedFile;

/**
 * This is the model class for table "profile".
 *
 * @property int $id
 * @property string|null $surname
 * @property string|null $name
 * @property string|null $email
 * @property string|null $gender
 * @property string|null $birthday
 * @property string|null $telephone
 * @property string|null $site
 * @property string|null $role
 * @property string|null $company
 * @property string|null $about
 * @property string|null $photo_link
 * @property string|null $city
 *
 * @property User $id0
 */
class Profile extends \yii\db\ActiveRecord
{
    public $photo_link;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'profile';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['birthday'], 'safe'],
            [['about', 'photo_link'], 'string'],
            [['surname', 'name', 'email', 'gender', 'telephone', 'site', 'role', 'company', 'city'], 'string', 'max' => 255],
            [['id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['id' => 'id']],
            [['photo_link'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg']
        ];
    }

    public function upload() {
        if ($this->validate()) {
            $this->photo_link->saveAs('uploads/' . $this->photo_link->baseName . '.' . $this->photo_link-extension);
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'surname' => 'Surname',
            'name' => 'Name',
            'email' => 'Email',
            'gender' => 'Gender',
            'birthday' => 'Birthday',
            'telephone' => 'Telephone',
            'site' => 'Site',
            'role' => 'Role',
            'company' => 'Company',
            'about' => 'About',
            'photo_link' => 'Photo Link',
            'city' => 'City',
        ];
    }
}


<?php

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

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

<div class="profile-form">

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

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

    <?= $form->field($model, 'surname')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'gender')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'birthday')->textInput(['maxlength' => true, 'type' => date]) ?>

    <?= $form->field($model, 'telephone')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'site')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'company')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'about')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'photo_link')->fileInput() ?>

    <?= $form->field($model, 'city')->textInput(['maxlength' => true]) ?>

    <div class="form-group">
        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
    </div>

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

</div>


<?php

namespace app\controllers;

use Yii;
use app\models\Profile;
use app\models\ProfileSearch;
use yii\db\Exception;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

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

    /**
     * Lists all Profile models.
     * @return mixed
     */
//    public function actionIndex()
//    {
//        $searchModel = new ProfileSearch();
//        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//
//        return $this->render('index', [
//            'searchModel' => $searchModel,
//            'dataProvider' => $dataProvider,
//        ]);
//    }

    /**
     * Displays a single Profile model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

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

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

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

    /**
     * Updates an existing Profile model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate()
    {
        if (Yii::$app->user->isGuest) return $this->redirect(['site/login']);
        $id = Yii::$app->getUser()->getId();

        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->photo_link = UploadedFile::getInstance($model, 'photo_link');
            return $this->redirect(['view', 'id' => $model->id]);
        }

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

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

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

    /**
     * Finds the Profile model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Profile the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Profile::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    /**
     * Показывает профиль текущего пользователя
     * @return mixed
     */
    public function actionIndex() {
        if (Yii::$app->user->isGuest) return $this->redirect(['site/login']);

        $id = Yii::$app->getUser()->getId();
        $model = null;
        $role = null;

        try {
            $model = $this->findModel($id);
            $role = Yii::$app->db->createCommand('SELECT item_name FROM auth_assignment WHERE user_id=:id')->bindValue(':id', $id)->queryScalar();
        }
         catch (Exception $e) {
            echo "Ошибка формирования Вашего профиля. Сообщите нам об ошибке по почте." . $e;
        }

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


When you select a file, the validation passes, but when I click on Save, the validation says that you need to select a file. There is no entry in the database. And the file was not saved in the project.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Alexander Lykasov, 2021-02-10
@lykasov-aleksandr

If you have a photo_link field in your table, then remove it from the modelpublic $photo_link;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question