How could I assign a value to a dynamic query field? I want to make an update of a record.

ac.get(campo) = totalAcumulado.get((String)ac.Name);  <-- Expression cannot be assigned at line 

This is my code:

public void actualizarAcumulados(Map<String, Map<Integer,Integer>> concepto, String campo) {

          Integer totalAC = 0;
          Integer total =  0;
          Integer acum = 0;
          Integer valorAcumulado = 0;
          Map<String, Integer> totalAcumulado = new Map<String, Integer>();

          String nombreFraccFormateado = null;
         List<Acumulado__c> actualizar = new List<Acumulado__c>();

          for (String f : fracc) {
            total =  concepto.get(f).get(13);
            acum = (Integer)acumulado.get(f).Visitas__c;

            if (acum != null) {
                totalAC = total + acum;
                nombreFraccFormateado = f;
                totalAcumulado.put(nombreFraccFormateado, totalAC);

          for (Acumulado__c ac : Database.query('Select Id, Name,'+campo+' From Acumulado__c Where Name In: totalAcumulado.keySet()')) {
              valorAcumulado = (Integer)ac.get(campo);
              if (valorAcumulado != totalAcumulado.get(ac.Name)) { 

                ac.get(campo) = totalAcumulado.get((String)ac.Name);   


          if (!actualizar.isEmpty()) update actualizar;   



2 Answers 2


If you take your SOQL outside of the for loop, you can use dynamic SOQL. Here is an example:

string queryString = 'SELECT id, Name,' + campo + 'FROM From Acumulado__c Where Name In: totalAcumulado.keySet()';
List<Acumulado__c> aList = Database.query(queryString);
for (Acumulado__c ac : aList ) { ...

You don't need to cast the Name field either. You can just reference that variable directly:




Lastly, you need to use a set to set the field value, like this:


Use the same method as a any map:

ac.put(campo, totalAcumulado.get(ac.Name) );

No need for casting (pointed out by the other answer )

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .