cakephp - Javascript - javascript

We are working on an application using the CakePHP framework
Basically, its a questionnaire application and it has a few dependant questions, i.e. based on a response to a specific question, it needs to show or hide the next one
For e.g.
Question: Are you married? Yes/No
If the user selects Yes, then using javascript the next question gets displayed for user input
Question: Spouse's name
Saving this information is fine, but when editing, when populating the form, we would want to be able to display the fields for which user has inputted data - in this case, it needs to show the field that has the spouse's name
Since by default we are hiding the spouse name field, when editing, it doesn’t display the field, even though there is a value to it
Is there some way that CakePHP can handle this or does it require us to write some javascript to take care of this?
Thanks in advance.

CakePHP does not manage this for you. While CakePHP is very powerful and a great framework, it will not write this kind of logic for you. You must write it.
I would suggest making the EDIT screen different from the ADD screen. Build the list of values from the database and display the fields that have values (and include any empty fields that should require values).
Keep in mind reusable does not necessarily mean that all CRUD actions fit into the same view.

Like others I advise you use differents EDIT and ADD screens.
But you can try make it with Javascript like this:
<script>
function enableDisableField(targetFieldId){
var targetField = document.getElementById(targetFieldId);
var checkbox = event.target;
console.log(checkbox.checked);
if (checkbox.checked){
targetField.disabled = false;
targetField.value = "empyt";
}else{
targetField.disabled = true;
targetField.value = "empyt";
}
}
</script>
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, 'disabled']); ?>
It works well for ADD, but if you and EDIT you have to change de disable value according a field value:
<label><input type="checkbox" onchange="enableDisableField('married')"/> Merried</label>
<?= $this->Form->input('married',['label' => false, !isset($user->married) ? 'disabled' : '' ]); ?>

Related

Django Modelmultiplechoicefield Checkboxselectmultiple Problem Getting Selected Checkbox

I have been working all day to try and get the selected values on one set of checkboxes on my Django form and copy the selected ones only to an identical checkbox on my form. If a user clicks on a checkbox in form.author defined below, I want the same identical checkbox to automatically be checked on form.favorite_author defined below.
I've tried a JQuery approach as documented here...Copy Selected Checkbox Value From One Checkbox To Another Immediately Using JQUERY but no luck so far. I've recently begun exploring an avenue with the Modelmultiplechoicefield and the checkboxselectmultiple parameters within the form itself. From what I can tell, when I am using JQuery and trying to check a box on the form, the value is coming back as undefined which is most likely why it is not propagating the checkbox selection to the other checkbox.
Here is my form....
class ManagerUpdateNewAssociateForm(forms.ModelForm):
class Meta:
model = Library
self.fields['author'] = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(),
queryset=Books.objects.all()
self.fields['favorite_author'] = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(),
queryset=Books.objects.all()
My HTML...
<div class="spacer83">
{{ form.author }}
</div>
<div class="spacer83">
{{ form.favorite_author }}
</div>
When I tried to trace JQuery, it told me the checkbox selections are undefined. I did read a bit about how Modelmultiplechoicefield, since it uses a queryset it doesn't show the selections, but I can't figure out how to get it to.
Thanks in advance for any thoughts.
In combination with the other issue included in this one, I went back to the JQuery route and explored further. From what I can tell, I was not able to use the class for the input because of the way the HTML for Django forms is generated in this use case. I ultimately was able to leverage the input name and then used the code below to interrogate the checkboxes accordingly:
$(document).ready(function() {
$("[name=author]").change(function() {
let selectedValA = $(this).val();
let isAChecked = $(this).prop("checked");
$(`[name=favorite_author][value="${selectedValA}"]`).prop("checked", isAChecked);
});
});
});

How do I autofill a widget with form inputs using Javascript?

I'm working on a donation form that has a widget embedded in it. The widget opts users into our Mobile Giving giving program which uses separate software than our donation forms. I've been asked to see if we can make the widget invisible but transfer the form data to it and submit it when the user submits the donation form. I've already run into a problem with getting the form data to transfer to the widget though.
The form should get the donors first name, last name and phone number from the form and then autofill the widget when a checkbox is clicked stating that the user would like to receive mobile updates.
Below is what I've tried but it doesn't seem to be working. The code for the form is relatively long so I just included the relevant fields but here is link to the full form: http://support.ddfl.org/site/Donation2?df_id=9442&mfc_pref=T&9442.donation=form1
I'm very new to Javascript so I'm not entirely sure if this is possible. Just an fyi, I also included console statements so I could see if the values were working.
<input type="text" name="billing_first_namename" id="billing_first_namename"
<input type="text" name="billing_last_namename" id="billing_last_namename"
<input type="text" name="donor_phonename" id="donor_phonename"
<input type="checkbox" name="mcoptin" onclick="FillMobileCause(this.form)" value="this.form"> Opt in to receive mobile updates.
Mobile messaging powered by Mobilecause<script>!function(d,s){var s=d.createElement("script"),h=(document.head||d.getElementsByTagName('head')[0]);s.src="https://app.mobilecause.com/public/messaging_widgets/q71xd/source";h.appendChild(s);}(document);</script>
<script>
function FillMobileCause(f){
if(f.mcoptin.checked == true){
console.log(f.billing_first_namename.value);
console.log(f.billing_last_namename.value);
console.log(f.donor_phonename.value);
if(f.billing_first_namename.value.length>=1){
f.firstname.value = f.billing_first_namename.value;
}else {
f.firstname.value = '';
}
if(f.billing_last_namename.length>=1){
f.lastname.value = f.billing_last_namename.value;
}else{
f.lastname.value = '';
}
if(f.donor_phonename.length>=1){
f.mobilenumber.value = f.donor_phonename.value;
}else{
f.mobilenumber.value = '';
}
console.log(f.firstname.value);
}
}
</script>
Please let me know if I'm leaving off important details. This is also my first StackOverflow post. ;)
I appreciate your help!
Your main issue is that you were referring to inputs in the mobilecause form as if they were in the same form, but they are in another (nested in your f main form).
function FillMobileCause(f){
var mcF = f.getElementsByClassName('mc-triggersubscription')[0];
if(f.mcoptin.checked == true){
mcF.firstname.value = f.billing_first_namename.value;
mcF.lastname.value = f.billing_last_namename.value;
mcF.mobilenumber.value = f.donor_phonename.value;
}
}
f is still the main form (the one that is the parent of the checkbox).
But now we have another one, mcF (mobilecauseForm), which is selected using the getElementsByClassName (this will search for a child with the mc-triggersubscription class). The [0] part is so the first match is selected (getElementsByClassName returns an array.
After that, all we need to do is assign the f inputs' values to the mcF ones.
Note: I left behind the "if empty" validation for simplifying. Anyway I don't think it's really needed, if a value is empty, there is no major issue in just copying it to the mobilecause value.

Select field populated with multiple entries after one checkbox change

I have something in my mind, but I have no idea how to get it done, so I hope I can get some advise here.
I'm working on an activity registration app (using Laravel), where every activity will be registered. Very important is that we need to record who was invited and who actually attended. I already have this part running. My issue is more on the practical side.
I use jQuery Select2 for the multiple select fields for invitees and attendees. Imagine now that there's a group of users that need to be invited or attend virtually all activities, while the invitation or attendance of others depends on the type of activity. Using Select2, I can only select users one at a time and that sucks if you need to do that for, say, 50 users for virtually every activity.
What is the best way to have a "group" that can be selected, which selection fills in all the names of those in the group in the select field? Or is there a better way to get this done?
I'm seeing something in my head, where there are checkboxes next to the select field, representing the groups. When you tick a checkbox of a group, the select field is populated with all users who are part of that group.
I have no idea ow this can be done. I looked around and every search brings up select boxes populating select boxes. None handle checkboxes.
Any advise on how to get this done?
My PHP/MySql is intermediate, Javascript/Ajax is very basic.
One strategy would be to build a control (checkbox element) that will set or toggle the selection of your group of users whenever it's clicked. Say we have the following markup:
<select class="my-big-group-select" multiple="multiple">
<!-- assorted options here -->
</select>
<label>
<input type="checkbox" class="toggle-default-group" />
Use my default big group of users
</label>
The Select2 API allows you programmatic control over the component it generates.
You can read more about it here: https://select2.github.io/examples.html#programmatic
Here's one way to leverage this knowledge using jQuery with Select2:
<script>
var groupSelect = $('.my-big-group-select').select2();
var groupToggle = $('.toggle-default-group');
var myBigGroup = ["Aaron", "Beth", "Cindy"]; // assorted option values
groupToggle.on("click", function() {
if ($(this).is(':checked')) {
groupSelect.val(myBigGroup).trigger('change');
} else {
var currentlySelected = groupSelect.val();
if (currentlySelected) {
var filteredSelections = currentlySelected.filter(function(key) {
return myBigGroup.indexOf(key) < 0;
});
groupSelect.val(filteredSelections).trigger('change');
}
}
});
</script>
Here's a CodePen that shows it all in action: http://codepen.io/anon/pen/qNQKOd
Of course you can build on this to make additional enhancements (the ability to select multiple groups, for example).
As an alternative, you may consider other code libraries like Bootstrap Multiselect: https://davidstutz.github.io/bootstrap-multiselect/
Hope this points you in the right direction!

WordPress - Custom Form for custom post types in back-end

I am creating an eSports website and I want to create a bracket generator for each tournament. What I essentialy want to achieve is a custom form for each of the tournaments (post types). In that form I want to have an ability to choose how many rounds should this tournament have and be able to assign teams to any of the parts of the bracket.
I thought about doing this with custom fields but I doubt that they can be dynamic (for example, the amount of fields should increase if the tournament has more rounds than by default). They should also be simple to use for my client, so he shouldn't have to add custom fields manualy.
I decided to create a meta box with a form inside of it:
function add_meta_boxes() {
add_meta_box('peterworks-tournament-bracket', 'Peterworks Tournament Bracket', 'pworks_bracket', 'tournaments', 'side');
}
function pworks_bracket() {
?>
<form method="POST">
<input type="text" name="test_it" value="test" />
</form>
<?php
}
Then I tested if data from that form is reachable inside the wp_insert_post_data filter. It is:
function modify_post_title( $data , $postarr )
{
$data['post_title'] = $_POST['test_it'];
return $data;
}
This succesfully changes the title of a post to the value of that form's input. It means that I can create a custom form and make it dynamic with JavaScript.
My question is - is this approach correct? What are the potential problems I might be facing using this technique? Is there a better/easier way to do this?

How to control a combo box by using another combo box in HTML

I have 4 combo box in my HTML form. First 2 are Area and Subarea. Another 2 are Type and Subtype. I want to fill combo box using database values. I already filled first combo box i.e. Area ID but after that when I select particular Area then according to that value I want to fill SubArea combo box. I can't do it in PHP only. And I am new to JavaScript and Ajax. Will you please help me??
Many people have in fact tackled this problem before. It is frequently refered to as a "dependent" or "related" or "cascading" selectbox/combobox. Here's a google search to get you some plugins for javascript (using the excellent jQuery library): https://www.google.com/search?hl=en&q=jquery+dependent+select&oq=jquery+dependent+select
Also, the "related questions" on the right side of this question look fairly pertinent to your situation, try reading up on some of them.
Please note that the FAQ encourages questions to match one or all of the criteria
a specific programming problem
a software algorithm software tools
commonly used by programmers practical, answerable problems that are
unique to the programming profession
Which, as mustafa.0x points out, your question is overly broad and does not include a specific question. Take a swing at using a plugin, or research some non-jQuery solutions, and if you run into trouble, post another question with the specific problem you're running into.
I use an event in javascript then I can retrieve the id being use from it but sadly cannot import it to php.
`
* Department Name
<select name = "dept_type" id = 'new_jobdep_id' onchange = 'clickSelect(this.value)' class= "form-control" required>
<option value = "" selected>-----Select Department---</option>
<?php
$sql_in = mysql_query('Select * from department where DeptStatus = 1');
while ($r = mysql_fetch_assoc($sql_in)){
$depID = $r['DeptID'];
$depName = $r['DeptName'];
$depName = ucwords($depName);
?>
<option value = <?php echo $depID; ?> required><?php echo $depName; ?> </option>
<?php
}
?>
</select>`
hopefully this code can give you a good logic.
Pls.. answer this question..
I just want to get the value the select statement below then make it as a reference to another combo box by inserting the retrieve ID from php to my query..
This is a broad design question, but you'll need to attach an event to the combo box, so when an item is selected, you execute an AJAX request which retrieves the sub-items of the selected item.

Categories

Resources