Jump to content
GuruMeditation

Function Snippets

Recommended Posts

Hello everyone. 
 
I thought I'd share a few of the functions I've been working on in case any new users etc find them useful. I've not been programming in PHP long, so excuse the sloppy code, and if you find any errors etc, let me know and I will update it.
 
The following function basically takes your $page date and returns it in either hours and minutes if the page is less than a day old, or as sandard if it's older. This could also be extended to display the date as yesterday etc as well.

If people are interested, I can add more, and feel free to add your own.

function formatDate($itemDate)
{

  // Let's check the item date against the current date so that we can work out the date and time difference.
  $itemDateTime = new DateTime($itemDate);
  $currentDateTime = new DateTime('now');
  $interval = $itemDateTime->diff($currentDateTime);
  $day = $interval->format('%d');
  $hour = $interval->format('%h');
  $minute = $interval->format('%i');

  // If it's less than a day, display the date as hours and minutes since the post.
  // $day == 0 means there is no day difference, i.e we know it is on the same day.
  if($hour < 24 && $day == 0){
    // If it's been less than an hour.
    if($hour < 1){
      if($minute == 0){
        $itemDate = "less than a minute ago";
      }
      elseif($minute == 1){
        $itemDate = $minute . " minute ago";
      }
      else{
        $itemDate = $minute . " minutes ago";
      } 
    }
    // If it's been more than an hour and less than a day.
    elseif($hour >= 1 && $hour < 24){
      if($hour == 1 && $minute == 0){
        $itemDate = $hour . " hour ago";
      }
      elseif($hour == 1 && $minute == 1){
        $itemDate = $hour . " hour and " . $minute . " minute ago";
      }
      elseif($hour == 1 && $minute > 1){
        $itemDate = $hour . " hour and " . $minute . " minutes ago";
      }
      elseif($hour > 1 && $minute == 0){
        $itemDate = $hour . " hours ago";
      }
      elseif($hour > 1 && $minute == 1){
        $itemDate = $hour . " hours and " . $minute . " minute ago";
      }
      elseif($hour > 1 && $minute > 1){
        $itemDate = $hour . " hours and " . $minute . " minutes ago";
      }
    }
  }
  // If it's more than a day, just post the standard date.
  else {
    $itemDate = $itemDate;
  }

return $itemDate;
}

The following function can be used in conjunction with the formatDate($itemDate) above.
 

/* This function outputs each article / page header according to how we want it.
** $icon = Font Awesome icon etc, i.e "fa fa-link" which could be used if we create a links system.
** $item = Usually the $page we call the function from.
** $type = A string in the form of Article, Link etc.
** Example: If we call the function with the following args showItemHeader("fa fa-link", $link, "Link");
** We will see the following displayed: (link icon) Link published 22 hours ago in Website Links 
** Obviously change the markup to suit your own needs.
*/

function showItemHeader($icon, $item, $type)
{

 echo "<h3><a href='{$item->url}'>{$item->title}</a></h3>" .
      "<h6><i class='$icon'></i> " . $type . " published: " . formatDate($item->date) . " in " . "<a href='{$item->parent->url}'>{$item->parent->title}</a></h6>";

}
  • Like 1

Share this post


Link to post
Share on other sites

There's a function for that in core

echo wireRelativeTimeStr($page->modified);

You're welcome.

Just a note: Doesn't work well with when caching. ;)

  • Like 4

Share this post


Link to post
Share on other sites

I'm sorry to tell you.

In /wire/core/functions.php there you have the wireRelativeTimeStr function.

echo wireRelativeTimeStr(1400586357); // 1400586357 = unix timestamp

(Soma wins.....)

Edited by Martijn Geerts
  • Like 3

Share this post


Link to post
Share on other sites

There's a function for that in core

echo wireRelativeTimeStr($page->modified);
You're welcome.

Just a note: Doesn't work well with when caching. ;)

I'm sorry to tell you.

In /wire/core/functions.php there you have the wireRelativeTimeStr function.

echo wireRelativeTimeStr(1400586357); // 1400586357 = unix timestamp

Sorry Gurumeditation...

Between the amazing stuff in ProcessWire and the stellar support community, it can be hard to do any work around here! Talk about "RelativeTime": 9 minutes from post to double answer.

Thanks,

Matthew

  • Like 3

Share this post


Link to post
Share on other sites

LOL - No need to apologise. I often reinvent the wheel. It's great to know these methods.

How do you find this magic? Where is it hidden? I'm keen to find the other hidden goodies.

Oh well, it was a nice coding exercise.  :lol:

Edit: I found the hidden goodies in the Functions.php file in wire/core (as Martijn mentioned, and I missed) - Nice.

  • Like 3

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 David-M
      anyone, any ideas how to solve? 
      i get following error on a website:
      Notice: Undefined variable: out in /var/sites/i/islandmemorials.co.uk/public_html/site/templates/includes/functions.php on line 43
      and this is a code in that very functions file:
      <?php function numberOpen() { date_default_timezone_set("Europe/London"); $currentHour = date('G'); if($currentHour > 9 && $currentHour < 21) { $openFor = 21 - $currentHour; if($openFor > 1) { echo "We're currently open for another ".$openFor." hours, why not pop in?"; } else { echo "Our lines are open for another hour - <a href=\"tel:+01983 857 600\">01983 857 600</a>"; } } else { echo "Unfortunately, our lines are currently closed, but you can still send a message below"; } } function getSubNav($pid) { $test = wire('pages')->get("/services/"); $parents = wire('page')->parentID; $template = wire('page')->template; $out = ''; //echo "pid".$pid."<BR>"; //echo "parents".$parents."<BR>"; //echo "template".$template."<BR>"; $children = $test->children; foreach($children as $child) { $class = $child->id === $pid ? " active" : 'inactive'; if ($child->id === $pid ) { $class= 'active'; } elseif ($template= "memorials" && $child->id === $parents ) { $class= 'active'; } $out .= "<li><a class='{$class}' href='{$child->url}'>{$child->title}</a></li>"; } return $out; } ?> i suppose this has to do with a variable scope, but not sure
    • By louisstephens
      I am wondering, how do you pass a variable into wire('page')->get() inside a function? I have been looking through the forums, but unfortunately I have not found the answer yet.
      My current set up is:
      function generateNewPages($parentPageName) { $p = new Page(); $p->template = "parent"; $p->parent = wire('pages')->get('/home/'); $p->name = $parentPageName; $p->title = $parentPageName; $p->of(false); $p->save(); $p2 = new Page(); $p2->template = "child"; $p2->parent = wire('pages')->get('$parentPageName'); $p2->name = "child"; $p2->title = "Child Page"; $p2->of(false); $p2->save(); } When I try to run it by passing in a title like generateNewPages('Demo');, "Demo" is created, but when it gets to the child page I get:
      Unknown Selector operator: '$' -- was your selector value properly escaped?
      Is there a way to pass the $parentPageName to "wire('pages')->get('$parentPageName')" ?
    • By Guy Incognito
      Just wondering what software/approaches others take to the management of their code snippets.
      Relatively new to PW and finding that its logical approach is making it far easier for me to reuse code in projects and encourages me to try and be more organised!
      I've looked at few notes apps that piggyback of Gists - although I'm not sure if Gists is a good idea for private project work seeing as they're never totally private.
    • By celfred
      Hello,
      Another newbie question. My Processwire sites is growing and I'm wondering if my way of doing things sounds goog to you. I tend to avoid what I consider 'heavy and frequent' database requests in my functions. For example :
      // In functions.php myfunction($player) { wire('$pages')->find("myselectors"); // This means about 300 database requests do something... (like $p->newTmpField = 1;) return $player; } // In template.php $allPlayers = $pages->find("template=player"); // About 300 players foreach ($allPlayers as $p) { myfunction($p); } // Now I have access to newTmpField, for example.  I tend to replace with :
      // In function.php myfunction($allPlayers) { foreach($allPlayers as $p) { // do something like set $p->newTmpField = 1 } return $allPlayers; } // In template.php $allPlayers = $pages->find("template=player"); myfunction($allPlayers); // Now $players have been modified. For example, I have $allPlayer->find("newTmpField=1"); So for the moment, I tend to choose the second solution which makes only 1 database request, but what do more experimented developers would recommend ?
      What I find useful with Page objects in functons arguments is that I have the whole 'tree' I can then 'find' in my function. But as you can see, I need to understand things better. I have a feeling my 'practical' explanation is not really convincing 🙂 
      Thanks if someone can take a few minutes to give me advice !
    • By celfred
      Hello,
      I've been struggling ALL day on my loading time problem and I'm stuck... As I said somewhere else on the Forum, I'm discovering TracyDebugger module to try and help me (and it does help !), but I'm still in a dead-end.
      Tracy told me one of my page loads about 4,500 pages and I can't find any way to make it less (and let me tell you that my website is far from having so many users/visitors or whatever, it's just a teacher's website to try to work differently in class).
      I have a feeling I am mis-understanding some concepts here. The page can be seen there : http://planetalert.tuxfamily.org/players/4d (for example, but the problem is the same for all teams in my site). As you can see, there are many information on this page, but not that much either I guess for a computer, but it takes 20 seconds to load ! It feels like my page loads just about EVERYTHING that resides in the backend, but I just can't understand by looking a tmy code. For example, the little green and red circles next to the player's names show the actions that have been saved on the last day (so usually 3-5 actions at most, except for players doing online exercises who may have 10 actions). My query is :
      $lastEvent = $player->child("name=history")->children("sort=-date")->first(); // Get all events on same day $prevDay = date("m/d/Y", $lastEvent->date); $prevDate = $prevDay.' 0:0:0'; // Select events for the whole day $prevEvents = $player->child("name='history'")->children("date>=$prevDate"); $trend = ''; foreach ($prevEvents as $event) { $HP = $event->task->HP; $title = $event->task->title; if ($HP < 0) { $trendClass = 'negativeTrend'; } else { $trendClass = 'positiveTrend'; } if ($event->summary !== '') { $summary = ' ('.$event->summary.')'; } else { $summary = ''; } $trend .= '<span class="'.$trendClass.'" data-toggle="tooltip" data-html="true" title="'.strftime("%d/%m", $event->date).': '.$title.$summary.'">&nbsp;</span>'; } But in Tracy pages, I see that the COMPLETE history for EACH player is loaded ! I thought my code was limiting it to the events appearing on the same day as the last saved event. Do you see where I am wrong ?
      What's more : I feel like I must do the same mistake for the players (they are all in althought I'm limiting to the particular team). I must say though, that I'm caching (supposively) ALL players when Admin is logged in so he can have a faster access in the top menu.
      More? All places and people that players can free are loaded as well. Why is this? I just want to load the places and people that are actually freed by players and show the names (not complete info). I'm not putting an example of the code here because I have a feeling the problem resides in my way of organising the complete thing... and that's what worries me the most... Maybe it's gonna be hard for one of you to understand (and have the time) my awkward way of organizing things (even though I'm trying hard to be well-organized ). So I'd rather point to the Github repository : https://github.com/celfred/PlanetAlertProfile/tree/master/site/templates
      The file I'm talking about above is team.inc.php. It is included in list-all.php which includes head.inc and foot.inc as well.
      Things have changed quite a bit on my local site today, but I'm getting in such a mess that I'd rather not commit to remote. I've corrected some things, but what I have just explained above is still there
      While I'm at it. Other page, other problem detected : my adminTable.php page which you can a look at at : http://planetalert.tuxfamily.org/players/adminTable/4d (I've just noticed that it should be acess restricted, but nevermind for today, don't submit just in case I forgot other things... _ yes, I'm desperate tonight...) and which submits to submitForms.php. Well, I had to put AJAX request for that because it was running into a timeout because of the loading time. It worked (althought I ended up waiting 30 seconds to record my table !) but today, Tracy and debug ON showed me the 'Maximum 100 nested functions limit fatal error' after hours of research, I endend up... writing this post I know my function updateScore() (in my-functions.php) is difficult, but what?? It just updates the scores depending on the task being recorded then checks the impact on other players and if it does have an impact, it triggers itself back to update the score of that other player. But yes, I know it can be some sort of never-ending story, but how can I do differently ? I wonder if it's ok to have wire('pages') in so many of my functions. But again, how can I do in another way?
      Well, sorry for such a long post, folks, but as you can understand, I'm facing a wall here and I hope someone around here will find some time to try and find his or her way into my code and give me a hint on where I could improve.
      I have had so many help from this community in the past and it felt such a relief and a revelation (Ended up telling my wife : "Wow, it looks so simple for these guys ! I've spent so many hours on that and... Of course ! Now I get it !! I'm getting better ! No next time !")
      Well, today is a 'next time'...
      Thanks if you've read up to this point and THANKS if you go and have a look at my code !
      Fred.
×
×
  • Create New...