show division depending on result from server - php

How can I show or hide div depending on result come from server, in the file that handle the request, I get a customer object from db, depending on user request, if I didn't find the corresponding customer I want to hide a div .
here's my php code
$customer=getCustomerViaCellPhone($link,$cellPhoneNo);
if(!$customer){
$error = 'No result found';
}
here's the view
<div id="customerInfo" class="<?php (is_null($customer))?'hide':''?>">
....
</div>
but it shows the div in both cases

You are missing the command echo in your example so it should be:
<div id="customerInfo" class="<?php echo (is_null($customer))?'hide':''?>">
....
</div>
obviously your css would also need to define a class called .hide that had display:hidden; in it.

According to your comment, $customer is not NULL, it's an object with NULL values in it. Which will return false for your is_null($customer) check because it's not NULLDocs - it is an object.
You can solve this by decoupling the output logic from your data a bit:
$customer=getCustomerViaCellPhone($link,$cellPhoneNo);
$hideCustomerInfo = false;
if(!$customer) {
$error = 'No result found';
$hideCustomerInfo = true;
}
and in the view then:
<div id="customerInfo" class="<?php echo $hideCustomerInfo ? 'hide' : ''; ?>">
....
</div>
In case this does not work, you can validate the $hideCustomerInfo flag already in you controller to see if it contains the value you expect. Additionally this simplifies your view.
Next to that ensure your CSS is correct as well to hide HTML elements with such a class.

<div id="customerInfo" style="display:<?php echo (is_null($customer))?'none':'block'?>">
Take a look at css' display and visibility options

Related

Whether following types of code can be present in view in mvc(codeigniter)?

I am new to MVC & codeigniter and want to know whether its okay to have following types of code in view files
if(strcasecmp($_SESSION['role'],'author')==0)
{
some code
}
or
if($this->session->flashdata('edition_done_by'))
{
some code
}
i.e. checking existence of a session object or flashdata in a view file
Also,I would want to know whether creating table rows dynamically in a view file using foreach loop construct(like given below) is alright as per MVC
<?php foreach($items as $item){ ?>
<tr>
<td><?php echo $item->name; ?> </td>
<td><?php echo $item->price; ?> </td>
</tr>
<?php } ?>
Its not a good practice to check session values within the view. Check it within controller and pass the relevant data to view
It goes completely against the idea of the Model-View-Controller principe.
In (really) short; the model is responsible for managing data entities, CRUD operations, how a data entity should look like, etc. The controller is responsible for any business logic. Which means; when should I update a record, should this data be available to user x, etc. The view is merely responsible for displaying data that is already available. Nothing more, nothing less.
So in your example; the Controller should check session data, flash data, whatever, and send the processed data to the view. Eg:
if( strcasecmp($_SESSION['role'],'author') === 0 )
{
$can_edit = true;
$message = 'You can edit! Go ahead';
} else {
$can_edit = false;
$message = 'You do not have sufficient rights to edit this entity';
}
Now pass these variables to the view, there you can do something like:
<?php if ( $can_edit ): ?>
<form action="POST">
<p><?php echo $message; ?></p>
<textarea name="content"><?php echo $entity->content; ?></textarea>
<button type="submit">Update</button>
</form>
<?php else: ?>
<p><?php echo $message; ?>
<?php endif; ?>
One Word Answer is Yes! No Problem
It is fine to access Session Variables in Views . Session are variable to store information.
As Long as you are not putting Business Logic Inside Your View . you can use anything in views . The Case you mentioned you are using is What I will call "Display Logic" that is used to check which / What /From Where/ How content will be shown .
From Two Code Samples you Show Following One is Correct to Use with MVC
if($this->session->flashdata('edition_done_by'))
{
some code
}
You For Loop Code is also having no problem with MVC

PHP: How to populate a page dynamically once the user clicks on the URL

With help from #teresko I've managed to create dynamic pages (& their urls) for my site using the loop below. My problem is how do i get the newly created page at ahref to combine data I have in database with the template (which I already have ready), so that when the user clicks on it, she/he goes to the page populated with the data. Am i supposed to use a javascript click function (would rather not). How would i do it with php and html?
Here is the loop generating the URLs:
<?php foreach ($reciperow as $recipe) { ?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php } ?>
Would really appreciate a solution that stays clear of routing, since my site's a basic project and I plan to get to MVC and PHP routing in the next projects. Thanks.
If you meant How, when user clicks generated link, show him page with data from database accordingly to "id" he/she selected, then do the following:
<?php
$id = intval($_REQUEST['id']);
if ($id) { // user get here by clicking on link with id
$data = ... // fetch data from database
?>
<sometag>Some data from database:<?php echo $data['somecollumn']; ?></sometag>
...
<?php
} else {
// user just opened first page
// generate links list as usual
...
foreach ($reciperow as $recipe) {
?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php
}
...
}
?>
Edit:
Is this how it is normally done for simple sites?
Depends.
If you has only one entity in datadabe, then there will be no arguments clash, id is identifier only for recipies, but if you intent to show also details for, f.e. ingredients, furniture and/or more, then you must add specificators.
Like, links will look like
<a href="?show=recipie&id=<?php echo $recipe['uniqno'];?>">
<a href="?show=ingredient&id=<?php echo $ingredients['id'];?>">
... and then data must be fetched and displayed correspondingly:
$id = ...;
if ($id)
switch ($_REQUEST['show']) {
case 'recipie':
// show recipie data
break;
case 'ingredient':
// show ingredient data
break;
case ...
default:
// show start page
}
But with addition of another entities yours .php file will grow. Another solution will be to add separate scripts for handling each entity:
// generate links list as usual
...
foreach ($reciperow as $recipe) { // look at `recipie.php` portion of link's href
?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php
}
And add recipie.php file in the same folder as base script with following contents:
<?php
$id = intval($_REQUEST['id']);
if ($id) { // user get here by clicking on link with id
$data = ... // fetch data from database
?>
<sometag>Some data from database:<?php echo $data['somecollumn']; ?></sometag>
...
<?php
} else {
?>
<h1 class="error">No recipie ID specified</h1>
<?php
}
<?
Further exploring will bring you to concepts of MVC and routing via human-friendly-links format, when links looks like /home, /recipie/12 and/or /recipie/?id=12 or even /recipie/12-cream-pie. But that's story for another time...

WordPress - IF statement not working within archive.php

I'm looking to add a simple IF statement to check whether a custom field is selected, and if so, add the code 'display:none'.
I have the code I want to add:
if( get_field('my_custom_field') )
{
echo "";
}
else
{
echo "style='display:none'";
}
But, if I add this code where I want it, it throws an error, plus, becaus eof where it's being placed, no matter what other php type code I add, it throws up an error, I believe it's because it's in some kind of loop it's not allowing it, hopefully you'll be able to assist, here is the code it's sitting within:
$offices.= '
<div class="office_section" id="office_part_'.$locator.'">
<h1>'.$officetitle.'</h1>
'.$room_specs.'
<div class="office_dimensions_holder" *** this is where I would like to
add custom IF statement, but doesn't allow me to ***>
<div class="dimensions">
<div class="dimension_sml">Dimensions: </div>
'.$dimension1.'
I imagine it's because it's within the $offices.= ' call, so would appreciate the correct syntax to allow me to check the custom field I have recently added is true and if not...then add a display:none.
Looks like this question about php syntax...
Correct one should looks like:
$offices.= '
<div class="office_section" id="office_part_'.$locator.'">
<h1>'.$officetitle.'</h1>
'.$room_specs.'
<div class="office_dimensions_holder" '.(get_field('my_custom_field') ? "" : "style='display:none'").'>
<div class="dimensions">
<div class="dimension_sml">Dimensions: </div>
'.$dimension1.'
I ended up entering this outside my code and then called the conditional inside it:
$showdimensions = get_field('show_dimensions');
if(!empty($showdimensions)){
$showdimensions = 'style="display:none"';
} else {
$showdimensions = '';
}
Then within the original code added:
'.$showdimensions.'
to pull in the display:none if the checkbox was not checked.

PHP/Wordpress: IF/ELSE executing both conditions

Have been reading through multiple similar questions and went over my syntax many times, but I can't figure out why my PHP code is executing both conditions.
I'm trying to replace the url of an element with the string from a custom field if the field is not empty. If the field is empty, I want to output the permalink normally. What happens is that the code concatenates both the string from the custom field and the permalink when the field is not empty. If i remove the string in the field, it works fine.
<div class="profile-content">
<a href="
<?php
if ( the_field('direct_resource_link') != '') {
the_field('direct_resource_link');
} else {
the_permalink($id);
} ?>
"><h5><?php the_title(); ?></h5></a>
<div class="profile-footer">
Thanks!
Dan.
EDIT after comment from original poster
My initial assessment (left below for reference) was correct. You are using function that will print/echo content instead of returning it. Your if will always evaluate to false, because you are calling function that returns nothing; and PHP thinks that nothing and empty string are the same thing.
You didn't see that when field was empty, because the_field() for empty field printed empty string (or nothing at all), i.e. it didn't modify value printed by the_permalink() in any way/
According to ACF documentation, the_field() is accompanied by get_field() which returns value instead of printing it.
Your code should look like that:
<div class="profile-content">
<a href="
<?php
if ( get_field('direct_resource_link') ) {
the_field('direct_resource_link');
} else {
the_permalink($id);
} ?>
"><h5><?php the_title(); ?></h5></a>
<div class="profile-footer">
My initial post
What happens is that you run function the_field('direct_resource_link') and compare it's return value to ''; if that value is empty, you run the_permalink($id);.
It's hard to tell what the_field() is and what it is supposed to do, but I guess that it prints value instead of returning it. So if field is empty, it prints nothing, resulting in pure run of the_permalink(). If field is not empty, it prints it content and returns nothing. Since nothing is equal to empty string, PHP proceeds with else branch and invokes the_permalink() that prints additional info.
Solution: modify the_field() to return value instead of printing it, or make additional function that will query for value and return it, and use that function in if statement.
Miroslaw Zalewski already answered your question here, so this is simply to show you the kind of code needed to fix your issue:
function get_the_field($field) {
ob_start();
the_field($field);
return ob_get_clean();
}
This code will start an output buffer (which will capture all echo'd data), run the_field and return (and delete) the output buffer (the echo'd data from the_field). This means you can simply do the following:
...
<?php
$theField = get_the_field('direct_resource_link');
if ( $theField != '') {
echo $theField;
} else {
the_permalink($id);
}
?>
...
This can all be simplified. the_field() echoes a meta value. You don't want that...Instead, you want to return the value to check it, before conditionally echoing it. You can do this using get_field().
In the simplest form, your final code would look like the following:
<a href="<?php get_field('direct_resource_link') ? the_field('direct_resource_link') : the_permalink($id); ?>">
<h5><?php the_title(); ?></h5>
</a>

Hide/Show Input's based on mysql data

I have an active session in my page using: $_session_start(); I want to hide part of my form and show another based on the users previous entries.
Basically I offer Direct Deposit and Paper Check I want to be able to have the user only see the fields required for them to complete previously (in signup so the values are already in the database)
Right now the database table is set up like this:
paper_check with a value of 1 (yes pay this way) or 0 (no pay this way)
and the same thing with direct deposit. I need a way to show/hide the fields associated with each based on the users previous selections.
I typed this up but it doesn't seem to do anything. Please help me!!!!! (The class names hide and show are in my css and working properly!)
<?php
if ($_SESSION['direct_deposit'] == 1)
{
$doc->getElementById('check_payable_to')->className+" hide";
}
else
{
$doc->getElementById('name_on_account')->className+" hide";
$doc->getElementById('check_payable_to')->className+" show";
}
?>
I don't see a className property in the PHP DOM library. It looks like this is the way to add a class to an element:
$doc->getElementById('check_payable_to')->setAttribute('class',
$doc->getElementById('check_payable_to')->getAttribute('class') . " hide");
Do you have error reporting enabled? It should be warning about the unknown property.
If you want to do this in Javascript instead of PHP, have your PHP do something like:
<script>
var direct_deposit = <?php echo $_SESSION['direct_deposit']; ?>;
if (direct_deposit == 1) {
/* Do what you want */
} else {
/* Do what else you want */
}
</script>
In your question you said "I have an active session in my page using: $_session_start();" You shouldn't use $_session_start(). It should be session_start() .
className+" hide" should be className .= " hide"
By wrapping each section in it's own div like so:
<div id="paperCheck class="show">
<!--Your Paper Check Information here-->
</div>
<div id="directDeposit" class="show">
<!--Your Direct Deposit Information here-->
</div>
And then by using javascript you are able to do the following:
var direct_deposit = <?php echo $_SESSION['direct_deposit']; ?>;
if (direct_deposit == 1)
{
document.getElementById('paperCheck').className ="hide";
}
else
{
document.getElementById('directDeposit').className ="hide";
}

Categories