In Yii2 I have ActiveForm with checkbox field. In mysql database it is tinyint(1) column that can be NULL.
I need unchecked checkbox (false value) to be saved as NULL in database. Currently when checkbox is unchecked, it is saved as (int) 0.
What is the proper way to save false value as NULL?
Here is the model:
class ProductToProductCategory extends ActiveRecord {
public function rules()
{
return [
['product_category_id', 'required'],
['product_category_id', 'integer'],
['is_main', 'boolean'],
];
}
}
Here is the view:
<?= $form->field($model, "is_main")->checkbox() ?>
public function rules()
{
return [
['product_category_id', 'required'],
['product_category_id', 'integer'],
['is_main', 'boolean'],
['is_main', 'filter', function ($value) {
// return value you need
return $value ?: null;
}, 'skipOnError' => true],
];
}
Never tried it but you should be able to do it implementing the beforeSave method of the saved model.
public function beforeSave($insert)
{
if (!parent::beforeSave($insert)) {
return false;
}
if( $this->scenario == "strangeNullScenario" ) {
if( empty( $this->FIELD ) ) {
$this->FIELD = null;
}
}
return true;
}
Just pass uncheck option
<?= $form->field($model, "is_main")->checkbox(['uncheck' => null]) ?>
Related
I have an ActiveForm in my _form view:
<?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'isInternal')->checkbox() ?> <?php ActiveForm::end(); ?>
('isInternal' is a boolean)
If the checkbox is selected I want to show another checkbox:
$form->field($model, 'activateReminder')->checkbox();
Is there a possibility? Maybe with JavaScript like this?
<?= $form->field($model, 'isInternal')->checkbox(['onclick' =>
'showInternDetails()']) ?>
<script>
function showInternDetails() {
$model->isInternal = 1;
}
</script>
<?php
if($model->isInternal == true)
{
$form->field($model, 'activateReminder')->checkbox();
}
?>
You can do that by JS:
<?php
$this->registerJs(
"$('#myBox').on('change', function() { if($(this).is(":checked")){// Display your input...}else {// hide it} });",
View::POS_READY
);
You can use the when and whenClient options inside the model rules that you have declared so that it works when creating or updating both on the model end to require and show error to the user that he needs to select the value for the check-box and also to show and hide the activateReminder at the same time.
So go inside the model that you are using with this form and add a rule like below.
public function rules(){
return [
[['activateReminder'],'required','when'=>function($model){return ($model->isInternal);},
'whenClient'=>'function(attribute,value){
if($("#'.\yii\helpers\Html::getInputId($this, 'isInternal').'").val()===1){
$("#'.\yii\helpers\Html::getInputId($this, 'activateReminder').'").show();
return true;
}else{
$("#'.\yii\helpers\Html::getInputId($this, 'activateReminder').'").hide();
}
}']
];
}
Thank you for your answers!!
I have solved it as follows:
function isInternalOnClick(){
$('#isInternalCheckbox').on('change',function(){ showOrHideActivateReminder();});
}
function showOrHideActivateReminder() {
if($('#isInternalCheckbox').is(':checked'))
{
$('#hiddenActivateReminder').show()
}
else{
$('#hiddenActivateReminder').hide();
}
}
$(document).ready(function() {
<?php
if($model->isInternal)
{
echo "
showOrHideActivateReminder();
";
}
?>
});
I have a checkbox in a gridview Yii2 like this,
[
'class' => 'kartik\grid\CheckboxColumn',
'width' => '20px',
'checkboxOptions' => function ($model, $key, $index, $column) {
return [
'value' => trim($model->vessel),
];
}
],
Then to get all the value checkbox in yii2, I use this button
Html::a('<i class="glyphicon glyphicon-print"></i> Print All',
["print-all-based-date"],
[
"class" => "btn btn-success",
'role' => 'modal-remote-bulk',
])
But when in my controller that handle the the action,
public function actionPrintAllBasedTanggal()
{
$request = Yii::$app->request;
$get = $request->get();
print_r($get);
die();
I get :
Array
(
[r] => iwwi/incoming/print-all-based-tanggal
[KMTC_HOCHIMINH,OOCL_NAGOYA] =>
[_] => 1495123320863
)
What it means [KMTC_HOCHIMINH,OOCL_NAGOYA] =>,
I check in html, the checkbox is named selection[] ?
I need this : KMTC_HOCHIMINH,OOCL_NAGOYA
to get continue my app.
Please advise.
Thanks
may be you can use jquery for the solution.
example :
$(document).on('click','#ceklist_all',function(){
if ($(this).is(':checked')) {
$('.ceklist_child').attr('checked',true);
your_variable = [];
$('.ceklist_child:checked').map(function(key,val) {
if(this.checked) {
your_variable[key] = this.value;
}
}).get();
}
});
so,. you can use the your_variable and use the ajax for submit..
$.ajax({
type: 'get',
url: your_url,
data: {
'your_variabel_to_post' : your_variable
},
success: function(data){
// success function
},
error: function(data){
if(data.responseText)
alert(data.responseText);
},
});
CMIIW,.
just the optional solution. heheh
<?php
echo $this->Form->postLink(
'',
array('action' => 'edit',$comment['id'],
'controller'=>'Comments',
),array('class'=>'glyphicon glyphicon-edit','onClick'=>'showDialog()') )?>
This is comment edit icon that I create when I click the Icon the
model dialog box is pop up .
<div id="overlay" onClick="hideDialog()"></div>
<div id="dialog">
<h2>Edit Comment <span onClick="hideDialog()">×</span></h2>
<?php echo $this->Form->create('Comment',array('enctype'=>'multipart/form-data'));?>
<?php echo $this->Form->input('Comment.comment',array('class'=>'form-control'));
echo $this->Form->end('Save');
?>
</div>
<script>
function showDialog() {
document.getElementById("overlay").style.display = "block";
document.getElementById("dialog").style.display = "block";
}
function hideDialog() {
document.getElementById("overlay").style.display = "none";
document.getElementById("dialog").style.display = "none";
}
</script>
The dialog to edit the comment but The comment just add as a another
comment but not edit . Why? Here is the Edit Function in my controller
public function edit($id = null) {
$user_id=$this->Auth->user('id');
$comment_fields=$this->Comment->findById($id);
$comment_id=$comment_fields['Comment']['id'];
$comment = $this->Comment->findById($id);
if (!($user_id == $comment_fields['Comment']['user_id'])) {
$this->Flash->error(__('Unable to edit your post.'));
return $this->redirect(array('action'=>'../posts/view',$comment_fields['Comment']['foreign_id']));
}
if (!$comment)
{
$this->redirect(array('action'=>'../posts/view',$comment_fields['Comment']['foreign_id']));
}
if ($this->request->is(array('post', 'put'))) {
if($this->Comment->id = $id)
{
if ($this->Comment->save($this->request->data)) {
$this->Flash->success(__('Your Comment has been updated.'));
$this->redirect(array('action'=>'../posts/view',$comment_fields['Comment']['foreign_id']));
}
}else{
$this->Flash->error(__('Unable to update your Comment.'));
}
}
if (!$this->request->data) {
$this->request->data = $comment;
}
}
You are trying to assign a value in the if's conditional statement part!
if($this->Comment->id = $id) : This is wrong because that part is for checking conditions.
The solution to your problem would be:
$this->Comment->id = $id;
if ($this->Comment->exists()) {
if ($this->Comment->save($this->request->data)) {
$this->Flash->success(__('Your Comment has been updated.'));
$this>redirect(array('action'=>'../posts/view',$comment_fields['Comment']['foreign_id']));
}
}
else {
$this->Flash->error(__('Unable to update your Comment.'));
}
I am trying to group by Year in cakephp3. I am able to get data using
following way, but it's not still grouped by year(The way I want.)
$query = $this->Alerts->query();
$year = $query->func()->year([
'added_on' => 'literal'
]);
$month = $query->func()->monthname(['added_on' => 'literal']);
$monthAlertsCount = $query->func()->count($month);
$data = $query
->select([
'year' => $year,
'month' => $month,
'count' => $monthAlertsCount
])
->group($year)
->group($month);
$status = "success";
$this->set('response', $status);
$this->set('year', $data);
$this->set('_serialize', ['response','year']);
Current output is as follows:
{
"response":"success",
"year":[
{
"year":"2013",
"month":"November",
"count":"1"
},
{
"year":"2014",
"month":"February",
"count":"2"
},
{
"year":"2014",
"month":"January",
"count":"3"
},
{
"year":"2015",
"month":"December",
"count":"6"
},
{
"year":"2015",
"month":"February",
"count":"3"
},
{
"year":"2015",
"month":"January",
"count":"4"
},
{
"year":"2016",
"month":"January",
"count":"83"
}
]
}
Expected Output:
{
"response":"success",
"year":[
{
"2013":[
{
"month":"November",
"count":"1"
}
],
"2014":[
{
"month":"February",
"count":"2"
},
{
"month":"January",
"count":"3"
}
],
"2015":[
{
"month":"December",
"count":"6"
},
{
"month":"February",
"count":"3"
},
{
"month":"January",
"count":"4"
}
],
"2016":[
{
"month":"January",
"count":"83"
}
]
}
]
}
Can anybody help me get the expected output in cakephp3?
Use the collection method groupBy() - remember, queries are collection objects (kind of)!
$data = $query
->select([
'year' => $year,
'month' => $month,
'count' => $monthAlertsCount
])
->group($year)
->group($month)
->groupBy('year');
That will create the desired grouped structure, however it won't remove the year field from the individual rows, if you want them removed, use a mapper, like
// ...
->groupBy('year')
->map(function ($rows) {
foreach ($rows as &$row) {
unset($row['year']);
}
return $rows;
});
See also
Cookbook > Collections > Collection::groupBy()
Cookbook > Collections > Collection::map()
Cookbook > Database Access & ORM > Query Builder > Queries Are Collection Objects
I'm working on a symfony2 project.
I send from my controller to twig, an array of arrays of objects.
My array is nicely set, and got the values I want.
But when I try to access to these datas on twig, I can't...
My twig looks like {{ myarray.1.0.getFichier() }}
But, twig didn't call getFichier method of myarray.1.0.
Here is what twig responses to me : Item "getFichier" for "Array" does not exist in CDUserBundle:Prof:edit_session.html.twig at line 74
Edit :
dump(myarray.1.0) shows nothing, dump(myarray) shows nothing.
But dump() show a blank page...
Edit² :
Here is my controller
return $this->render('CDUserBundle:Prof:edit_session.html.twig', array(
'erreur' => $erreur,'message' => $message,
'title' => 'C# | Editer session',
'description' => 'keywords description',
'sessionInfo' => $sessionInfo,
'sessionFull' => $sessionFull,
'documents' => $documents,
'videos' => $videos,
'a' => 'showForm',
'vidName' => $videos[0]->getName(),
'vidDMCId'=>$videos[0]->getDMCId(),
'session' => $form->createView(),
'partPath' => $documents[0]->getFichier()
));
My Array is either $documents either $videos
Here is when I create arrays
$videos=array();
if($sessionFull[0]['sess_vid_id']!=NULL) {
if($em->getRepository('CD\ConfigBundle\Entity\Video')->findOneById($sessionFull[0]['sess_vid_id']))
array_push($videos,$em->getRepository('CD\ConfigBundle\Entity\Video')->findOneById($sessionFull[0]['sess_vid_id']));
else
array_push($videos,new Video());
}
else
array_push($videos,new Video());
for($i=0;$i<4;$i++) {
if($sessionFull[$i]['coursVidId']!=NULL) {
$vids=array();
$vidsId=explode(',',$sessionFull[$i]['coursVidId']);
foreach($vidsId as $vidId) {
if($em->getRepository('CD\ConfigBundle\Entity\Video')->findOneById($vidId))
array_push($vids,$em->getRepository('CD\ConfigBundle\Entity\Video')->findOneById($vidId));
else
array_push($vids,new Video());
}
array_push($videos,$vids);
}
else
array_push($videos,array(new Video()));
}
$documents=array();
if($sessionFull[0]['sess_doc_id']!=NULL) {
if($em->getRepository('CD\ConfigBundle\Entity\Document')->findOneById($sessionFull[0]['sess_doc_id']))
array_push($documents,$em->getRepository('CD\ConfigBundle\Entity\Document')->findOneById($sessionFull[0]['sess_doc_id']));
else
array_push(new Document());
}
else
array_push($documents,new Document());
for($i=0;$i<4;$i++) {
if($sessionFull[$i]['coursDocId']!=NULL) {
$docs=array();
$docsId=explode(',',$sessionFull[$i]['coursDocId']);
foreach($docsId as $docId) {
if($em->getRepository('CD\ConfigBundle\Entity\Document')->findOneById($docId))
array_push($docs,$em->getRepository('CD\ConfigBundle\Entity\Document')->findOneById($docId));
else
array_push($docs,new Document());
}
array_push($documents,$docs);
}
else
array_push($documents,array(new Document()));
}
Use {{ myarray.1.0.Fichier }} directly