Jump to:

23581 Posts in 19403 Topics by 2893 members

General Questions

SilverStripe Forums » General Questions » ArrayLists & foreach question

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Page: 1
Go to End
Author Topic: 1564 Views
  • socks
    Avatar
    Community Member
    190 Posts

    ArrayLists & foreach question Link to this post

    SS3.0.2

    I'm trying to replicate the comma separated field for the Tags in BlogEntry.php. I'm pretty close, but not very familiar with PHP. I'm doing this since widgets can't use a Gridfield.

    I have 2 textfields in a widget where both accept comma separated data. (I have it working with just the one field, but not sure how to get the second field into the same Array or if I should do two foreach loops and combine them somehow.

    class VideoWidget extends Widget {
       
       static $db = array(
          'VideoTitle' => 'Varchar(150)',
          'VideoLink' => 'Text'
       );

    public function getVideos() {
          
          $videos = preg_split(" *, *", trim($this->VideoLink));
          $titles = preg_split(" *, *", trim($this->VideoTitle)); // how do I get this second field into the array?
          $output = new ArrayList();
          
          foreach($videos as $video) {
             $output->push(new ArrayData(array(
                'VideoLink' => $video,
                'VideoTitle' => $title
             )));
          }
          
          if($this->VideoLink) {
             return $output;
          }
          
       }

    }

    Thank you

  • Kirk
    Avatar
    Community Member
    42 Posts

    Re: ArrayLists & foreach question Link to this post

    In the foreach loop for $videos you are trying to push $title into the array however this has not been defined yet.
    If you are sure that VideoLink and VideoTitle are going to have the same number of elements you could do something like below

    $i = 0;
    foreach($videos as $video) {
    $output->push(new ArrayData(array(
    'VideoLink' => $video,
    'VideoTitle' => $titles[$i]
    )));
    // increment $i so the next element will be read
    $i++;
    }

    One thing you will also need to consider is a video title with a comma in the name for example the film "The Good, the Bad and the Ugly" has a comma in the name which would end up being split into "The Good' and the " the Bad and the Ugly"

  • socks
    Avatar
    Community Member
    190 Posts

    Re: ArrayLists & foreach question Link to this post

    Yep both Link and Title will have same number and I did consider the issue with commas in the title, but thanks for the heads-up.

    Thanks Kirk! Just what I needed

    1564 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.