Answer the question
In order to leave comments, you need to log in
How to display value from db to input yii2?
There is a form:
<?php $f = ActiveForm::begin(['options' => ['id' => 'contact', 'class' => 'floating-labels m-t-40']]); ?>
<?php echo $f->field($form, 'tel') ?>
<?php echo $f->field($form, 'skype') ?>
<?php echo $f->field($form, 'whatsapp') ?>
<?php echo $f->field($form, 'index') ?>
<?php echo Html::submitButton('Сохранить', ['class' => 'btn btn-danger']); ?>
<?php ActiveForm::end(); ?>
<?php
namespace app\modules\dashboard\models;
use Yii;
use yii\db\ActiveRecord;
/**
*
*/
class ContactForm extends ActiveRecord
{
public static function tableName() {
return 'contact';
}
public function rules()
{
return [
[['tel', 'skype', 'whatsapp', 'index'], 'trim'],
[['tel', 'skype'], 'required'],
];
}
public function attributeLabels()
{
return [
'tel' => 'Номер телефон',
'skype' => 'Логин Skype',
'whatsapp' => 'Номер whatsapp',
'index' => 'Ваш индекс',
];
}
}
?>
public function actionProfile() {
$id = Yii::$app->user->identity->id;
$user = ContactForm::find()->where(['=', 'user_id', $id])->one();
$form = new ContactForm();
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
$id = Yii::$app->user->identity->id;
$user = ContactForm::find()->where(['=', 'user_id', $id])->one();
$user->tel = Html::encode($form->tel);
$user->skype = Html::encode($form->skype);
$user->whatsapp = Html::encode($form->whatsapp);
$user->index = Html::encode($form->index);
$user->save();
return $this->refresh();
}else{
return $this->render('profile', compact('form', 'user'));
}
}
<?php echo $f->field($form, 'tel')->textInput() ?>but nothing happens.
Answer the question
In order to leave comments, you need to log in
echo $f->field($user, 'tel')
Isn't that how it should be?
upd: You fill in the $user model, and bind the input from the $form model, which is empty unless a POST is passed to fill it.
$form = new ContactForm();
$form->tel = $user->tel;
$id = Yii::$app->user->identity->id;
$user = ContactForm::find()->where(['user_id' => $id])->one();
$form = new ContactForm($user);
if ($form->load(Yii::$app->request->post()) && $form->validate() && $form->save()) {
return $this->refresh();
}else{
return $this->render('profile', compact('form', 'user'));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question