how to display default value in dropDownlist - yii2

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)

Related

Save multiples checkboxList

I have a form with a CheckboxList generated through a model "Candidates" and I need to make a vote where the voter can select multiple candidates and record.
How do I 'pick up' the selected candidates and write to the votes table / model ??
Form "votos"
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'candidato_id')->checkboxList(ArrayHelper::map(Candidatos::find()->where(['status' => 1])->orderBy("nome ASC")->all(), 'id', 'nome')); ?>
<?= Html::activeHiddenInput($model, 'eleicao_id', ['value' => 1]) ?>
<?= Html::activeHiddenInput($model, 'cargo_id', ['value' => 1]) ?>
<?= Html::activeHiddenInput($model, 'urna_id', ['value' => 1]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
Model "Votos"
namespace app\models;
use Yii;
class Votos extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'votos';
}
public function rules()
{
return [
[['eleicao_id', 'candidato_id', 'cargo_id', 'urna_id', 'data'], 'required'],
[['eleicao_id', 'candidato_id', 'cargo_id', 'urna_id'], 'integer'],
[['data'], 'safe'],
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'eleicao_id' => 'Eleicao ID',
'candidato_id' => 'Candidato ID',
'cargo_id' => 'Cargo ID',
'urna_id' => 'Urna ID',
'data' => 'Data',
];
}
}
Controller "VotosControllers"
public function actionVotacao()
{
$model = new Votos();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('votacao', [
'model' => $model,
]);
}
Slightly unrelated, but if you haven't already I would strongly suggest making sure you have something like xdebug set up so you can quickly see what your code is doing as you make your changes. Being able to set breakpoints and see what your form has submitted can go a long way to helping you solve a problem like this on your own and the framework becomes less mysterious. With that out of the way, something like the following MIGHT help as far as the controller goes. There is other validation you would want to do as well I should add. Maybe the each validator which you can read up on here. For actionUpdate() you would need to look at deleting all the values that relate to the related id and re-populate with the new ones, checkout deleteAll. Hopefully I don't get smashed too hard for providing this solution which is not a drop in solution.
public function actionVotacao()
{
$model = new Votos();
if (Yii::$app->request->isPost) {
$model->load(Yii::$app->request->post());
if ($model->save()) {
// Save the checkbox values.
if (!empty(Yii::$app->request->post()['Votos']['XXXX'])) { // Your form should give you an idea of what the XXXX should be, xdebug is also your friend.
foreach (Yii::$app->request->post()['Votos']['XXXX'] as $candidato_id) {
$candidato = new Candidato();
$candidato->id = $candidato_id;
if (!$candidato->save()) print_r($candidato->errors);
}
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}

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);

Yii2 insert data from CheckBoxList

In my Form:
<?= GridView::widget([
'id' => 'griditems',
'dataProvider' => $dataProvider,
'columns' => [
'receiver_name',
'receiver_phone',
'item_price',
'shipment_price',
['class' => 'yii\grid\CheckboxColumn'],
],
]); ?>
In my Controller:
public function actionCreate()
{
$model = new Package();
$searchModel = new ShipmentSearch();
$searchModel->shipment_position=1; // الشحنه في مقر الشركة
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if ($model->loadAll(Yii::$app->request->post())){
$select = Yii::$app->request->post('selection');
foreach($select as $id){
$shipment= shipment::findOne((int)$id);
$model->company_id=1;
$model->shipment_id=$shipment->id;
$model->send_from=$shipment->send_from;
$model->send_to=$shipment->send_to;
$model->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'dataProvider'=>$dataProvider,
]);
}
}
I just try this way to insert data as above its works but the data inserted just last one or last CheckBox from the list. I tried to print the id that in foreach and there is more than one id.
That is beacuse you're reusing the same instace for each save() inside of foreach, so you're overwriting the same model over and over. You need to place $model = new Package() inside of foreach:
foreach($select as $id){
$shipment= shipment::findOne((int)$id);
$model = new Package();
$model->company_id=1;
$model->shipment_id=$shipment->id;
$model->send_from=$shipment->send_from;
$model->send_to=$shipment->send_to;
$model->save(false);
}

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 - Search exact value and return result in detailview

I need to put on the page to search by protocol number, and display only one result when the entered protocol number is exactly the same. If possible the results to be shown, it is a DetailView
My model OccurrenceSearch:
public function searchprotocol($params)
{
$query = Occurrence::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'protocol' => $this->protocol,
]);
return $dataProvider;
}
}
My view search:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="occurrence-search">
<?php $form = ActiveForm::begin([
'action' => ['search'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'protocol') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My controller actionSearch() :
public function actionSearch()
{
$searchModel = new OccurrenceSearch();
$dataProvider = $searchModel->searchprotocol(Yii::$app->request->queryParams);
return $this->render('search', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
The guest user can see only the record for its protocol number
The a detailView use model (and not dataProvider) for show the data instance ..
then in you controller you should obtain the model
public function actionSearch()
{
$searchModel = new OccurrenceSearch();
$dataProvider = $searchModel->searchprotocol(Yii::$app->request->queryParams);
$model = $dataProvider->query->one();
return $this->render('search', [
'searchModel' => $searchModel,
//'dataProvider' => $dataProvider,
'model' => $model,
]);
}
But in you view the code proposed don't show a detailView widget .. you should probably add
I decided to use the GRIDVIEW, and so changed the MymodelSearch
if (isset($_GET['AuthorSearch']) && !($this->load($params) && $this->validate())) {
return $dataProvider;
}