Velocity Script to Loop through Custom Objects

companyman
Level 1

Velocity Script to Loop through Custom Objects

Hello, all. I am fairly new to Velocity scripting. Our Marketo Custom Objects store multiple fields of Engagement data that users submit through a form. I am trying to access the Product value on any number of Custom Objects/Engagements a lead may have.

 

When I drag the Product field into the Edit Script Token window it appears like this:

 ${marketoEngagement_cList.get(0).Product__c}

 

This will show the most recent value for Product that a lead submitted. I know that I can change the get(0) to get(1) to look at the second most recent, but how do I iterate through all of the potential engagements a lead may have to see the value of Product on each one?

 

Essentially, what I'm trying to do right now is to check if a particular value exists on any of the Product fields for any of the Custom Objects/Engagements. I will need to do more conditional checks later though, so I don't want to just do this for each one:

#set($lastProduct = ${marketoEngagement_cList.get(0).Product__c})
#if($lastProduct.contains("Product Name"))

 

3 REPLIES 3
SanfordWhiteman
Level 10 - Community Moderator

Re: Velocity Script to Loop through Custom Objects

Use a #foreach loop. There are thousands of examples here on Marketing Nation if you search.

 

Why are you using .contains() instead of .equals()?

companyman
Level 1

Re: Velocity Script to Loop through Custom Objects

Hi, Sanford. First of all, I have to say thank you, as you've been so helpful to others and by proxy myself as I've searched these forums.

 

My main issue is that I don't know how to apply a #foreach loop to 

${marketoEngagement_cList.get(0).Product__c}

My first guess was to do .get($i) but I don't know how to write a #foreach loop in this syntax and none of the examples I've found on this forum have an example that uses an index built into the reference. Most examples are simpler: 

#foreach ($item.emailLinkToPerson in $car_cList)
  #set ($count = $count + 1)
#end

I am using .contains() because there are variations of each Product which all include a parent name.

SanfordWhiteman
Level 10 - Community Moderator

Re: Velocity Script to Loop through Custom Objects

I still would advise against .contains() unless the placement of the parent name is truly unpredictable.

 

Anyway, you loop like this:

 

#foreach( $marketoEngagement in $marketoEngagement_cList )
#if( $marketoEngagement.Product__c.startsWith("Something") )
## do something
#end
#end