I have a view, which is including a form. If an attribute of the model is empty in the DB I see the form so I can immediately upload a file, which at the same time updates the attribute in the DB, so next time I see the data what I want according to what I've uploaded.
This is my controller:
public function actionView($id) {
$model = $this->findModel($id);
...
if ($model->load($_POST)) {
$this->actionUpload($id);
}
return $this->render('view', [
'model' => $model,
]);
}
public function actionUpload($id) {
$model = $this->findModel($id);
if ($model->upload()) {
return $this->redirect(Url::previous());
} else {
# ***
return $this->render('view', [
'model' => $model,
]);
}
}
*** If validation fails, at this point I can see the error, but in the view not any more, because it's empty. How can it be? It should be there, shouldn't it? Somewhere I'm doing a mistake but I have no clue how.
My View:
if ($model->attr) {
echo $model->attr;
} else {
echo $this->render('_upload', [
'model' => $model,
]);
}
_upload:
echo $form->field($model, 'uploadedFiles[]')->fileInput([...
echo $form->errorSummary($model);
(submitButton)
Can you please tell me at which point my error can be disappearing?
Merge both controller actions into one action. From first action you are calling the second action which does redirect on success - so it would never return back to first action.
Related
I have modified user table to add one column, the column's name is id_periode, I have advanced template, so from backend controler i want update that column value. I create controller like this
public function actionPindahPeriode($id)
{
$model2 = $this->findModel2($id);
if ($model2->load(Yii::$app->request->post()) ) {
$model2->save();
return $this->render('view',
'model2' => $this->findModel2($id),
]);
}
date_default_timezone_set('Asia/Makassar');
$jam_sekarang = date('h:i:s', time());
$tgl_sekarang=date('Y-m-d');
$model_periode = Periode::find()
->andWhere(['>','mulai_daftar_ulang',$tgl_sekarang ])
->asArray()
->all();
return $this->renderAjax('pindah_periode', [
'model_periode' => $model_periode,
'model2' => $this->findModel2($id),
]);
}
The findModel2 function is like this
protected function findModel2($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
I render that model into a form
<?php $form = ActiveForm::begin(); ?>
<?php $listData=ArrayHelper::map($model_periode,'id',function($model_periode){
return $model_periode['nama_periode'].' Tahun '.$model_periode['tahun'];});?>
<?= $form->field($model2, 'id_periode')->dropDownList($listData, ['prompt' => '']) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
The form is working but i can not update the value id_periode column in table user. There is not error showing, any suggestion?
Make sure your new attribute id_periode has a rule defined in the public function rules(){} function, this way $model2->load(Yii::$app->request->post()) will assign this value from the data submitted.
$model->save() returns a bool value whether the record was saved or not. You can use this to your advantage and check whether there are any validation errors.ie:
if($model2->save()) {
return $this->render('view',
'model2' => $this->findModel2($id),
]);
} else {
return $this->renderAjax('pindah_periode', [
'model_periode' => $model_periode,
'model2' => $this->findModel2($id),
]);
}
Option 1 : Check your column fields in User model's validation rules. You need to shift unwanted column fields from required attribute to safe attribute.
Option 2 : try $model2->save(false);. false will override your model rules.
I searched in documentation how to turn on ToggleTranslate on Yii 2 but with no success. I echoed widget
<?= \lajax\translatemanager\widgets\ToggleTranslate::widget(); ?>
but it does not apper. Then I went to source code and got this:
if (!Yii::$app->session->has(Module::SESSION_KEY_ENABLE_TRANSLATE)) {
return;
}
I commented it and my button appeared. But button is not working. So my question is how to properly (by proper flow, by proper guide) configure it and run it?
Site controller I modified:
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
/** set session key for appearing translate button */
if(array_key_exists('admin', Yii::$app->authManager->getAssignments(Yii::$app->user->id)))
\Yii::$app->session->set('frontendTranslation_EnableTranslate',1);
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
I have a controller with a working action:
class ConfigurationController extends Controller {
public function actions() {
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionView() {
$myModel = ...
$this->render('view', ['model' => $myModel]);
}
}
All seems to be fine, however the layout file which is app/views/layout/main.php does not get shown. There is no special configuration about the layout. What could be wrong?
The main reason: I did not use the return statement. So the correct action is:
public function actionView() {
$myModel = ...
return $this->render('view', ['model' => $myModel]);
// ^^^^^^
}
More info can be found in the guide.
Note: Usually an empty page would be shown. But I also had a <?php $form = ActiveForm::begin(); ?> without an <?php ActiveForm::end(); ?> in the view file. This caused a partial rendering somehow (caused no exception). So I needed to correct this as well.
I'm just sharing my problem and what I've found out so if anyone else has a similar effect may be reminded that the return statement must not be forgotten.
I'm making my first application using Yii and I have the next code:
public function actionCreate()
{
$model = new User();
$singUp = new \frontend\models\SingupForm;
if ($singUp->load(Yii::$app->request->post()) && $singUp->save()) {
$model = ModelName::findOne(['id' => $singUP->id]);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
'singUp' => $singUp
]);
}
}
And I'm having the next error message when I try to go to that method:
Class 'frontend\models\SingupForm' not found
But I have the file saved on the directory as it is showed in the screenshot I attached. Additionally I added all the models folder of the Frontend on the controller I am using:
use Yii;
use \frontend\models;
use common\models\User;
use backend\models\search\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\PermissionHelpers;
So I don't know what I'm doing wrong. Please help
Screenshot
There is a typo in your code.
Please Change frontend\models\SingupForm to frontend\models\SignupForm.
I am trying to create make a two-step form in yii2.
This is my SiteController.php
public function actionCreateCharacter()
{
$model = new Character();
var_dump(Yii::$app->request->post('Character'));
if ($model->load(Yii::$app->request->post())) {
$attributes=['imie','nazwisko','plec','wyznanie_id'];
if ($step1 = $model->validate($attributes)) {
//var_dump($step1);
// form inputs are valid, do something here
//var_dump(Yii::$app->request->post('Character');
return $this->render('createCharacterStep2', [
'model' => $model,
]);;
}
else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
}
return $this->render('createCharacter', [
'model' => $model,
]);
}
public function actionCreateCharacterStep2()
{
$model2 = new Character();
var_dump($model);
if ($model2->load(Yii::$app->request->post())) {
var_dump(Yii::$app->request->post('Character'));
if ($model2->validate()) {
// form inputs are valid, do something here
return;
}
}
/*return $this->render('createCharacter2', [
'model' => $model,
]);*/
}
... and this is my Character.php (model + attributeLabels and tableName)
public function rules()
{
return [
[['user_id', 'imie', 'nazwisko', 'plec', 'wyznanie_id', 'avatar_src', 'avatar_svg'], 'required'],
[['user_id', 'wyznanie_id'], 'integer'],
[['avatar_svg'], 'string'],
[['imie'], 'string', 'max' => 15],
[['nazwisko'], 'string', 'max' => 20],
[['plec'], 'string', 'max' => 1],
[['avatar_src'], 'string', 'max' => 30]
];
}
I have access to $_POST by Yii::$app->request->post() in createCharacter - I get imie, nazwisko, plec and wyznanie_id.
But when I send the form in step 2 I have only post data from step 2.
How can I set the post data from step1+step2?
Sorry for my english and thanks in advance.
While rendering step2 from step1 action, you can always pass additional data to controller's action. So I added "STEPONEPOSTS" post variable which contains all posts of step 1. Check below.
public function actionCreateCharacter()
{
$model = new Character();
var_dump(Yii::$app->request->post('Character'));
if ($model->load(Yii::$app->request->post())) {
$attributes=['imie','nazwisko','plec','wyznanie_id'];
if ($step1 = $model->validate($attributes)) {
//var_dump($step1);
// form inputs are valid, do something here
//var_dump(Yii::$app->request->post('Character');
return $this->render('createCharacterStep2', [
'model' => $model,
'STEPONEPOSTS' => Yii::$app->request->post(),
]);;
}
else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
}
return $this->render('createCharacter', [
'model' => $model,
]);
}
And now in step 2 view, you can get step 1 posts variable as
$STEPONEPOSTS
There is another way , if you have to table for step 1 and step 2. then save the data of step 1 first then step2 data. if you are not using two tables then you can create two form each form for each step and also create scenarios for each step according to the fields.I think this may help . You can use session also as per discussion in comments or you can use the extension array wizard but array wizard extension is not well documented , so i suggest you try my way i will help you.