Basically, I have a model that I display to standard checkboxlist that have a value :
I got this from my model
echo $model->bundle_numbers;
Array
(
[0] => 1
[1] => 2
[2] => 3
)
So, In controller,
if ($model->load($request->post()) && $model->save()) {
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new OutgoingPipe",
'content' => '<span class="text-success">Create Outgoing Pipe success</span>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
}
Now I wnat to change the array into string format :
So, use beforeSave :
public function beforeSave($insert){
$this->bundle_numbers = implode(",", $this->bundle_numbers);
return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}
In rules, based Gii generator model, I remove string rules
[['bundle_numbers'], 'string', //deleted
But still not success to insert the data.
No errors displayed.
Please advise.
** update **
I can see all errors,
$model->save(false);
$model->getErrors();
Now, I can see, I have a lot of errors in another rule.
By the way, thanks for the help.
public function beforeSave($insert){
if (parent::beforeSave($insert)) {
$this->bundle_numbers = implode(",", $this->bundle_numbers);
return $this->bundle_numbers;
} else {
return false;
}
}
try this
Try if you have some error in load or validate
if ($model->load($request->post()) {
if ($model->save()){
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new OutgoingPipe",
'content' => '<span class="text-success">Create Outgoing Pipe success</span>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
} else {
var_dump('save fail');
var_dump( $model->errors);
}
do like this
<?php
if ($model->load($request->post()) {
$model->bundle_numbers = implode(",", $model->bundle_numbers);
$model->save();
return //wherever you want return
}
Related
i need some help.
I have a Form where i would like to either choose an existing Entity or submit a new one. So i have a Class Dolmetscher (Interpreter for languages) with title, name, surname and language. To create the Form i have a Class InterpreterType with the function
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('anrede', ChoiceType::class, array(
'choices' => array(
'Herr' => 'Herr',
'Frau' => 'Frau'
)
))
->add('vorname')
->add('nachname')
->add('sprache')
->add('dolmetscher', EntityType::class, array(
'class' => 'AppBundle:Dolmetscher',
'placeholder' => 'Dolmetscher wählen',
'label' => 'Dolmetscher',
'choice_value' => 'id',
'choice_label' => function ($dolmetscher) {
return $dolmetscher->getAnrede() . ' ' .
$dolmetscher->getVorname() . ' ' .
$dolmetscher->getNachname();
},
'mapped' => false,
))
->add('select', SubmitType::class, array(
'label' => 'Übernehmen',
'attr' => array(
'class' => 'btn btn-default',
'formnovalidate' => 'formnovalidate'
)
))
->add('save', SubmitType::class, array(
'label' => 'OK',
'attr' => array(
'style' => 'float: right',
'class' => 'btn btn-default'
)
))
->add('reset', SubmitType::class, array(
'label' => 'Zurücksetzen',
'attr' => array(
'style' => 'float: right; margin-right: 10px',
'class' => 'btn btn-warning',
'formnovalidate' => 'formnovalidate'
)
));
}
So i have a selection with Entities, which is working, with a 'select' Button and Form fields for a new Dolmetscher with a 'save' Button. Also a 'reset' Button
My Controller Class looks like
/**
* #Route("/u01/5", name="u1_5")
*/
public function dolmetscherAction(Request $request) {
$session = $this->get("session");
var_dump($session->get("foo"));
if (!$session->get("dolmetscher")) {
$dolmetscher = new Dolmetscher();
} else {
$dolmetscher = $session->get("dolmetscher");
}
$dolmetscherForm = $this->createForm(DolmetscherType::class, $dolmetscher);
$dolmetscherForm->handleRequest($request);
if ($dolmetscherForm->get('select')->isClicked()) {
$dolmetscher = $dolmetscherForm->get('dolmetscher');
$session->set("dolmetscher", $dolmetscher);
return $this->redirectToRoute('u1_5');
}
if ($dolmetscherForm->get('reset')->isClicked()) {
$dolmetscher = new Dolmetscher();
$session->set("dolmetscher", $dolmetscher);
return $this->redirectToRoute('u1_5');
}
if ($dolmetscherForm->get('save')->isClicked() && $dolmetscherForm->isSubmitted() && $dolmetscherForm->isValid()) {
$dolmetscher = $dolmetscherForm->getData();
$session->set("dolmetscher", $dolmetscher);
return $this->redirectToRoute('homepage');
}
return $this->render('urkunden/u01/5.html.twig', [
'form' => $dolmetscherForm->createView(),
'page_title' => 'U01'
]);
}
I want to put the Dolmetscher from the selection into $_SET for later use ,e.g. persist in DB, which works fine for a new Dolmetscher but not for my selection. I get an Exception
Serialization of 'Closure' is not allowed
I'm not sure if I'm doing this right at all (I have some OneToMany Relations and wanted to have a view for each Entity/Form and persist everything at once at the end so that i don't have only a Dolmetscher in my DB when the user quits in mid process)
I also thought it might be possible to populate the Form fields from the selection which I couldn't get to work. Can someone please help me, i would appreciate it.
This part of code is probably the origin of your problems :
if ($dolmetscherForm->get('select')->isClicked()) {
$dolmetscher = $dolmetscherForm->get('dolmetscher'); <------ this one
$session->set("dolmetscher", $dolmetscher);
return $this->redirectToRoute('u1_5');
}
you are trying to serialize a form object which contains a closure. Closure can not be serialized ( visit this link for more insights Exception: Serialization of 'Closure' is not allowed )
If you dump $dolmetscher variable you will probably get a form object not the entity you want. try to replace the line :
$dolmetscher = $dolmetscherForm->get('dolmetscher');
with :
$dolmetscher = $dolmetscherForm->get('dolmetscher')->getData();
I have two models in a form.
One model is a master, and one model is representated as junction table (model).
Desc :
request_table : $model,
link_req_tipe : $modelLinkReqTipe;
My goal is,
I save the $model, then I get the $model->id
I batch insert to link_req_item
id_request = $model->id and id_tipe = modelLinkReqTipe->id_tipe
Here it is the php :
_form.php (just example, because a lot of many input form)
<?= $form->field($model, 'karyawan_id')->dropDownList(
ArrayHelper::map(Karyawan::find()->all(), 'id', 'first_name'), ['prompt' => 'Select Karyawan'])
?>
<?= $form->field($modelLinkReqTipe, 'id_tipe')->checkBoxList(ArrayHelper::map(TipeRequest::find()->all(), 'id', 'nama_tipe'));
?>
RequestController
if ($model->load($request->post()) && $modelLinkReqTipe->load(Yii::$app->request->post())) {
$valid = $model->validate();
$valid = $modelLinkReqTipe->validate() && $valid;
if ($valid) { ## Check validate : true
$transaction = Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelLinkReqTipe as $index => $modelLinkReqTipe ) {
if ($flag === false) {
break;
}
$modelLinkReqTipe->id_request = $model->id;
if (!($flag = $modelLinkReqTipe->save(false))) {
break;
}
}
}
if ($flag) {
$transaction->commit();
} else {
$transaction->rollBack()
}
}
catch (\Exception $e) {
$transaction->rollBack();
}
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new Request",
'content' => '<h1 class="text-success">Success</h1>,
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
}else{ ## Check validate : false
return [
'title' => "Create New Request",
'content' => $this->renderAjax('create', [
'model' => $model,
'modelLinkReqTipe' => (empty($modelLinkReqTipe)) ? new LinkReqTipe() : $modelLinkReqTipe,
'modelLinkReqItem' => (empty($modelLinkReqItem)) ? [new LinkReqItem] : $modelLinkReqItem,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
Now, validation is in trouble,
it always return false in submit.
Please Advise.
There are many ways to resolve this issue. I think the best way to make sure that $modelLinkReqTipe's attribute id_request is not taken into account upon validation is to provide validate() function with array of attributes you want to validate: validate(['id_tipe'])
ActiveQuery doesn't select map.src_fin_position_id column
$query = FinancePossibleFinPositions::find()
->select (['dst.row_num', 'dst.src_value', 'map.src_fin_position_id'])
->from('finance.possible_fin_positions dst')
->leftJoin('finance.fin_pos_mapping map','map.map_fin_position_id = dst.possible_fin_positions_id')
->leftJoin('finance.possible_fin_positions src','src.possible_fin_positions_id = map.src_fin_position_id AND src.possible_fin_docs_id = :possible_fin_docs_id',[":possible_fin_docs_id"=> 95])
->where('dst.possible_fin_docs_id=:possible_fin_docs_id', [":possible_fin_docs_id"=> 88])
->orderBy('dst.row_num')
->all();
gives
array(2) {
["row_num"]=>
string(4) "1000"
["src_value"]=>
string(18) "My value"
}
although
$query = (new \yii\db\Query())
->select(["dst.row_num", "dst.src_value", "map.src_fin_position_id"])
->from('finance.possible_fin_positions dst')
->join('LEFT JOIN','finance.fin_pos_mapping map','map.map_fin_position_id = dst.possible_fin_positions_id')
->join('LEFT JOIN','finance.possible_fin_positions src','src.possible_fin_positions_id = map.src_fin_position_id AND src.possible_fin_docs_id = :possible_fin_docs_id',[":possible_fin_docs_id"=> $fin_doc])
->where('dst.possible_fin_docs_id=:possible_fin_docs_id', [":possible_fin_docs_id"=> $main_fin_doc])
->orderBy('dst.row_num')->all();
gives the result I need to get with ActiveQuery
array(3) {
["row_num"]=>
string(4) "1000"
["src_value"]=>
string(18) "My value"
["src_fin_position_id"]=>
int(3426)
}
I would use \yii\db\Query() but when I fill tabular form with this array the $_POST is empty.
Does anyone know how to solve this issue?
UPDATE
Simpler example
form.php
<div class="col-md-6">
<?php
$form = ActiveForm::begin(['id'=>'post-multiple','action' => ['submit-posts']]);
echo TabularForm::widget([
'form' => $form,
'dataProvider' => $dataProvider,
'serialColumn' => false,
'actionColumn' => false,
'checkboxColumn' => false,
'attributes' => [
'post_id' => ['type' => TabularForm::INPUT_STATIC, 'columnOptions'=>['hAlign'=>GridView::ALIGN_CENTER]],
'post_title' => ['type' => TabularForm::INPUT_STATIC],
'post_description' => ['type' => TabularForm::INPUT_TEXT, 'options' => ['class' => 'droppable']],
],
'gridSettings' => [
'floatHeader' => true,
'panel' => [
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> Manage Books</h3>',
'type' => GridView::TYPE_PRIMARY,
'after'=>
Html::a(
'<i class="glyphicon glyphicon-plus"></i> Add New',
'#',
['class'=>'btn btn-success']
) . ' ' .
Html::a(
'<i class="glyphicon glyphicon-remove"></i> Delete',
'#',
['class'=>'btn btn-danger']
) . ' ' .
Html::submitButton(
'<i class="glyphicon glyphicon-floppy-disk"></i> Save',
['class'=>'btn btn-primary']
)
]
]
]);
ActiveForm::end(); ?>
</div>
Controllers
public function actionTabular()
{
// $query = (new \yii\db\Query())
// ->select("post_id, post_title, post_description")
// ->from('posts');
$query = Posts::find()->indexBy('post_id');
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
]);
return $this->render('tabular', [
'dataProvider'=>$dataProvider,
]);
}
public function actionSubmitPosts()
{
var_dump(Yii::$app->request->post());exit;
}
$query = Posts::find()->indexBy('post_id');
<input type="text" id="posts-40-post_description" class="droppable form-control ui-droppable" name="Posts[40][post_description]" value="tre">
$_POST is not empty
$query = (new \yii\db\Query())
->select("post_id, post_title, post_description")
->from('posts');
<input type="text" id="-28-post_description" class="droppable ui-droppable" name="[28][post_description]" value="tre">
$_POST is empty
Both queries fill the form correctly
The difference is inputs names. But I don't need to validate this form and it is strange why
[28][post_description] doesn't go into $_POST.
From Yii 2 Guide:
Note: If you call select() while eagerly loading relations, you have to make sure the columns referenced in the relation declarations are being selected. Otherwise, the related models may not be loaded properly. For example,
$orders = Order::find()->select(['id', 'amount'])->with('customer')->all();
// $orders[0]->customer is always null.
// To fix the problem, you should do the following:
$orders = Order::find()
->select(['id', 'amount', 'customer_id'])
->with('customer')->all();
I figured this out.
For yii\db\Query
I should have used
<?= Html::beginForm(['save-posts','method'=>'post']); ?>
I have a problem on getting all the selected values/data Yii2 Gridview using checkboxColumn.
I can only get one of the value in the grid using this code:
'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' => function($model, $key, $index, $widget) {
return ['value' => $model['item_id'] ];
},
Need some suggestions on how can I get all the values in the grid...
Here is my Code Code snippet Controller/View:
Controller:
public function actionBulk(){
$action=Yii::$app->request->post('action');
$selection=(array)Yii::$app->request->post('selection');
print_r($selection);
}
View:
<?=Html::beginForm(['transjournal/bulk'],'post');?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'bordered'=>true,
'striped'=>true,
'condensed'=>true,
'hover'=>true,
'export' => false,
'showOnEmpty' => false,
'panel'=>[
'after'=>Html::submitButton('<i class="glyphicon glyphicon-plus"></i> Posted', ['class' => 'btn btn-success']),
],
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' => function($model, $key, $index, $widget) {
return ['value' => $model['item_id'] ];
},
],
'item_id',
'description',
],
]);
?>
<?= Html::endForm();?>
Here is my attachment:
This is the GridView
This is the Result in the GridView (Selected Data only returns item_id)
How can I return both item_id and description?
Issue with your code 'checkboxOptions' =>, can you remove it?
<?=Html::beginForm(['controller/bulk'],'post');?>
<?=Html::dropDownList('action','',[''=>'Mark selected as: ','c'=>'Confirmed','nc'=>'No Confirmed'],['class'=>'dropdown',])?>
<?=Html::submitButton('Send', ['class' => 'btn btn-info',]);?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
...
],
]); ?>
<?= Html::endForm();?>
In Controller:
public function actionBulk(){
$action=Yii::$app->request->post('action');
$selection=(array)Yii::$app->request->post('selection');//typecasting
foreach($selection as $id){
$model = Post::findOne((int)$id);//make a typecasting
//do your stuff
$model->save();
// or delete
}
}
basically, i am using yii's CheckboxColumn:
<?php
namespace common\grid;
class CheckboxColumn extends \yii\grid\CheckboxColumn {
public $headerOptions = ['class' => 'text-center', 'style' => 'width: 5em'];
public $contentOptions = ['class' => 'text-center'];
}
?>
then i wrote a jquery plugin for triggering operations with selected items, plus custom Actions and so on, here the relevant javascript code, where options.grid is the id/selector for your grid, e.g. '#grid':
var selection = [];
$(options.grid + ' input:checkbox[name="selection[]"]:checked').each(function() {
selection.push($(this).val());
});
so var selection contains an array with my item ids. length is:
selection.length
I have normal login form which work great. Now I'm trying to make second simple step when user enter his password and user name and if they are correct to redirect him to new page where he must enter pass phrase in order to continue.
I'm not sure if this is correct what I have make so far. This is my route:
Route::get ('/users/login', ['uses' => 'UsersController#login', 'before' => 'guest']);
Route::post('/users/login', ['uses' => 'UsersController#loginSubmit', 'before' => 'guest']);
// new
Route::get('/users/auth', ['uses' => 'UsersController#loginAuth', 'before' => 'guest']);
Route::post('/users/auth', ['uses' => 'UsersController#loginSubmitAuth', 'before' => 'auth|csrf']);
This is my auth.blade.php
{{ Form::open(['class' => 'form-horizontal']) }}
<div class="form-group"> {{ Form::textarea('key', ['class' => 'form-control', 'id' => 'key', 'autocomplete' => 'off']) }} </div><br/>
<hr />
<div class="row">
<button type="submit" class="btn btn-primary col-xs-4 col-xs-offset-4">Login</button>
</div>
<hr />
{{ Form::close() }}
This is my controller
public function login() {
return View::make('site.users.login');
}
public function loginSubmit() {
$validatorRules = array(
'captcha' => 'required|captcha',
'username' => 'required|alpha_dash',
'password' => 'required|min:6'
);
Input::merge(array_map('trim', Input::all()));
$validator = Validator::make(Input::all(), $validatorRules);
if ($validator->fails()) {
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
$user = User::where('username', Input::get('username'))->first();
if (!$user) {
$validator->messages()->add('username', 'Invalid login or password.');
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
if (!Hash::check(Input::get('password'), $user->password)) {
$validator->messages()->add('username', 'Invalid login or password.');
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
//$user->last_login = \Carbon\Carbon::now();
//$user->save();
//Session::put('user', ['user_id' => $user->user_id]);
return Redirect::to('/users/auth');
}
public function loginAuth() {
return View::make('site.users.auth');
}
public function loginSubmitAuth() {
$validatorRules = array(
'key' => 'required',
'captcha' => 'required|captcha'
);
Input::merge(array_map('trim', Input::all()));
$validator = Validator::make(Input::all(), $validatorRules);
if ($validator->fails()) {
return Redirect::to('/users/auth')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
$user = User::where('key', Input::get('key'))->first();
if (!$user) {
$validator->messages()->add('key', 'Invalid Key.');
return Redirect::to('/users/auth')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
$user->last_login = \Carbon\Carbon::now();
$user->save();
Session::put('user', ['user_id' => $user->user_id]);
return Redirect::to('/');
}
Current error is 'Array to string conversion'
Any help is appreciated. Thank's
The issue of second parameter in Form::textarea you need to pass null to make it empty in second parameter and array in third parameter like,
<div class="form-group">
{{ Form::textarea('key',null, ['class' => 'form-control', 'id' => 'key', 'autocomplete' => 'off']) }}
</div><br/>
You can refer to Creating a Textarea Input Field
Can you try if this fixes your problem:
{{ Form::textarea('key', null, ['class' => 'form-control', 'id' => 'key', 'autocomplete' => 'off']) }}
It's this way because the value argument comes second and it is mandatory in difference with the third one which is optional