Want to have checkbox already checked when data is loaded - php

I am using bootstrap-table (https://bootstrap-table.com/) and loading data via json. All data is currently loading correctly - an id field, checkbox field, and name. I load the data into an array, then into the table. However, I want certain records to have the checkbox already selected, depending on certain things. How do I pass this via the array below?
The scenario below does not work.
Here is how I am preparing my array in php:
$user_accounts[] = array(
'id' => $i,
'selected' => 'true', -- this is the checkbox
'name' => $name
);
My table is set up with these columns:
{ field: 'id', colspan: 1 },
{ field: 'bs-checkbox' },
{ field: 'name', align: center }
I get my data from an ajax call:
$.ajax
.....
success: function(data);
var opts = $.parseJSON(data);
$('.userTable').bootstrapTable(load,opts);
I thought sending 'true' to the checkbox would cause the checkbox to be checked, but that does not seem to be the case.
My HTML is set up as follows:
<th data-field="id"></th>
<th data-field="state" data-checkbox=true"></th>
<th data-field="cn">Name</th>
<th data-field="selected">Selected</th>

You can use the built-in bootstrap-table check method as:
$('.userTable').bootstrapTable('check', 1);
Where 1 is the row index that of the row that you want to be checked.
In your case you should place this code after table has loaded.

Related

jquery - How to add image to the Select2 dropdown list with data retreived from MySQL and PHP through AJAX?

I want to add an image in front of the options in the searchable dropdown list I made. The list is populated with data from MySQL database retrieved via PHP and AJAX. I am using the Select2 plugin for this problem, and I succeeded in making it work with simple data from the database, but I don't know how to add an image (link to the image is stored in the database) to the option. I read this article, but I don't know how to implement that information into my code.
This is what I made so far:
HTML
<select id="js-hieroglyph-code-select" name="hieroglyph-code-input" data-width="100%">
<option value="" selected disabled>Select hieroglyph code</option>
</select>
JS/Jquery
$("#js-hieroglyph-code-select").select2({
ajax : {
url : "./includes/individual_retrieve_scripts/retrieve_hieroglyph_undefined.script.php",
type : "POST",
dataType : "json",
delay : 250,
data : function(params){
return {
hieroglyphCodeValue : params.term
};
},
processResults : function(response){
return {
results : response
};
},
cache : true
}
});
PHP
$data = array(["id" => "0", "text" => "Hieroglyph without code"]);
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array(
"id" => $row["undefined_hieroglyph_code"],
"text" => $row["undefined_hieroglyph_code"]
);
}
echo json_encode($data);
exit();
I purposely left out the database query part of the PHP code for the sake of convenience, but I think it is not important for the problem here.
I thought about concatenating image link data and text data in PHP and then separate it in Javascript, but this is only an idea, and I don't know how to use that separated data further. Something like this:
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array(
"id" => $row["undefined_hieroglyph_code"],
"text" => $row["undefined_hieroglyph_code"]."/".$row["image_link"]
);
}
Is there a solution to this problem?
I recommend you take a look at select2 templateResult option here
You should first add the URL of the image as a separate key in your results and then use it in the function that templates your select2
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array(
"id" => $row["undefined_hieroglyph_code"],
"text" => $row["undefined_hieroglyph_code"],
"imageUrl" => $row["image_link"]
);}

PHP datatables / ajax : <td> in data

I need to update an old project - it has its own backend and does deliver row data as an array which gets displayed as a standard html table.
The last attribute in the row array has an "editing column" by default, which means, it contains markup for an edit-icon like this:
$aData = array(
"first_name" => "John",
"last_name" => "Connor",
"edit_columns" => "<a href='#' class='edit'>Edit</a>"
);
The problem - there are also tables in my backend which will deliver several table cells (which works so far as it used to be a html table) with array data like this:
$aData = array(
"first_name" => "John",
"last_name" => "Connor",
"edit_columns" => "<a href='#' class='edit'>Edit</a> </td><td> <a href='#' class='delete'>Delete</a>"
);
The problem: the datatables plugin will treat edit_columns as a single cell and filter the </td><td> markup which results in 2 hyperlinks within one cell.
I know i would need to refactor my data but my customer wants to keep the backend data untouched. So - is there a way to "shift" the cell data as required?
Depending on the version of datatables you are using you could listen to the xhr.dt-event with javascript and then modify/split the data before it gets rendered in your table.
myTable.on('xhr.dt', function (e, settings, json, xhr) {
let data = json.data;
for ( let i=0, dataLength=data.length; i<dataLength; i++ ) {
let edit_columns = data[i].edit_columns.split("</td><td>");
data[i].edit_column = edit_columns[0];
data[i].delete_column = edit_columns[1];
}
});
Now you can use the created data-columns (edit_column and delete_column) in your table like they are regular columns without modifying the code on the backend/serverside.

Grouping a checkbox with a corresponding input field

I am trying to find a way to group a checkbox and input field so a user can only input data into the field if the checkbox has been selected. I currently have a generated checkbox field (values from table) with a corresponding input field.
My current solution is:
#foreach($labourTypes as $id => $name)
<div class="checkbox">
<label>
{!! Form::checkbox("labour_types[]", $id) !!} {{$name}}
</label>
{!! Form::input('number', 'required_labour_type_hours[]', '') !!}
</div>
#endforeach
And for inputting into the database:
$required_labour_hours = array_filter($required_labour_hours);
$required_labour_hours = array_values($required_labour_hours);
foreach(array_combine($labour_types, $required_labour_hours) as $labour_type => $hours) {
DB::table('required_labour_type')->insert([
'id' => null,
'labour_type_id' => $labour_type,
'required_labour_type_hours' => $hours
]);
}
This is my current workaround, but it does not prevent (and messes up inserting) if the user were to fill out an input field that does not have the corresponding checkbox ticked.
This is what it looks like at the moment:
http://i.imgur.com/sVhnFMc.png
I am trying to find a way to make it so input is only allowed if the corresponding checkbox is selected, or to group them into an array prior inserting, and drop the ones that have no checkbox selected before inputting? I am new to laravel and php in general, so I am having a hard time coming up with a fool-proof workaround.
Thanks.
I would use jQuery on the front end to control the input from the user. I would also validate the data on the server side just be to safe. Using jQuery, you could easily make the input fields readonly if the checkbox was not checked, and update as needed. This code assumes that the input field is one of type="text". You could easily update to support multiple input types.
jQuery(document).ready(function($) {
$('.checkbox').each(function() {
var cbox = $(this).find('input[type=checkbox]'),
inp = $(this).find('input[type=text]');
cbox.on('change', function(evt) {
if( $(this).is(':checked') )
inp.removeAttr('readonly');
else
inp.attr('readonly', true);
});
//init
if( ! cbox.is(':checked') )
inp.attr('readonly', true);
});
});
On the server side, this would be as simple as checking for the existence of the checkbox. If a checkbox is not checked, it is not sent to the server during the form submission. So using something like:
if( isset($_POST['some_checkbox']) ) {
//sanitize, validate, and save the value of the corresponding text field
} // else do nothing with this text field

How to create dynamically disable a single check box of checkboxlist in YII

In a form, I have checkboxlist which has two check box (Male and Female)
User can select both of them or any of them. And values are getting save in DB.
When we populate it from DB then I want to do like if male was selected then it should select Male checkbox and disable the Female checkbox or vice versa.
The code in my View file is:
<?php if(isset($model['gender'])){
$data = $model['gender'];
if (isset($data)) {
if($data == 0)
$htmlOptions = array(
'0' => array('label'=>'MALE'),
'1' => array('disabled'=>'disabled','label'=>'FEMALE'),);
}
if($data == 1){
$htmlOptions = array(
'0' => array('disabled'=>'disabled','label'=>'MALE', ),
'1' => array('label'=>'FEMALE'),);
}
}
echo $form->checkBoxList($model, 'gender', $htmlOptions); ?>
Problem is when I am populating it is selecting the one,I selected while saving but not disabling the other one.
For this you have to use javascript because there is no way you can handle it only with PHP. Now I don't know that much JS, but the steps are easy:
Get the checkbox id's
check which one is selected
disable the other one with innerHTML in JS.
Here you have an example on how you disable checkboxes in JS
Just so you know, the JS should be placed inside the view.

Autopopulate textarea from database based on dropdown selection

I am trying to autopopulate a textarea with values from a (wordpress) database based on the value selected in a select menu. Basically the select menu contains a list of teams and I wish to populate my textarea with names of the players from the selected team.
The problem is that I need to convert the selected text to a php variable in order to use it to query the database. Like so:
PHP
$usergroups = $mingleforum->get_usergroups();
$team_title = $_GET['usergroup'];
$team_id = get_page_by_title( $team_title );
$players = get_users( array (
'meta_key' => 'team-meta',
'meta_value' => $team_id
));
JS
jQuery(function(jQuery){
jQuery('#usergroup').change(function() {
jQuery.ajax({
type: "GET",
url: "http://localhost:8888/dev_wordpress/wp-admin/admin.php?page=mfgroups&mingleforum_action=usergroups&do=add_user_togroup",
data: { usergroup: jQuery(this).find(':selected').text() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
UPDATE: corrected the url (based on #jterry 's comment) and no longer getting error (although it still isn't working)
I am getting the following error:
GET http://localhost:8888/dev_wordpress/wp-admin/wpf-addusers.php?usergroup=Coq+and+Bulldog 404 (Not Found)
For the points! :D
wpf-addusers.php doesn't exist at that path. Specify the absolute URI and you'll at least make it past the 404 error. Also, it looks like your url parameter has "" on both sides of the variable - you just need one on each side.
EDIT
To access the variable you're looking for (usergroup) to use in your PHP script, you can use $_GET['usergroup']. From there, you can use it as you see fit or insert it as the value of an input element.
If you use the value in an input element, be sure to use htmlentities to properly escape the value.

Categories