Wordpress Advanced Custom Fields within an if statement - php

I'm trying to use ACF to output different salary amounts for a job listing board.
E.g:
Select box option in ACF for salary type ("competitive", per day, per annum etc). Looks like this:
Then I have conditional fields. So if "P.A" is selected it shows the P.A field:
I have a bunch of these conditional fields for the different select box options.
My question is:
How do I add these to an if statement so that the correct field is shown based on the content that was supplied?
E.g
if job_salary was selected as "competitive" =
echo "competitive"
else if job_salary was selected as "p.a" =
echo job_salary_singular
else if job_salary was selected as "p.a range" =
echo job_range_start " to " job_range_end
Hopefully this makes sense. This is the code I have at the moment, which just outputs the type of salary entered (e.g, competitive, P.A, Per Day Range) as text.

This approach should work. In my example, the main selector field where you choose if it's per annum pay, competitive, a range, etc., is called salary_type.
Then I've got per_annum. It appearing is conditional on 'Per Annum' being selected from salary_type. And finally per_annum_range_low and per_annum_range_high, both of which are conditional on 'Per Annum Range' being selected.
We can then test based on the salary_type selection to output the appropriate values and HTML. Alternatively, you could test for the existence of those fields. But I think this is a bit cleaner and allows you to skip adding an additional field for "Competitive".
PHP
<?php
if (get_field('salary_type')) { //first we check if the salary_type field exists.
$selection = get_field('salary_type'); //then we store its value as '$selection'
if ($selection === 'comp') { //we check which selection was made by looking at its label.
echo '<p>' . 'Competitive' . '</p>';
} else if ($selection === 'perannum') { //ACF allows you to store a selection as both a value (in this case, 'perannum') and a label ('Per Annum', which is what the user sees.)
echo '<p>' . get_field('per_annum') . ' per year</p>';
} else if ($selection === 'perannumrange') {
echo '<p>From ' . get_field('per_annum_range_low') . ' to ' . get_field('per_annum_range_high') . ' per year</p>'; //and then echo its output and any HTML markup you want.
} else {
echo '<p>No Salary Info Given.</p>'; //if they don't make a selection
}
}
?>

Related

Getting an alternate value for an unchecked checkbox?

I've seen a solution here that I, quite frankly, don't understand.
On the administration side of a website I'm working on, an administrator can edit blog posts. When the administrator goes to the page to edit the blog post, it also displays all of the comments on that post. Instead of adding a new table for each new blog post which contains comments, I simply created one table which holds all the information for the blog post, including a column for the comments.
Comments and comment-content is delimited. I.E. internally, a blog post comment column would look similar to this...
Name:Content:Email>Name2:Content2:Email
Etc.
This is how I display the comments on the admin page:
$post_query = "SELECT * FROM `$blog_table` WHERE id=$identifier";
$post_result = $connection->query($post_query);
$post = $post_result->fetch_assoc();
$comments_value = $post["comments"];
$original_comments_array = explode(">", $comments_value);
$comments_array = [];
foreach($original_comments_array as $comment) {
$individual_comment_array = explode(":", $comment);
$comments_array[] = $individual_comment_array;
}
foreach($comments_array as $index=>$comment) {
if ($comment_deletions_array[$index] === $index) {
$checked = "checked";
}
echo '<div class="content-border comment-margin"><span class="comment-name">';
echo $comment[0];
echo '</span><br /><p class="comment-content">';
echo $comment[1];
echo '<br /></p>';
echo $comment[2];
echo '<br /><br /><input name="comment_deletions[]" type="checkbox" value="' . $index . '" ' . $checked . '/> Delete This Comment';
echo '</div>';
}
As you may have noticed from the code above, each comment renders with its own checkbox input, the value of which is determined by the index.
Each checkbox shares the same name. I get all the values of the checkboxes like this:
$comment_deletions_array = $_POST["comment_deletions"];
In the snippet I provided earlier, there is an if statement within the foreach loop which determines if the comment was marked for deletion, and if so checks the check box. (This function is to replace the user's input if there was an error.)
The problem is that the indexes do not line up. If there is a checkbox which is not checked, it does not return false or null or anything of the sort to the $comment_deletions_array rather the array is just populated by value of the next input which WAS checked.
Is there a way I can return a value if the checkbox is not checked in order to maintain the correct index?

Creating tr value filter

I creating filer for website data. I have created value attribute for <tr>which means that the row belongs for specific company. And now i want to make that table would show rows depending which value i will choose. And i really dont have idea how to do that. $currentCompany is that value number of company id. Here is my script:
if($row["type"] != "Staff Comment")
{
print("<tr value=". $currentCompany ." style='height:25px;'>\n");
for ($loop = 0; $loop < count($fields["headings"]); $loop++) {
print("<td bgcolor='white' align=" . $fields["aligns"][$loop] . ">\n");
//translate some information, some not
if ($fields["headings"][$loop] == "Status") {
print($AppUI->_(format_field($row[$fields["columns"][$loop]], $fields["types"][$loop], $row[$fields["columns"][0]])) . "\n");
}
else {
print(format_field($row[$fields["columns"][$loop]], $fields["types"][$loop], $row[$fields["columns"][0]]) . "\n");
}
print("</td>\n");
//print("<tr>" . var_dump($fields) ."</tr>\n");
}
print("</tr>\n");
And here is how it looks like in website:
Hope you can help me guys. For example if i would choose value 25 it would print all tr which has that value.
You want to hide rows, or just not print them? If hide - You have to use JS - PHP cannot modify site dynamically. If just don't print them - use simple if, and possibly You want to pass this information via simple form and POST request.
Create form, which action point to Your script, and have text field where you can specify which company have to be shown. Then, in Your code something like this:
if($currentCompany == $_POST['company'])
{
print("<tr value=". $currentCompany ." style='height:25px;'>\n");
//More code....
}
With JS it will be more complicated - but easy, too. It will have to be done in this way:
Get all TR's
Check every TR value. If value not corresponds to Your needs - add "display: none" CSS attribute.
Concrete JS implementation depends on way you want to code in JS - pure JS, jQuery, other JS framework.

Echo input from users only if it exists or is of desired value

I am building a Order form for a Client's website. One of the pages lets users choose Vehicle Spareparts by entering the quantity beside each part. I have achieved this by writing the following code
<input class="qty" type="number" name="oil-pump" min="0" max="100">
The above input attribute is added several times besides each sparepart type while changing just the name value. On clicking Submit, the user is taken to a review page with details on the spareparts ordered.
I presently have the following code in review page:
<?php
echo 'Engine Bearings: ' . $_POST['eng-bearings'];
echo 'Cylinder Heads: ' . $_POST['cyl-heads'];
echo 'Cam and Valve Train: ' . $_POST['cam-valve-train'];
echo 'Oil Pump: ' . $_POST['oil-pump'];
echo 'Oil Caps and Pipes: ' . $_POST['oil-caps-pipes'];
?>
This works well if the user has entered a value in every field. If he doesn't, then the review page has just the echo text without any quantity. Also, I don't want the quantity to apppear if the user has entered 0.
I can't figure out how to use isset() with null and OR statements to not echo text when the value entered is 0 or left blank.
Any help is appreciated. Thanks!!
This is the perfect opportunity for a function:
function print_user_input($title, $queryVar) {
if (isset($_POST[$queryVar]) && !empty($_POST[$queryVar])) {
echo $title . ': ' . $_POST[$queryVar];
}
}
Use it like so:
print_user_input('Engine Bearings', 'eng-bearings');
Echo the value conditionally. If the target data is empty, echo an empty string:
echo empty($_POST['eng-bearings']) ? '': 'Engine Bearings: ' . $_POST['eng-bearings'];
Repeat for the other post values. Information about the ternary operator (<conditional> ? <value1> : <value2>) is here.
You need to check if its set & that its not empty before printing it on a screen.
<?php
if (! empty($_POST['eng-bearings'])) {
echo 'Engine Bearings: ' . $_POST['eng-bearings'];
} else {
// whatever you wanna do here in case eng-bearings is not set or its empty
}
// Do same for other $_POST values ...
?>

For loops & If Statements

I'm working on this code in PHP and basically I have 5 checkboxes, for 5 individual items, each called "ItemCheck" and they have values of 0-4. Now I wrote a code where it has it so it displays the numbers that are checked from those 5 check lists.
Form:
for ($i=0;$i<count(5);$i++){
echo "
<input type='checkbox' name='ItemCheck' value='$i.check'>$i</input><br>"}
PHP Process:
if (isset($_POST['ItemCheck'])){
for ($o=0;$o<$ItemCount;$o++){
if($_POST['ItemCheck'] == $o.'.check') {
echo "Item " . $o . "<br>";
}
}
}
else{ echo "You must select at least one product";}
Although say if I check box #1,2 & 3, the final output will only display "Item 3". Now matter how many checkboxes you select, it will only display the one with the highest value and none other. Does anybody know what's wrong with the code and how to have it so it displays each individual number that's selected, and not just the one with the highest value?
What you want to do is set the name of the checkbox element ItemCheck[] this will make $_POST["ItemCheck"] an array.
Example:
for ($i=0;$i<count(5);$i++){
echo "<input type='checkbox' name='ItemCheck[]' value='$i.check'/> $i<br>";
}
Another thing to note is the browser won't post up anything for an unchecked checkbox so I think your processor needs to be like this.
<?php
if (isset($_POST['ItemCheck'])){
for ($o=0;$o<count($_POST['ItemCheck']);$o++){
echo "Item " . $_POST['ItemCheck'] . "<br>";
}
} else {
echo "You must select at least one product";
}
?>
Another thing so make sure of is that your form has the method set to POST

Using PHP function to create a dynamic dropdown menu using arrays: dropdown doesn't populate

I am trying to dynamically build a drop down menu using PHP. The idea is: the elements are formed from a loop which calls and array. If the array element matches the data held in session then it adds the "selected" attribute to the tag, meaning that the page displays the previously selected option.
I have tried to include one complete set of code here, all the way from defining the variables from session data to echoing the HTML for the form element.
It doesn't currently work - the drop down menu appears, but is blank, and has no options. I've debugged it with ideone and it seemed to run successfully, and I can't see where I am going wrong, however this is my first PHP function! So I'm sure I've screwed it up somehow :)
Any help much appreciated.
<?php
session_start();
//if the session data has been set, then the variable $sv_02 is defined
//as the data held in the session under that name, otherwise it is blank
if (isset($_SESSION['sv_02'])) {$sv_02=$_SESSION['sv_02'];} else {$sv_02="";}
//define the array
$dm_sv_02 = array('-Year','-2012','-2011','-2010','-2009');
//create the function
function dropdown($dropdownoptions, $session_data)
{
foreach($dropdownoptions as $dropdownoption){
if($session_data == $dropdownoption){
echo '<option value="' . $dropdownoption . '" selected>' . $dropdownoption . '</option>';
} else {
echo '<option value="' . $dropdownoption . '">' . $dropdownoption . '</option>';
}
}
}
//echo the HTML needed to create a drop down, and populate it with
//the function which should create the <option> elements
echo '<select name="sv_02">';
dropdown($dm_sv_02, $sv_02);
echo '</select>';
?>
Try this:
foreach ($dropdownoptions as $dropdownoption) {
echo ($dropdownoption == $sv_02) ? "<option selected=\"selected\" value=\"$dropdownoption\">$dropdownoption</option>" : "<option value=\"$dropdownoption\">$dropdownoption</option>";}
This turned out to be a result of the fact I was using {smarty} tags to build my php, the code was as written but only worked when it was all included in one smarty tag, I'm not sure I understand why that should be the case but in any regard it was fixed by including it all in one tag.

Categories