Sandiip Patil
Sandiip Patil

Reputation: 446

Map not working when trying to get by entity name

I am using Telosys tool to generate entity classes and it is doing wonders for me. However I have a specific requirement to change some attributes of entities.

I have loaded all the attributes that need to be changed in a map and parsed it in my entity template. But when I am trying to iterate through the map using entity.name it fails saying there is no get method. This is my map: sample_map.vm

#set( $map = {
 "AABUHA": "Name",
 "ABAKTX": "Code",
 "ABABDZ": "Date"
 }

I parsed it in my template like this:

#parse("include/sample_map.vm")

And this is how I am trying to fetch the value for the corresponding entity

$map["${entity.name}"]

I also tried:

($map.get($field.name))

The error I get is either

$!map.[: no attribute '['

Or no method get()

Surprisingly, this works fine when I pass the value as hardcoded string.

Any suggestions please

Upvotes: 0

Views: 175

Answers (2)

lgu
lgu

Reputation: 2460

Technically my first answer works, but if you need to add specific information about an entity a "map" in the templates is not the best option (this information should be in the model).

So, I suggest using a "tag" ( # + tag name) positioned at the entity level (or attribute level) in your model ( in “.entity” file ).

For example:

In “.entity” file (a tag 'OtherName' with a tag value):

#OtherName("Empl")
Employee
{
id : int { @Id } ;
firstName : string { #MyTag("xyz") } ;
}

In “.vm” file:
Usage 1 :

#if ( $entity.hasTag('OtherName') )
 name : $entity.tagValue('OtherName')
#else
 name : $entity.name
#end

Usage 2 - the simplest (with default value if no tag in entity) :

name : $entity.tagValue('OtherName', $entity.name)

Note : Tags are available at entity level since Telosys 4.0.0

See hasTag() and tagValue() in :

Upvotes: 0

lgu
lgu

Reputation: 2460

In Velocity the error “: no attribute '['” ( or "no method 'get'" ) occurs when the key doesn’t exist in the map.

So, I suppose that in your case you try to get an “entity.name” that is not defined in the map.

To check if a key is defined in a map you can use : $map.containsKey("xx")

See example here : https://doc.telosys.org/templates/velocity-objects#map

You can also use : $map.getOrDefault(“key”, "default_value") to get a default value if the key doesn’t exist in the map

Upvotes: 1

Related Questions