Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

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

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

ArrayLists & foreach question


Go to End


3 Posts   5572 Views

Avatar
socks

Community Member, 191 Posts

4 November 2012 at 11:11am

Edited: 04/11/2012 11:13am

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

Avatar
Kirk

Community Member, 67 Posts

6 November 2012 at 1:58pm

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"

Avatar
socks

Community Member, 191 Posts

7 November 2012 at 2:04pm

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 :)