Cakephp how to set checkbox value selected? - cakephp-2.0

I am using checkbox in one of my project.I am giving checkbox code below:
$this->Form->checkbox('ClubOpenDay.status', array("data-on-label" => "Open", "data-off-label" => "Close", "checked" => "checked"), array("empty" => false))
Here,Open is active by default. But in edit mode,if value is set to close,than close will be display.I am unable to do that.I just want,if I get value open from database,it will display open else close by default.Any idea about it?

Well you should get the value from the database as you say and in the view just have an if statement, should look something like this:
if($value == true){
$this->Form->checkbox('ClubOpenDay.status', array("data-on-label" => "Open", "data-off-label" => "Close", "checked" => "checked"), array("empty" => false))
}
else{
$this->Form->checkbox('ClubOpenDay.status', array("data-on-label" => "Open", "data-off-label" => "Close"), array("empty" => false))
}
$value should be a variable that you assing from your controller that has the value true if its open or false if its closed, or maybe not even true or false, a 1 or 0 would do you would only need to change the if statement in your view accordingly
I hope that helps, good luck

You can save your if else time
$checked = ($status == true) ? 'checked' : '';
$this->Form->checkbox('ClubOpenDay.status', array("data-on-label" => "Open", "data-off- label" => "Close", "checked" => $checked), array("empty" => false))

In your Controller you have to write this
public function edit($id){ // for example
//[...]
$this->request->data['ClubOpenDay']['status'] = $db_value;
//$this->request->data['ClubOpenDay']['status'] = 1; // if you want to force a checkbox checked
}
And your checkbox will be automatically checked or unchecked.

Related

How do I validate a checkout form in React?

I am trying to implement a checkout form in React. The form has 4 fields in all: Name, CC Number, CC expiration and CVV. I am using a library that validates each field on unfocus. The validation is triggered by the validationCallback method which takes 3 arguments: field, status, and message. I'd like to key off of the status for each input and only allow submit once each status === true. Here is my code.
constructor(props) {
super(props);
this.state = {
nameOnCard: '',
errorMessage: '',
showLoaderForPayment: '',
collectJs: null,
token: null,
isPaymentRequestCalled: false,
showErrorModal: false,
paymentErrorText: '',
disabled: true,
};
}
I have a disabled property in my state which I'm initially setting to true.
validationCallback: (field, status, message) => {
if (status) {
this.setState({ errorMessage: '' });
} else {
let fieldName = '';
switch (field) {
case 'ccnumber':
fieldName = 'Credit Card';
break;
case 'ccexp':
fieldName = 'Expire Date';
break;
case 'cvv':
fieldName = 'Security Code';
break;
default:
fieldName = 'A';
}
if (message === 'Field is empty') {
this.setState({ errorMessage: `${fieldName} ${message}` });
} else {
this.setState({ errorMessage: `${message}` });
}
}
},
In the above method, I'd like to set disabled to false if each of the field's status===true... Below is the button which I'm setting to be the value of this.state.disabled.
<button
className="continueBtn disabled"
disabled={this.state.disabled}
onClick={this.handleCardSubmit}
>
<span className="fa fa-lock" />
Pay $
{selectedPayment.amount}
</button>
I hope this is enough of the code to help with the issue. I can provide more of the file if need be.
From what i understand, you want to set the button to NOT DISABLED if all the fields are filled properly, i.e. all status are true.
What you can do is maintain a boolean array for each field and update the status in that array, i.e. initialize an array of length = no. of fields (in your case 3) and set all values as false. False depicts that the field hasn't been validated.
this.state = {
statusArray = [false, false, false] // For as many fields
}
Then in validationCallback, set the index as true or false for that field i.e. if the 2nd field status is returned true by your validation library, set statusArray as [false, true, false].
The form will only be validated if all 3 of the values become true. So you can iterate over the array and check if array has all 3 values as true. or you can use the logical AND operator which returns true only if all values are true(the approach which i use below).
For the button,
<button disabled={this.checkDisable()}>
checkDisable = () => {
let temp = this.state.statusArray;
let answer = true;
for(int i=0;i<temp.length;i++)
answer = answer && temp[i];
return answer; // Only returns true if all 3 values are true
}
I hope you get it now.
You need to check 2 things, has the form been touched and are there any errors. I don't know what library you are using but most likely it has a property touched in it, if not add an onFocus to each input field and a touched property in your state. You don't really need a disabled property in your state since its a computed value. Just check on every render if the form has been touched and if there are any errors.
state = {
...,
touched: false,
...
}
handleFocus = () => this.setState({touched: true})
render(){
const disabled = !!(this.state.touched && this.state.errorCode)
return(
...
<input onFocus={this.handleFocus} ... />
...
<button disabled={disabled}
)
}
EDIT:
state = {
...
validInputs: []
}
validationCallback: (field, status, message) => {
if (status) {
this.setState((state) => ({ errorMessage: '', validInputs: [... new Set([...state.validInputs, field])] }));
} else {
...
render(){
const disabled = this.state.length < inputs.length // the number of the input fields
return(
...
<button disabled={disabled} >
...
)

Ag-grid fill row after select in infinite scroll model reactjs

I use ag-grid as infinite scroll model. When i select some row, i check it in BE and after that i want to fill this row as green (in screenshot blue - it's selected row, i want to fill green this row after some action, for example, after click button for checking this row).
I try to set RowClassRules for this way, but it's not worked. But this work before the table waas rendered. After the table was rendered i select row and it's not fill green.
I know about updateData function, but it's not supported in infinite scroll model. Can i do this with another way?
render(){
let cells = this.state.rowIndexWithBadValue;
let cellsImported = this.state.rowIndexAlreadyImported;
return(
...
<AgGridReact
enableColResize={true}
columnDefs={this.state.columnDefs}
rowModelType="infinite"
rowSelection="multiple"
rowDeselection={true}
maxBlocksInCache={2}
suppressRowClickSelection={true}
getRowNodeId={this.state.getRowNodeId}
datasource={this.getDataSource(1000)}
isRowSelectable={this.state.isRowSelectable}
rowClassRules={{
"red-row": function(params) {
return cells.find(e => e === params.node.rowIndex) !== undefined ? true : false;
},
"green-row": function(params) {
return cellsImported.find(e => e === params.node.id) !== undefined ? true : false;
},
}}
onGridReady={this.onGridReady}
onSelectionChanged={this.onSelectionChanged}
/>
...
)
}
State:
this.state = {
columnDefs: this.props.columnDefs,
data: this.props.data,
selectedData: null,
getRowNodeId: function(item) {
let columnIndex = null;
Object.keys(item).map((elem, index) => {
if (elem === item_id) { columnIndex = index; }
});
return Object.values(item)[columnIndex];
},
rowIndexWithBadValue: this.props.rowIndexWithBadValue,
isRowSelectable: function(rowNode) {
return row.find(e => e === rowNode.rowIndex) == undefined ? true :false;
},
jumpButton: true,
selectButton: false,
deselectButton: false,
primaryKey: this.props.primaryKey,
nextBadRow: null,
columnsWithDefaultsvalues: this.props.columnsWithDefaultsvalues,
rowIndexAlreadyImported: this.props.rowIndexAlreadyImported
};
For this case you don't have full solution.
You can make only one: fill this rows, but after rerendering it lose.
So you can only prepare data before first render of table, or you can change source data and rerender table, but in this case you lose all selected rows and you need to set it selected again.

Yii2: save checkbox false as NULL

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]) ?>

KendoUI Grid Checkbox click event

I have data to be displayed in KendoUI grid. There is some boolean data and I want it to be displayed as check boxes. Also, when the user clicks the check box I need to do something so I need the onclick event for each row of data. How do I do this in KendoUI grid? How do I give each check box a different name and fire onclick events? My code:
#(Html.Kendo().Grid((IList<M.TS.DomainModel.C>)ViewData["peoplefind"])
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.FirstName);
columns.Bound(p => p.LastName);
columns.Bound(p => p.User).Title("Email");
columns.Bound(p => p.City);
columns.Bound(p => p.TimeStamp).Title("Testdate").Format("{0:MM/dd/yyyy}");
columns.Command(command => command.Custom("Info").Click("showDetails")).Title("Info");
columns.Bound(p => p.CheckOK).ClientTemplate(
"<input type='checkbox' value= '#= CheckOK #' " +
"# if (CheckOK) { #" +
"checked='checked'" +
"# } #" +
"/>"
);
})
.Sortable()
.Scrollable(scr => scr.Height(300))
.Groupable()
.Selectable()
.Pageable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false))
.Resizable(resize => resize.Columns(true))
)
OK so I figured it out. I added class='c-ok' in the template of the check box and added the following code to get the click event.
$('.c-ok').click(function (e) {
if ($(this).is(':checked')) {
alert('checked');
cokclick();
} else {
alert('not checked');
}
});

twig array of 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

Resources