Repeater field groups - php

I'm trying to add a group of repeater fields to a WordPress plugin's settings page. This code works if I only have one repeater field, but if I have more than one repeater field in the same group, it behaves unexpectedly. What it does is, after saving the settings, it automatically adds empty fields. If I have, say, two repeater fields in the group, it will add two empty fields after saving. If I have more than two repeater fields, the number of empty fields after saving increases exponentially. I can't figure out why it's doing this. Again, with the current code, if I use only one repeater field, no empty fields are added after saving (that's what I want).
Here's the code I'm using:
function ssfrm_render_form(){ ?>
<form method="post" action="options.php">
<?php settings_fields('ssfrm_plugin_options'); $options = get_option('ssfrm_options'); ?>
<script>
jQuery(document).ready(function($) {
$('.repeatable-field-add').click(function() {
var theField = $(this).closest('div.repeatable-wrap')
.find('.repeatable-fields-list li:last').clone(true);
var theLocation = $(this).closest('div.repeatable-wrap')
.find('.repeatable-fields-list li:last');
$('input', theField).val('').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
});
$('select', theField).val('').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
});
theField.insertAfter(theLocation, $(this).closest('div.repeatable-wrap'));
var fieldsCount = $('.repeatable-field-remove').length;
if( fieldsCount > 1 ) {
$('.repeatable-field-remove').css('display','inline');
}
return false;
});
$('.repeatable-field-remove').click(function(){
$(this).parent().remove();
var fieldsCount = $('.repeatable-field-remove').length;
if( fieldsCount == 1 ) {
$('.repeatable-field-remove').css('display','none');
}
return false;
});
});
</script>
<h4>Configure PDF Output</h4>
<?php
echo '<div class="repeatable-wrap"><ul id="tracks-repeatable" class="repeatable-fields-list">';
if ( ! empty( $options ) ) {
$i = 1;
foreach( $options as $option ) {
?> <li>
<input type="text" name="ssfrm_options[ssfrm_mytext<?php echo $i; ?>]" value="<?php echo $options['ssfrm_mytext'.$i]; ?>" />
<input type="text" name="ssfrm_options[ssfrm_myothertext<?php echo $i; ?>]" value="<?php echo $options['ssfrm_myothertext'.$i]; ?>" />
<select name="ssfrm_options[ssfrm_myselect<?php echo $i; ?>]">
<option value="" <?php selected('', $options['ssfrm_myselect'.$i]); ?>></option>
<option value="true" <?php selected('true', $options['ssfrm_myselect'.$i]); ?>>Yes</option>
<option value="false" <?php selected('false', $options['ssfrm_myselect'.$i]); ?>>No</option>
</select>
<a class="repeatable-field-remove button" href="#">X</a>
</li>
<?php
$i++;
}
} else {
?> <li>
<input type="text" name="ssfrm_options[ssfrm_mytext1]" value="<?php echo $options['ssfrm_mytext1']; ?>" />
<input type="text" name="ssfrm_options[ssfrm_myothertext1]" value="<?php echo $options['ssfrm_myothertext1']; ?>" />
<select name="ssfrm_options[ssfrm_myselect1]">
<option value="" <?php selected('', $options['ssfrm_myselect1']); ?>></option>
<option value="true" <?php selected('true', $options['ssfrm_myselect1']); ?>>Yes</option>
<option value="false" <?php selected('false', $options['ssfrm_myselect1']); ?>>No</option>
</select>
<a class="repeatable-field-remove button" href="#">X</a>
</li>
<?php
} ?>
</ul><a class="repeatable-field-add button" href="#">+</a></div>
<br />
<p class="submit"><input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" /></p>
</form>
</div>
<?php
}

I've figured out the problem. After saving, it was repeating the fields group for each option in the group. I solved the problem by wrapping the repeatable section inside a conditional statement, checking if the first required field has a null value:
if ( $options['ssfrm_mytext'.$i] !== null ) {
// repeatable fields section
}

Related

Keep select list on reload

I have a select list, but on page reload , the data in the list is not saved of corse.
I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET.
Here is an example of the form I have now:
<form action="" id="exampleForm" method="get">
<input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
</br>
<select name="exampleList" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<input type="submit" value="Submit" id="submitButton"> </form>
I would like to keep the values of the 'exampleList' once submitted
(I stay on the same page)
I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var opts = localStorage.getItem('opts'); // get selected items from localStorage key
opts = opts.split(','); // split result from localstorage to array
$('#exampleList').val(opts); // select options with array
});
</script>
<html>
<body>
<select id="exampleList" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
When you POST the form you only need to write the selected option values, comma separated, to the localstorage.
I finally found a solution:
The only flaw is the order of the :)
But since I use a plugin for displaying it does not matter much.
The fix:
I created 2 Array lists
list1 with everying in it
list2 with all selected values
Then I subtract list2 from list1 and dont have duplicates
So I can print both in different print methods.
<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
<select name="exampleList[]" multiple>
<?php
foreach($fruitArray as $value) {
echo "<option value='$value'>$value</option>";
}
foreach($selectedFruitArray as $value) {
echo "<option value='$value' selected>$value</option>";
}
?>
</select>
<input type="submit">
</form>
Use FormRepo, a plugin specially made for retaining form data
on page refreshes.
Its usage is also simple:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
var $form = $('#input')
, $output = $('#output')
, repo = new FormRepo('restclient')
;
// get the last submitted values back
repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
$form.submit(function (e) {
// preserve the last submitted values
repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
});
console.log( repo.all() );
</script>
You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.
For e.g.,
<?php
session_start(); // Other Code
<div>
<p>Subtitle needs to be
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
</p>
<input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
</div> //Other Code
?>
PHP Code for set value in session after submit :
<?php
session_start(); //Not required if your form action is on same page, else required //Rest code
$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code
?>
Same code works for me.
first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:
<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>
Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.
<form action="" id="exampleForm" method="get">
<?php
if (isset($_GET['exampleCheckboxStatus'])) {
echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
} else {
echo '<input type="checkbox" name="exampleCheckbox"> Check this';
?>
<br />
<select name="exampleList[]" multiple>
<?php
if( in_array('apple', $_GET['exampleList']) ) {
echo '<option value="apple" selected>Apple</option>';
} else {
echo '<option value="apple">Apple</option>';
}
if( in_array('banana', $_GET['exampleList']) ) {
echo '<option value="banana" selected>Banana</option>';
} else {
echo '<option value="banana">Banana</option>';
}
if( in_array('cherry', $_GET['exampleList']) ) {
echo '<option value="cherry" selected>Cherry</option>';
} else {
echo '<option value="cherry">Cherry</option>';
}
?>
</select>
<input type="submit" value="Submit" id="submitButton">
</form>
Note that I added [] to the select's name and corrected the br tag.
Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.
Try it for yourself, play around with the code a bit.

How to access values from MSQL database in a drop down menu in PHP

I am developing a website using PHP and MYSQL.
and i made a form to add categories for the blog and stored it in the table of categories.
Now i want to access those categories in the drop down menu in another form of blog . Can anyone solve my problem?
Here is the code of form:
<html>
<head>
<title>Create a Blog!</title>
</head>
<body>
<?php
include_once ('BlogClass.php');
$j = new Blog();
$ans = array();
$ans = $j->DisplayCategories();
?>
<form name="BlogTopic" action="BlogTopicProcess.php" method="post" onSubmit="return validateForm()">
topic_cat :
<select name="topic_cat">
<?php
for ( $i = 0; $i < count( $ans ); $i++ ) {
?>
<option value="<?php echo($ans[$i]['Category']);?>"><?php echo($ans[$i] ['Category']);?></option>
<? php
}
?>
</select>
<label><strong>topic_id:</strong></label>
<input name="topic_id" type="text"/><br>
<label><strong>topic_subject:</strong></label>
<input name="topic_subject" type="text"/><br>
<label><strong>topic_date:</strong></label>
<input name="topic_date" type="text"/><br>
<label><strong>topic_by:</strong></label>
<input name="topic_by" type="text"/><br>
<input type="checkbox" name="terms" />
I agree to the terms & conditions <br>
<input type="submit" value="Create Topic" /><br>
</form>
</body>
</html>
The function DisplayCategory()
public function DisplayCategory() {
$connection=$this->Con->connectDb();
$data=array();
$sql="select * from categories";
$query=mysql_query($sql);
$numrows=mysql_num_rows($query);
if ($numrows!=0) {
while ($a=mysql_fetch_array($query))
$data[]=$a;
}
mysql_close($connection);
return $data;
}
I dont know what values your $ans contains, but this might help you
<select name='topic_cat'>
<?php foreach ( $ans as $a ) { ?>
<option value="<?php echo $a['key']?>"> <?php echo $a['value']; ?> </option>
<?php } ?>
</select>
Firstable you must delete the blank here
<option value="<?php echo($ans[$i]['Category']);?>"><?php echo($ans[$i] ['Category']);?></option>
to
<option value="<?php echo($ans[$i]['Category']);?>"><?php echo($ans[$i]['Category']);?></option>
if doesnt work then must check the method DisplayCategories() what type returns and in witch format.
Send us the code of this method
replace the code $data[]=$a; with this array_push($data,$a);

Post form values where Field Names are dynamically created from a loop?

I have a page that is created dynamically from the information that a user has submitted on a previous page. For example on page 1, the user inputs some department names. They can enter as many as they want. On page 2, multiple sections are created for each department that was entered on page one. Inside each of these sections are going to be forms, I currently have it set up so that the names of the forms are created using a variable $a. I need to know how to post these items once the submit button in each section is clicked. I have tried several different ways and nothing is working. I want it so that ONLY the items with the same $a value as the submit button's $a get posted.
$departmentSql = "SELECT * FROM b_departments WHERE loc_id='$locid' AND b_id = '$bid'";
$departmentResults = mysql_query($departmentSql,$con);
$a = 0;
while ($departmentRow = mysql_fetch_array($departmentResults)) {
$department = $departmentRow['b_dep_name'];
$departmentID = $departmentRow['dep_id'];
$b_departmentID = $departmentRow['b_dep_id'];
$a++;
echo "
<div id=depDiv>
<div id=depDivHeader>
".$department."
</div>
";
$areaSql = "SELECT * from areas WHERE dep_id = $departmentID ORDER BY area_name ASC";
$areaSqlResult = mysql_query($areaSql);
?>
<br />
<input type="hidden" name="bdep<?php echo $a;?>" value="<?php echo $b_departmentID; ?>" />
Add Area:
<select name="dep_area<?php echo $a;?>" type="menu">
<option value=""></option>
<?php while($areaRows=mysql_fetch_assoc($areaSqlResult)){?>
<option value="<?php echo "".$areaRows['area_id'].",".$areaRows['area_name']."" ?>"><? php echo $areaRows[ 'area_name'] ?></option>
<?php }
?>
</select>
<input type="submit" name="areaSub<?php echo $a;?>" value="Add" />
<?php
echo "</div>";
}
?>
*EDIT I need everything to be in one form because the point of the page is to add up all of the values that will be inserted into each of the individual sections later. *
**EDIT 2 :
I figured it out using #dirt 's jquery suggestion.
HTML:
$departmentSql = "SELECT * FROM b_departments WHERE loc_id='$locid' AND b_id = '$bid'";
$departmentResults = mysql_query($departmentSql,$con);
$a = 0;
while ($departmentRow = mysql_fetch_array($departmentResults)) {
$department = $departmentRow['b_dep_name'];
$departmentID = $departmentRow['dep_id'];
$b_departmentID = $departmentRow['b_dep_id'];
$a++;
echo "
<div id=depDiv>
<div id=depDivHeader>
".$department."
</div>
<div id=$a>
";
$areaSql = "SELECT * from areas WHERE dep_id = $departmentID ORDER BY area_name ASC";
$areaSqlResult = mysql_query($areaSql);
?>
<br />
<input type="hidden" name="bdep<?php echo $a ?>" value="<?php echo $b_departmentID; ?>" />
Add Area:
<select name="dep_area<?php echo $a ?>" type="menu">
<option value=""></option>
<?php while($areaRows=mysql_fetch_assoc($areaSqlResult)){?>
<option value="<?php echo "".$areaRows['area_id'].",".$areaRows['area_name']."" ?>"><? php echo $areaRows[ 'area_name'] ?></option>
<?php }
?>
</select>
<button type="submit" name="areaSub" value="<?php echo $a ?>" />Add</button>
<?php
echo "</div></div>";
} ?>
jQuery:
<script>
$(document).ready(function() {
$('#<?php echo $a ?>').submit(function() {
.post("include/action.php")
});
});
</script>
PHP:
if(isset($_POST['areaSub'])) {
$areaval = intval($_POST['areaSub']);
$area = mysql_real_escape_string($_POST["dep_area".$areaval.""]);
list($area_id, $area_name) = explode(',', $area, 2);
$bdep = mysql_real_escape_string($_POST["bdep".$areaval.""]);
echo $areaval;
echo $area_name;
echo $bdep;
}
EDIT: If its a single form with multiple sections and you don't want to trim out unwanted form data after the POST then I think you must use jQuery to trim the form values prior to the post to the server, so see my jQuery portion below for a crued example of how you would go about only posting the data for the selected button.
Short answer would be to use the Name/Value attributes of the submit button and evaluate that once posted. Multiple buttons with the same name can have different values and the values don't have to be the labels.
Example:
<form id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<button type='submit' name='submit' value='<?php echo $a; ?>'>Add</button>
</form>
...
<form id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<button type='submit' name='submit' value='<?php echo $a; ?>'>Add</button>
</form>
...
<?php
# _POST:
if (isset($_POST['submit']) && $_POST['submit'] == '1') {
echo 'Department 1';
}
if (isset($_POST['submit']) && $_POST['submit'] == '2') {
echo 'Department 2';
}
?>
You could also use jQuery to get all elements contained in a certain Div ID. Something like (this is rough idea):
<div id='<?php echo $a; ?>'>
<input type='text' name='in1'>
<input type='text' name='in2'>
<input type="submit" name="areaSub<?php echo $a;?>" value="Add" />
</div>
jQuery:
$('#<?php echo $a; ?>').submit(function() {
do_something_with_form_$a
});
I'm not sure if I understand completely... but the issue you're having is that, when a user hits the 'submit' button for a given set of values (a given department), it submits ALL of the data on the page? And you only want the input fields for that specific area submitted?
Section off forms with the tag:
<form> </form>
So, you'll have multiple areas:
while(...) {
<form method="..." name="form $a">
<input name="... $a">
<input name="... $a">
...
<submit>
</form>
}
(Obviously this is pseudocode, adjust accordingly)

How to make a div appear from a php variable using jquery

I am populating a list of checkboxes from a foreach loop, and giving each an ID. I have added a set of divs below that would appear, depending on which checkbox is created. I was thinking I could load the id variable into a jQuery if statement, and then use a .toggle to show or hide the corresponding div.
<?php
//Call Programs
$getPrograms = Doctrine::getTable('Program')->createQuery()->where('subsection=?', 'mfa')->orWhere('subsection=?', 'mps')->orWhere('subsection=?', 'mat')->orWhere('subsection=?', 'ma')->orderBy('title ASC')->execute(); ?>
<div class="form_row">
<label>
<span><sup class="required_form_item">*</sup>Select Program</span>
</label>
<div class="buttonColumn" style="margin-left:170px;">
//loop the records in with checkboxes
<?php foreach ($getPrograms as $prog): ?>
<?php
$subsection = $prog->getSubsection();
$subsection = strtoupper($subsection);
$trimProg = trim($prog->getTitle(), ' ');
$removeChars = array(" ", "&");
$trimProg = str_replace( $removeChars, '', $trimProg );
$trimProg = preg_replace('/\s\s+/', '_', $trimProg);
?>
//custin id matches record title
<input type="checkbox" name="program" class="isChecked" id="<?php echo $trimProg; ?>" value="<?php echo $subsection . " " . $prog->getTitle() ?>" /><?php echo $subsection . " " . $prog->getTitle() ?><br />
<?php endforeach ?>
</div>
</div>
The following divs would be set to display:none until the matching checkbox is checked.
<div class="form_row sessionTime" id="Program1" style="display:none;">
Please choose an session time:
<input type="checkbox" name="schedule" value="5:00 pm" />5:00 pm<br />
</div>
<div class="form_row sessionTime" id="program2" style="display:none;">
Please choose an session time:
<input type="checkbox" name="schedule" value="10:00 pm" />10:00 pm<br />
</div>
...
And this is what I thought would work...but alas...it doesn't
$('.isChecked').click( function() {
if ( $(this).is(':checked') ) {
$thisID = $(this).attr("id");
$('.'+ $thisID).show();
}
else {
$('.'+ $thisID).hide();
}
}
);
You should be using "Program1" as class name instead of id like this
<div class="form_row sessionTime Program1" style="display:none;">
Please choose an session time:
<input type="checkbox" name="schedule" value="5:00 pm" />5:00 pm<br />
</div>
And your jQuery code should work, which you can simplify as follows:
$('.isChecked').click( function() {
if ( $(this).is(':checked') ) {
$('.'+ this.id).show();
}
else {
$('.'+ this.id).hide();
}
});
I tested this code # home and it works as you might want
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(
function()
{
$('.isChecked').click(
function()
{
if ( $(this).is(':checked') )
{
$(this).show();
}
else
{
$(this).hide();
}
}
);
}
);
</script>
</head>
<body>
<form>
<input type="checkbox" name="program" class="isChecked"/>
<input type="checkbox" name="program" class="isChecked"/>
<input type="checkbox" name="program" class="isChecked"/>
<input type="checkbox" name="program" class="isChecked"/>
</form>
</body>
I think the problem in your code can come from the $(document).ready() handler that waits for the entire DOM to be loaded before binding action listener to it.
What's more, your jquery code wasn't working for me. My version seems to work, but once checked box hidden, the user cannot handle them anymore.
Otherwise, I think doing some Doctrine requests in your template is a very bad idea.
Good bye !

Passing loop values of child window to parent window and vice versa

I have a text box named subscriber name.when I double clicked on that text box,a child window should open.In that child window list of subscriber names are shown using while loop of mysql query.My problem is when I double clicked on it ll pass a value as undefined.This problems comes due to looping of subscriber names from db table.How can I solve it? Please help me soon.Here my code.
<script type="text/javascript">
function displaymessage(){
opener.document.cash_entry.sub_name.value = document.subscriber.subname.value;
self.close();
}
</script>
<form>
<?php
$sel=mysql_query("select * from add_ticket");
while($row=mysql_fetch_array($sel)) {
$subscriber=$row['subscriber'];
?>
<input type="text" name="subid" id="subid" value="<?php echo $subscriber; ?>"
ondblclick="displaymessage()" readonly="true">
<?php } ?>
</form>
You have not named your form and you named your field differently than in the HTML code and you have more than on element with the same name which makes it an array if more than one
Do this
<script type="text/javascript">
function displaymessage(fld){
opener.document.cash_entry.sub_name.value = fld.value;
self.close();
}
</script>
<form>
<?php
$sel=mysql_query("select * from add_ticket");
while($row=mysql_fetch_array($sel)) {
$subscriber=$row['subscriber'];
?>
<input type="text" name="subname"
id="subid<?php echo $subscriber; ?>"
value="<?php echo $subscriber; ?>"
ondblclick="displaymessage(this)" readonly="true">
<?php } ?>
</form>
by why not
<input type="button" value="<?php echo $subscriber; ?>"
onclick="displaymessage(this)" >
For more than one value, you can do
function displaymessage(fld){
var parts = fld.value.split("|");
opener.document.cash_entry.sub_name.value = parts[0];
opener.document.cash_entry.sub_id.value = parts[1];
self.close();
}
<input type="button"
value="<?php echo $subscriber; ?>|<?php echo $subscriberID; ?>"
onclick="displaymessage(this)" >

Categories