How to grab the value of a dropDownList in Yii2? - yii2

I am not grabbing the selected value ($model->attribute) on a dropDownList in Yii2, what could be wrong? Thanks
This is the code that is located on a View:
$command = $connection->createCommand('SELECT att1
FROM table
ORDER By table_id ASC');
$rows = $command->queryAll();
$command->execute();
$listData = ArrayHelper::index($rows, null, 'table_id');
Then on the same View I call to $listData
<div class="row">
<div class="col-lg-9">
<?php Pjax::begin(['enablePushState' => false]); ?>
<?php $form = ActiveForm::begin(['id' => 'test-form', 'options' => ['data-pjax' => true]
]); ?>
<?= $form->field($model, 'attribute')->dropDownList($listData, ['prompt'=>'List of attributes.']); ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'test-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
</div>
</div>
This is the Controller:
public function actionTest()
{
$model = new TestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->insertTest();
return $this->renderAjax('test', ['model' => $model]);
} else {
return $this->renderAjax('test', ['model' => $model]);
}
}
The Model has the definition of $attribute and insertTest() is a function that use the value of $attribute to query onto a DB.

Thinking of you should use
ArrayHelper::map($listData, 'table_id', 'table_id');
Because you need a one-dimensional array.
And it's better to use the ActiveRecord for queries to the database.
ArrayHelper Docs

You are selecting only att1 from table so you should map this column
$listData = ArrayHelper::index($rows, 'att1');
for debug try modify your actionTest commenting $model->insertTest(); and using $model->save();
if the value is saved in db then you should check inside you $model->insertTest() function
public function actionTest()
{
$model = new TestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
// $model->insertTest();
$model->save();
return $this->renderAjax('test', ['model' => $model]);
} else {
return $this->renderAjax('test', ['model' => $model]);
}
}

you should use map in ArrayHelper
$listdata = ArrayHelper::map(CategoryModel::find()->orderBy(['table_id' => SORT_ASC])->all(), 'table_id', 'table_text');
Note: 'table_text' is table attribute that will appear in dropdown label.

I found the solution to that issue.
By doing this way the form was not able to save the submitted information.
$command = $connection->createCommand('SELECT att1
FROM table
ORDER By table_id ASC');
$rows = $command->queryAll();
$command->execute();
$listData = ArrayHelper::index($rows, null, 'table_id');
However, by this way the form is able to grab the value selected and put it into the variable.
$rows = table::find()->all();
$listData = ArrayHelper::map($rows,'table_id','att1');

Related

How to get the input value from form to controller and store in a variable?

I have a form page in which that there are 3 input fields connected to database, now i need to add a new input field and get the values in variable in my controller page.
I have tried with constants my function is working properly but i need variables to do in my function
my form page
<?= $form->field($model, 'idnew_table')->textInput(['maxlength' => 5,'style'=>'width:100px']) ?>
<?= $form->field($model, 'adcaddress1')->textInput(['maxlength' => 5,'style'=>'width:200px']) ?>
<?= $form->field($model, 'adcaddress2')->textInput(['maxlength' => 5,'style'=>'width:200px']) ?>
<label>Value:</label><br>
<input type="text" name="submitvalue" value=""><br><br>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
my controller function is,
public function actionCreate($data=null,$data1=null,$data2=null)
{
$model = new Adcaddress();
$this->layout='admin';
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->idnew_table]);
} else {
$data2 = "variable";
$my_file1 = 'test.txt';
$handle1 = fopen($my_file1, 'r');
$data = $handle1;
$data = fread($handle1,filesize($my_file1));
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
//$data = $handle;
fwrite($handle, "$data2");
// return $this->render('create', [ 'model' => $model, ]);
return $this->render('create', array('data' => $data,'data1' => $data1,'data2'=>$data2,
'model' => $model));
}
i need the value of name=submitvalue in my variable $data2 in my controller page.
the $model->load(Yii::$app->request->post())
load only the attribute related to the model contained in $_POST
the input you added named 'submitvalue' is not declared as a part of the model
(the name of attrribute model is by default as ModelName[attribute])
and then is not automatically loaded in the $model
if you need the content of the $_POST and work on it for inspecting you could use
$post = Yii::$app->request->post();
var_dump($post);

how to display default value in dropDownlist

I have two dropDownlist in index, when I select the submit button it will get action in controller, and it performs some operations and again render the index with gridview, but the Selected dropDownList become blank, how can I set the default in dropDownllist??
Any suggestion should be appreciatable...
this is my view
<div class="col-sm-12" align="center">
<?= $form->field($model, 'fk_int_payroll_month')->dropDownList(
ArrayHelper::map(TblPayrollMonth::find()->all(), 'pk_int_payroll_month_id','vchr_month'),
['prompt'=> 'Select...'])
?>
</div>
<div class="col-sm-12" align="center">
<?= $form->field($model, 'fk_int_payroll_year')->dropDownList(
ArrayHelper::map(TblPayrollYear::find()->all(), 'pk_int_payroll_year_id','year'),
['options' => [isset($_POST['fk_int_payroll_year'])?'fk_int_payroll_year':'' => ['Selected'=>true]]],
['prompt'=> 'Seect...'])
?>
</div>
this is my controller
public function actionDisplay()
{
$model = new TblPayroll();
if(Yii::$app->request->post()!=null)
{
$data = Yii::$app->request->post();
// var_dump($data);
// die;
$month = $data['TblPayroll']['fk_int_payroll_month'];
$year = $data['TblPayroll']['fk_int_payroll_year'];
/* Be careful with this! */
$dataProviderSearch = new ActiveDataProvider
([
'query' => TblPayroll::find()->where(['fk_int_payroll_month'=>$month, 'fk_int_payroll_year'=> $year]),
'pagination' => ['pageSize' => 5],
]);
if($dataProviderSearch)
{
return $this->render('index', [
'dataProviderSearch' => $dataProviderSearch,
'model' => $model,
]);
}
}
else{
return $this->render('index', ['model' => $model]);
}
when i select dropdown it will gott actionDisplay, and find the dataprovider, and then it again render to index, so that time how can i show default selected value in dropDownlist?
If you are using an activeRecord then in controllerAction you should assign to the $model->your_fiedl the value you need for default
else{
$model->fk_int_payroll_month = 3
return $this->render('index', ['model' => $model]);
}
if you don't are using an active record you could use
->dropDownList($yourlist ,$selection)
eg
->dropDownList(ArrayHelper::map(TblPayrollMonth::find()->all() ,3)

Get data from form field to button value in yii2

I have a form field and a button in a form. The button should get the data from the form field and pass the value as parameter. Please tell me how can I get the data from the form field and pass the value.
form field -
<?= $form->field($model, 'productname')->textInput(['maxlength' => true]) ?>
button
<?= Html::a('Search', ['/stock/sellitem/printproductledger3', 'productname' => '8904187001305'], ['class'=>'btn btn-primary']) ; ?>
The above example work fine because the value is already given here 'productname' => '8904187001305'
What I need to do is get the value '8904187001305' from the form field. Please help.
actionIndex
public function actionIndex2()
{
$searchModel = new SellitemsbdtSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('_formbtdt', [
'model' => $searchModel,
]);
}
This index leads to _formdtbt
'action' => ['/stock/sellitem/printproductledger3',],
<?= $form->field($model, 'productname')->textInput(['maxlength' => true,]) ?>
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
Controller action printproductledger3
public function actionPrintproductledger3() {
$searchModel1 = new SellitemsbdtSearch();
$dataProvider1 = $searchModel1->search(Yii::$app->request->get());
$searchModel2 = new PuritemsbdtSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->get());
return $this->render('_printproductledgerbtdt', [
'dataProvider1' => $dataProvider1,
'searchModel1' => $searchModel1,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
Well, I think I've pointed to wrong issue. The issue is model sellitemsbdtSearch is getting filtered but puritemsbdtSearch is not getting filtered.
Search Model sellitemsbdtSearch
public function search($params)
{
//$query = Sellitem::find();
$query = Sellitem::find()
->joinWith(['siSs'])
->select(['sellsum.ss_date as date','si_iupc','si_idesc', 'concat("By sales to Tax Invoice ", sellsum.ss_invno) as particular', 'si_qty as sellqty','(si_qty * si_rate) as value'])
->orDerBy([
'sellsum.ss_date'=>SORT_DESC,
]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ['pageSize' => 10000000000,],
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
if($this->productname){
$query->andFilterWhere(['si_iupc'=> $this->productname]);
return $dataProvider;
}
}
Search Model puritemsbdtSearch
public function search($params)
{
$query = Puritem::find()
->joinWith(['psi'])
->select(['pursum.ps_date as date','pi_upc','pi_desc', 'concat("By purchase to Tax Invoice ", pursum.ps_invno) as particular', 'pi_qty as buyqty','(pi_qty * pi_rate) as value'])
->orDerBy([
'pursum.ps_date'=>SORT_DESC,
]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ['pageSize' => 10000000000,],
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
if($this->productname){
$query->andFilterWhere(['pi_upc'=> $this->productname]);
return $dataProvider;
}
}
You could use this way for sending the value of the model to your action
<?php $form = ActiveForm::begin([
'action' => ['your_action'],
'method' => 'your_method ', /// get or post
]); ?>
<?= $form->field($model, 'productname')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
once submit you cant get the value in the normale yii2 way
you can see this for more .. http://www.yiiframework.com/doc-2.0/guide-input-forms.html
for the second Model that don't have the same realetd model and filed as the first you should use
// in $get try retrive the content of $get (in this case i related your yourModel1)
$get = Yii::$app->request->get(['yourModel1'])
// and the use the value for searching in your model2 with the proper value
// obviously you should adatp the name in this sample with the proper ones
$searchModel2 = new PuritemsbdtSearch();
$dataProvider2 = $searchModel2->search(['YourModelSearch2Name'=>['yourAttributeYouNeed'=>$get['productname']]]);

Yii2 update a record based on form in a view file

I tried to update one field of record based on value in a form. The form are placed within a modal in a view file.
view
Modal::begin([
'header' => '<h3>Update Payment Reference</h3>',
'toggleButton' => ['label' => 'Pay','class' => 'btn btn-success'],
]); ?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'pcpayreference')->textInput(['maxlength' => true]) ?>
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php Modal::end();
But I have no idea how to pass those value to my controller so it can update whatever the user have input and submitted.
Controller
public function actionPay($id)
{
$model = Purchase::findOne($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->pcstatus = 'Paid';
$model->pcpaydate = date('Y-m-d H:i:s');
$model->save();
return $this->redirect(['view', 'id' => $model->pcid]);
}
}
I'm new to Yii framework. Any help is much appreciated.
EDIT
The only thing I want to do is to update only this field (current record/view) into database instead of update the whole field.
You must set action in your form with id, it will work
Modal::begin([
'header' => '<h3>Update Payment Reference</h3>',
'toggleButton' => ['label' => 'Pay','class' => 'btn btn-success'],
]); ?>
<?php $form = ActiveForm::begin([
'action' => ['controller/pay','id'=>$id],
]); ?>
<?= $form->field($model, 'pcpayreference')->textInput(['maxlength' => true]) ?>
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php Modal::end();
I think this is the problem regarding csrf validation, just make sure in your config about enableCsrfValidation :
just put this function in your controller
public function beforeAction($action) {
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
Let me know please.

yii2 file upload error- Call to a member function saveAs() on null

I've learned a little bit about yii2 framework, but I've got an error which I can't solve. I'm trying to add a image to signup form.
view:
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'voornaam')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'bedrijf') ?>
<?= $form->field($model, 'telefoon') ?>
<?= $form->field($model, 'username')?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
controller
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
model:
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$imageName = $user->username;
$user->file = UploadedFile::getInstance($user,'file');
$user->file->saveAs( 'uploads/'.$imageName.'.'.$model->file->extension );
$user->picture = 'uploads/'.$imageName.'.'.$model->file->extension;
$user->voornaam = $this->voornaam;
$user->bedrijf = $this->bedrijf;
$user->telefoon = $this->telefoon;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
}
I'm getting the error:
Call to a member function saveAs() on null
What did I do wrong?
(I'm using the advanced template).
you should use $this instead of $user or you should add
$user=$this
because simply $user is new instance and it's field are empty !
It looks like you are mentioning wrong file path, you must mention rootpath for save function
for example
$user->file->saveAs(\Yii::getAlias('#webroot').'/uploads/'.$imageName.'.'.$model->file->extension );
I used separate upload function to upload a file and it's worked.
my view
<?php $form = ActiveForm::begin(['id' => 'form-signup','options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, "files")->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
controller
public function actionSignup() {
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
$model->files = \yii\web\UploadedFile::getInstance($model,'files');
if ($model->upload() && $user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
and my model is
//declare variable
public $files;
//add this to your rules
[['files'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg']
//File upload function
public function upload()
{
if ($this->validate()) {
$this->files->saveAs('../web/uploads/' . $this->files->baseName. '.' .$this->files->extension);
$this->picture = '../web/uploads/' . $this->files->baseName. '.' .$this->files->extension;
return true;
} else {
return false;
}
}
public function signup()
{
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->picture = $this->picture;
$user->setPassword($this->password);
$user->generateAuthKey();
if ($user->save()) {
return $user;
}
else{
return null;
}
}
Just sharing you my solution, change the path to uploads folder to ../uploads/
In your model try changing saveAs function as shown below
$user->file->saveAs( '../uploads/'.$imageName.'.'.$model->file->extension );
I am a beginner in yii2, I faced a problem when i tried the file upload code from
https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload,
this solved my problem