Jump to content
Peter Knight

If else not working

Recommended Posts

I'm trying a twist on a simple if / else statement.

  1. If the blog_category field is populated (page select), display the categories.
  2. If not, don't output anything.

This works:

<?php		
if ($page->blog_category){
    foreach($page->blog_category as $cat){
    echo"<a href=\"{$cat->url}\">{$cat->title}</a></li> ";} 

else {
    echo"";}
?>

But I've an added complication that the Categories need to have a "Posted under" before the very first Category.

I've tried variations on the code below and the first part works but even if there are no categories selected, I still get "posted under" appearing on the page.

<?php		
if ($page->blog_category){
  echo"Posted under: ";
  foreach($page->blog_category as $cat){
    echo"<a href=\"{$cat->url}\">{$cat->title}</a></li> ";} 
} 
else {
  foreach($page->blog_category as $cat){
    echo"";}
}							
?>

Have run my PHP through an online syntax checker and it's not showing any errors so it must be an issue.

Any tips?

Share this post


Link to post
Share on other sites

How about:

<?php
if ($page->blog_category) {
    echo "Posted under: " . $page->blog_category->each(function ($index, $cat) {
        return "<a href=\"{$cat->url}\">{$cat->title}</a>";
    });
}

Needs PW 2.5.27+

Share this post


Link to post
Share on other sites
<?php		
// An object is always equal to true in php.
// For a PageArray do check for the number of elements.
// For a Page one would check for the id.

if ($page->blog_category->count()){

  echo"Posted under: ";
  foreach($page->blog_category as $cat){
    echo"<a href=\"{$cat->url}\">{$cat->title}</a></li> ";
  } 
} 
// Else do nothing. Not even loop though an empty array

@Mike Rockett

When using the new wire api function than do it the right way:

echo "Posted under: " . $page->blog_category->implode(", ", function($cat) {
    return "<a href=\"{$cat->url}\">{$cat->title}</a>";
});
  • Like 5

Share this post


Link to post
Share on other sites

Thanks both for your help.

@LostKobrakai - that worked and more importantly (for me) makes sense. 

I had thought that ->count was mainly only useful if you wanted to output an integer. Hadn't thought of doing it like this.

Share this post


Link to post
Share on other sites

@Mike Rockett

When using the new wire api function than do it the right way:

echo "Posted under: " . $page->blog_category->implode(", ", function($cat) {
    return "<a href=\"{$cat->url}\">{$cat->title}</a>";
});

Also true. Thanks.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Peter Knight
      I have the following code which creates a 2 column div. In the first I check to see if there are any images present and only echo an image if there is.
      If I don't do this, I get an error.
      But I was wondering if there was a more efficient way to do this?
      I don't know the proper terminology but I suspect breaking the code into three parts as I have done ...
      First - the first <div class='uk-width-1-2@s'> Second - the image check Third - the final div ...is somewhat more verbose than it needs to be with more modern PHP
       
      <?php $imgoptions = array('quality' => 100,'upscaling' => false); $products = $page->siblings("id!=$page"); foreach ($products as $prod){ echo" <div class='uk-width-1-2@s'> "; if(count($prod->images)){ echo" <a href='$prod->url'> <img class='lazyload prod-thumb-ov' src='{$prod->images->first()->height(300, $imgoptions)->url}' data-src='{$prod->images->first()->height(300, $imgoptions)->url}' data-srcset=' {$prod->images->first()->width(414)->url} 414w, {$prod->images->first()->width(320)->url} 320w' data-sizes='auto' alt='{$prod->images->first()->description}'> </a> ";} echo " </div> <div class='uk-width-1-2@s'> {$prod->title} </div> ";} ?>  
      Thanks
       
       
    • By Peter Knight
      I was trying to fix an error earlier which was preventing a series of if statements from working.
      Basically I have a button called "Product Drawing" which needs localising depending on the current language session.
      Eventually got it working - I had a bracket in the wrong place.
       
      Curious as to why both these work though.
      On the sample below. each echo is surrounded by curly braces.
      <?php if ($page->files->count()) foreach($page->files->findTag('drawing') as $file) { if($user->language->name == 'default') {echo "<a href='$file->url' class='uk-button uk-button-primary'>Product drawing</a>";} if($user->language->name == 'french') {echo "<a href='$file->url' class='uk-button uk-button-primary'>Le plan du produit</a>";} if($user->language->name == 'german') {echo "<a href='$file->url' class='uk-button uk-button-primary'>Produktzeichnung</a>";} if($user->language->name == 'spanish') {echo "<a href='$file->url' class='uk-button uk-button-primary'>El dibujo del producto</a>";} if($user->language->name == 'italian') {echo "<a href='$file->url' class='uk-button uk-button-primary'>Il disegno del prodotto</a>";} } ?>  
      On the sample below, there are no curly braces around the echo
      <?php if ($page->files->count()) foreach($page->files->findTag('breakingreport') as $file) { if($user->language->name == 'default') echo "<a href='$file->url' class='uk-button uk-button-primary'>Breaking strain report</a>"; if($user->language->name == 'french') echo "<a href='$file->url' class='uk-button uk-button-primary'>Le test de rupture</a>"; if($user->language->name == 'german') echo "<a href='$file->url' class='uk-button uk-button-primary'>Bruchfestigkeit bericht</a>"; if($user->language->name == 'spanish') echo "<a href='$file->url' class='uk-button uk-button-primary'>Informe resistencia</a>"; if($user->language->name == 'italian') echo "<a href='$file->url' class='uk-button uk-button-primary'>La rottura rapporto ceppo</a>"; } ?>  
      Should the second piece work?
       
       
       
       
       
       
       
       
       
    • By hellomoto
      I have the following import script being included in the homepage template file:
      <?php $mmpid = wire('pages')->get('template.name=makes')->id; // Manufacturers: $file = __DIR__.'/manufacturers.csv'; importCSV($file, 'mamo_manufacturer', $mmpid); // Models: $file = __DIR__.'/models.csv'; importCSV($file, 'mamo_model', 0, $mmpid); function importCSV($filepath, $template, $parent_id = null, $grandparent_id = null) { $csv = array_map('str_getcsv', file($filepath)); array_walk($csv, function(&$a) use ($csv) { $a = array_combine($csv[0], $a); }); array_shift($csv); # remove column header //echo '<pre>'; print_r($csv); echo '</pre>'; foreach($csv as $r) { $p = new Page(); $p->name = wire('sanitizer')->pageName($r['title']); $p->template = $template; if($parent_id !== 0||null) { $p->parent_id = $parent_id; } elseif($parent_id == 0||null) { //$parent = wire('pages')->get('title=' . $r['parent']); //echo $parent.' ';// echo $r['parent'].' '; echo $grandparent_id.' '; $parent = wire('pages')->get('title=' . $r['parent'] . ', parent_id=' . $grandparent_id)->id; echo $parent.' '; $p->parent_id = $parent; unset($r['parent']); } $p->save(); foreach($r as $k=>$v) $p->$k = $v; $p->save(); echo '<br>'; } } Output =
      Why is it running the ELSE when the condition for the IF is met? (the first 9 lines)
      All 14 models (lines past 9) are created under the first manufacturer. I've been messing with it, been able to get them to display the page IDs proper at one point for the models but still there's the standing issue of all of them being created under the first manufacturer nonetheless and also the ELSE running despite not being a condition of ELSE.
      What's up please...
    • By melissa_boyle
      Hi Guys,
       
      I am trying to implement a website that uses processwire as the content management system. I am trying to create a page where stars can be added to a christmas tree, each star is a repeater field and is associated to a modal pop up which displays a message.
       
      There may be more stars than what we can physically put on the tree so I have implemented the search function to allow users to search for a name or message in order to find their star.
       
      At the minute the search function is showing the results from the repeater fields, I have 2 stars at the minute however only one shows in the search results. 1 star has test in all the fields and the other has mel in each of the fields. 
       
      I have no idea why only one result will show, any help would be greatly appreciated.
       
      The link to the page is as follows: http://www.friendsofthecancercentre.com/wish-upon-a-star/
      <?php $out = ''; if($q = $sanitizer->selectorValue($input->get->q)) { // Send our sanitized query 'q' variable to the whitelist where it will be // picked up and echoed in the search box by the head.inc file. $input->whitelist('q', $q); // Search the title, body and sidebar fields for our query text. // Limit the results to 50 pages. // Exclude results that use the 'admin' template. $matches = $pages->find("star.message|star.who|star.from*=$q,"); $count = count($matches); if($count) { $out .= "<h2>Found $count fields matching your query:</h2>" . "<ul class='nav'>"; foreach($matches as $m) { $out .= " <li><p><a href='{$m->url}'>{$m->title}</a><br />{$m->summary}</p></li>"; } $out .= "</ul>"; } else { $out .= "<h2>Sorry, no results were found.</h2>"; } } else { $out .= "<h2>Please enter a search term in the search box (upper right corner)</h2>"; }
    • By landitus
      I think this could be a bug. I'm using an Options field to create an array of radio fields. This field is required. Each option activates a conditional field and this works perfectly. I added a required if condition to this conditional fields, on a template level, and this is displayed correctly with the red *. But the fields are not validated and the page saves nonetheless. I figured since the red asterisk is on, I've configured the fields conditions correctly, right?



×
×
  • Create New...