Yii2 insert data from CheckBoxList - yii2

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

Related

Save multiple selections from a listbox - Yii2

I have made a Listbox depend on a dropDownList, when selecting an option from the dropDownList brings me a list of data that is added to the Listbox, it works to save a single option but the problem occurs when trying to save multiple selections, I cannot save more than 1 option, I have tried to add a foreach in my controller but it throws an error.
DropDownList
<?php echo $form->field($model, 'group_id')->widget(Select2::classname(), [
'data' => $seccion->lgrupo, //I get the group list
'size' => Select2::MEDIUM,
'theme' => Select2::THEME_BOOTSTRAP,
'options' => [
'placeholder' => '-- '.Yii::t('backend', 'Select').' --',
'onchange'=>'
$.post( "lists?id="+$(this).val(), function( data ) {//I get the list of people registered in the group and send it to the listbox
$( "select#assignment-user_id" ).html( data );
});',
],
'pluginOptions' => [
'allowClear' => true,
],
'addon' => [
'prepend' => [
'content' => Html::icon('building')
],
]
]); ?>
ListBox
<?php echo $form->field($model2, 'users_id')->listBox([] ,['multiple'=>true,'size'=>17]
); ?>
Groups Controller
public function actionCreate()
{
$model = new Groups();
$model2 = new Assignment();
$seccion = new Group();
if ($model->load(Yii::$app->request->post()) && $model2->load(Yii::$app->request->post())) {
if ($model->save(false)) {
foreach ($model2->users_id as $i => $as) {
$as->assign_group_id = $model->id_group_list;
if ($model2->save()) {
} else {
// error in saving model
}
}
return $this->redirect(['view', 'id' => $model->id_group]);
}
}
return $this->render('create', [
'model' => $model,
'model2' => $model2,
'seccion' => $seccion,
]);
}
Tables
I hope your can tell me what I'm doing wrong.
public function actionCreate()
{
$model = new Groups();
$model2 = new Assignment();
$seccion = new Group();
if ($model->load(Yii::$app->request->post()) && $model2->load(Yii::$app->request->post())) {
if ($model->save(false)) {
foreach ($model2->users_id as $user_id) {
$assignmentModel = new Assignment();
$assignmentModel->user_id= $user_id;
$assignmentModel->assign_group_id = $model->id_group_list;
//$assignmentModel->area= ''; //if you want to set some value to these fields
//$assignmentModel->assignment= '';
if ($assignmentModel->save()) {
} else {
// error in saving model
}
}
return $this->redirect(['view', 'id' => $model->id_group]);
}
}
return $this->render('create', [
'model' => $model,
'model2' => $model2,
'seccion' => $seccion,
]);
}

how insert Initial value in yii2 ckeditor

<?=
$form->field($model, 'template')->widget(CKEditor::className(), [
'options' => ['rows' => 100],
'preset' => 'full',
'value'=>'<p>Incercam sa editam</p>',
])->label(true)
?>
This is my code
I need to set initial value in editor
You should assign a value in your field template eg in you controller/create
public function actionCreate()
{
$model = new YourModel();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
$model->template ="your initila value ....... text "
return $this->render('#common/views/antigone-contribuente/create', [
'model' => $model,
]);
}
}
once you have assigne to youe $model->template the value you need yuo should see this in your editor in view

How to show only fix records in the yii2 gridview

I am working with yii2 Framework. I want only few records in gridview where status = 1 in databaseenter image description here
This is the screen shot of gridview I want only highlighted records whose status is 1
This Code of view page is -:
<p>All Issued Devices are Highlighted </p>
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel frontend\models\DeviceTrackerSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
//$this->title = 'Tracked Devices';
//$this->params['breadcrumbs'][] = $this->title;
?>
<b style="font-size: 30px;">ALL ISSUED DEVICES ARE HIGHLIGHTED </b>
<div class="device-tracker-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'rowOptions'=>function($model)
{
if($model->status == '1')
{
return ['class'=>'info'];
}
else
{
return ['class'=>'default'];
}
},
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'devices_device_id',
'value'=>'devicesDevice.device_name'
],
//'id',
//'devices_device_id',
'user_first_name',
'user_last_name',
'email_address:email',
// 'user_department',
'assign_date',
'return_date',
//'status',
//'Issued_by',
[
'attribute'=>'Issued_by' ,
'value'=>'issuedBy.first_name'
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Please Tell me how to solve the problem?
Controller action is-
public function actionReturn()
{
// echo "welcome";die;
if(isset(Yii::$app->user->identity->user_type))
{
$status = Yii::$app->user->identity->user_type;
if($status == 1)
{
$this->layout = 'headerLayoutSuperadmin';
$searchModel = new DeviceTrackerSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index1', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
else
{
$this->layout = 'headerLayout';
$searchModel = new DeviceTrackerSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index1', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
else
{
return $this->redirect(array('site/login'));
}
}
sql search models-:
<?php
namespace frontend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\DeviceTracker;
/**
* DeviceTrackerSearch represents the model behind the search form about `frontend\models\DeviceTracker`.
*/
class DeviceTrackerSearch extends DeviceTracker
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id', 'status', 'Issued_by'], 'integer'],
[['user_first_name', 'devices_device_id', 'user_last_name', 'email_address', 'user_department', 'assign_date', 'return_date'], 'safe'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = DeviceTracker::find();
//$query = DeviceTracker::findAll('status=>1');
// print_r($query);die;
//echo $query;die;
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->joinWith('devicesDevice');
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
//'devices_device_id' => $this->devices_device_id,
'assign_date' => $this->assign_date,
'return_date' => $this->return_date,
'status' => $this->status,
'Issued_by' => $this->Issued_by,
]);
$query->andFilterWhere(['like', 'user_first_name', $this->user_first_name])
->andFilterWhere(['like', 'user_last_name', $this->user_last_name])
->andFilterWhere(['like', 'email_address', $this->email_address])
->andFilterWhere(['like', 'user_department', $this->user_department])
->andFilterWhere(['like', 'devices.device_name', $this->devices_device_id]);
return $dataProvider;
}
}
in your search model, update the query to suit the output you want to pass to view.
something like this for the current condition i.e. you want to display only those rows whose status is 1
so,
$query->andFilterWhere([
'id' => $this->id,
//'devices_device_id' => $this->devices_device_id,
'assign_date' => $this->assign_date,
'return_date' => $this->return_date,
'status' => 1, // **this is where you are filtering the data with status == 1**
'Issued_by' => $this->Issued_by,
]);
and brief explanation of flow is
your controller which calls the dataProvider, gives you data that you pass to view and then eventually to gridView
the data is stored in mysql tables, so whatever data you want to send to view you need to query it in the searchModel in dataProvider's query
return dataProvide to controller > view > gridWidget

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

display the index for which data is owned by the user who logged in

how to display user data is logged in the index , while other user data does not appear , only users who log you appear
n2 should only user data that appears
public function actionIndex()
{
$searchModel = new CreateBookingsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$model = new Kasbon();
$data = Kasbon::findOne($id);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
'data' => $data,
]);
}
In your Search model, add a filter in the search function:
$query->andFilterWhere(['user_id' => Yii::$app->user->identity->id]);
public function actionIndex(){
$searchModel = new CreateBookingsSearch();
$session = yii::$app->session;
$id = $session->get('user_id');
$dataProvider = $searchModel->search($id);
return $this->render('index',['searchModel'=>$searchModel, 'dataProvider'=>$dataProvider]);
}