volume one
volume one

Reputation: 7563

How to set a dynamic key name in a struct?

I am looping through a query and want to set the name of a struct key and its value dynamically. But I can't seem to get it to work because its not interpreting the dynamic value properly - it thinks its the actual name of the key. Here's what I mean

<cfloop query="rsSettings">
 <cfset APPLICATION.Config.Settings[rsSettings.CompanyID] = StructNew()>
 <cfset APPLICATION.Config.Settings[rsSettings.CompanyID].#rsSettings.Name#" = rsSettings.SettingValue/>
</cfloop>

I need the #rsSettings.Name# part to be the name value stored in that recordset e.g. "MaxOrders"

I tried putting quotes around it like this <cfset APPLICATION.Config.Settings[rsSettings.CompanyID]."rsSettings.Name" = rsSettings.SettingValue/> but it doesn't work.

What can I do to make it accept a dynamic key name?

Upvotes: 1

Views: 3663

Answers (1)

Pankaj
Pankaj

Reputation: 1741

To make dynamic keys in a structure, you need to follow square [] braces notation. You can do it as follows:

<cfloop query="rsSettings">
     <cfset APPLICATION.Config.Settings[rsSettings.CompanyID] = StructNew()>
     <cfset APPLICATION.Config.Settings[rsSettings.CompanyID][rsSettings.Name] = rsSettings.SettingValue/>
</cfloop>

If you have multiple settings for a company (as mentioned by Joe) that you are getting from rsSettings query, then in that case you may need to check if the companyID already exists in APPLICATION.Config.Settings. Like this:

    <cfloop query="rsSettings">
         <cfif NOT structKeyExists(APPLICATION.Config.Settings, rsSettings.CompanyID) >
              <cfset APPLICATION.Config.Settings[rsSettings.CompanyID] = StructNew()>
         </cfif>
         <cfset APPLICATION.Config.Settings[rsSettings.CompanyID][rsSettings.Name] = rsSettings.SettingValue/>
    </cfloop>

Upvotes: 4

Related Questions