Jump to:

3447 Posts in 1032 Topics by 872 members

Template Questions

SilverStripe Forums » Template Questions » Conditional with just part of a date

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Page: 1
Go to End
Author Topic: 948 Views
  • Laurie
    Avatar
    Community Member
    21 Posts

    Conditional with just part of a date Link to this post

    In my db I have a series of projects, each with a StartDate and EndDate.

    So, for example...

    Name: Project 1; StartDate: 1/1/2009; EndDate: 12/31/2009
    Name: Project 2; StartDate: 7/1/2007; EndDate: 6/30/2012

    When displaying these projects, I only want to display the year AND if the start and end dates are in the same year, I would only like to show the year once (i.e., 2009 rather than 2009-2009)

    So, for the above example, I'd like the output to be...

    Project 1 (2009)

    Project 2 (2007-2012)

    How can I compare just the years from the date fields to determine whether to output (StartDate.Year) or (StartDate.Year-EndDate.Year) in my template?

    Thanks so much!

    Cheers,
    Laurie

  • Hamish
    Avatar
    Community Member
    712 Posts

    Re: Conditional with just part of a date Link to this post

    Rather than trying to do this in your template, add a new function to your Project object that creates the string for you.

    eg:

    function Years() {
    $start = $this->dbObject('StartDate')->Year();
    $end = $this->dbObject('EndDate')->Year();
    return ($start == $end) ? $start : "{$start} - {$end}";
    }

    Now in your template you can just do:

    $Project.Name ($Project.Years)

  • Laurie
    Avatar
    Community Member
    21 Posts

    Re: Conditional with just part of a date Link to this post

    Thanks Hamish!

    I had tried something similar, but didn't have the syntax quite right. Your code worked perfectly. Thanks again.

    948 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.