function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Cesar Ramirez Vasquez005391619375684564Cesar Ramirez Vasquez005391619375684564 

How can i assign a different value to a string dynamically so everytime the user insert a record the value change +1 ?

I need to do this by apex code if it is possible i know you can just change the fiel type to auto number in SF, im just curious about a string field 
DonRobinsDonRobins
There are common and long used ways to do this commonly implemented in other database technologies, the challenge is insuring that multiple users adding records simultaneously don't collide and end up using the same counter. To that end, you must somehow implement a lock on a counter field stored somewhere, perhaps in a custom object, that you could lock when the value is fetched to be incremented and assigned to your record as a key. You can lock the counter seed record by adding the FOR UPDATE phrase to your SOQL query, and it will be released after your Apex transaction commits.The key point is that you will indeed need to consider this kind of approach, regardless of how you store and set the value, and it likely isn't worth the effort - why not just use AutoNumber?   


Cesar Ramirez Vasquez005391619375684564Cesar Ramirez Vasquez005391619375684564
Im having some troubles trying to get that number. This is my problem : 
I have a VF page to insert invoices, every invoice have multiple lines (a list fill with products by the user) if the invoiceID field is an autonumber, how can i get this value to insert the lines in the object line ? My method first insert an invoice then i create a loop to insert every line but i dont know how to get that number. My method looks is the following :

current_factura.Descuento__c = STR_DESC;
        current_factura.Efectivo__c = false;
        current_factura.Estado__c = 'Pagado';
        current_factura.Fecha_y_Hora_de_Factura__c = system.now().addHours(-6);
        current_factura.Forma_de_Pago__c = 'Tarjeta';
        current_factura.Porcentaje__c = 0;
        current_factura.Subtotal__c = total_str;
        current_factura.Tarjeta__c = true;
        current_factura.Total__c = total_final;
        current_factura.Vuelto__c = 0;
        
        insert(current_factura);
       
        try{
        for  ( Producto__c C : CARRITO) {
       
        Linea.Cantidad__c = C.CantidadExistencia__c;
        //Linea.Descripcion__c = C.Descripcion__c;
        Linea.Factura__c = current_factura.Consecutivo__c;
        Linea.Monto_Colones__c = C.Precio__c;
        Linea.Monto_Dolares__c = 0;
               
        Linea.Producto__c = C.Codigo__c;
    
        insert(Linea);
      
        }

Thanks for your time !