• Cesar Ramirez Vasquez005391619375684564
  • NEWBIE
  • 50 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 32
    Replies
Hi i have created a trigger that checks before inserting a record of type Factura__c, if the master-relationship field (Empresa_Cliente__c) exist, and if it dont the trigger create a new one with the value contained in the field Empresa_Cliente__c.
The master relationship is between Factura__c (custom object) and Account. But when i try to save a record the trigger doesnt fire and i keep receiving the salesforce validation error (Error: No matches found.) in that field. Any suggestions this is my trigger :

trigger insertAcc on Factura__c (before insert) {
System.debug(Logginglevel.ERROR , ' ::::::: Empresa Cliente :::::::::::::' + trigger.New[0].Empresa_Cliente__c) ;
if(Trigger.isBefore)
  {
     if(Trigger.isInsert)
      {
  
List<Account> a = [select name, CodigoNAF__c from account where CodigoNAF__c = :trigger.New[0].Empresa_Cliente__c];
System.debug(Logginglevel.ERROR , ' ::::::: List :::::::::::::' + a) ;
if (a == null){
Account acc = new Account();
acc.Name = trigger.New[0].Empresa_Cliente__c;
acc.CodigoNAF__c = trigger.New[0].Empresa_Cliente__c;
insert (acc);

System.debug(Logginglevel.ERROR , ' ::::::: acc :::::::::::::' + acc) ;
}

}
}
}

The trigger is not firing when i try to save a record it just keep throwing me an error in the master-relationship field (Error:Error: No matches found) . Remember the value i put in the field doesnt exist that is the point of the trigger, create a new Account with the value provided in Empresa_Cliente__c and then save the new Factura__c record without errors.

Hi i created a trigger that checks before inserting a record of type Factura__c, if the master-relationship field exist, and if it dont the trigger create a new one with the value contained in the field Empresa_Cliente__c.
The master relationship is between Factura__c (custom object) and Account. But when i try to save a record the trigger doesnt fire and i keep receiving the salesforce validation error (Error: No matches found.) in that field. Any suggestions this is my trigger :

trigger insertAcc on Factura__c (before insert) {
System.debug(Logginglevel.ERROR , ' ::::::: Empresa Cliente :::::::::::::' + trigger.New[0].Empresa_Cliente__c) ; 
List<Account> a = [select name, CodigoNAF__c from account where CodigoNAF__c = :trigger.New[0].Empresa_Cliente__c];
System.debug(Logginglevel.ERROR , ' ::::::: List :::::::::::::' + a) ; 
if (a == null){
Account acc = new Account();
acc.Name = trigger.New[0].Compania__c;
acc.CodigoNAF__c = trigger.New[0].Empresa_Cliente__r.CodigoNAF__c;
insert (acc);

System.debug(Logginglevel.ERROR , ' ::::::: acc :::::::::::::' + acc) ;
}

}
Just for information CodigoNAF__c is a custom field i created within Account object.
I am trying to update my custom object Propiedad__c that has a master-detail relationship with a custom object called User__c; that master detail relationship already has read/write permissons; the worst part is that i dont even wanna update that field so im not setting any value but i keep getting the error Field is not writeable: Propiedad__c.User__c.
This is the snipet of my code that is failing:
public void actualizar(){
    Cookie lol = ApexPages.currentPage().getCookies().get('ID');
    try{
    Propiedad__c p = new Propiedad__c(id = prop.id);
    p.AmbosIdiomas__c= prop.AmbosIdiomas__c;
    p.Ba_os__c = prop.Ba_os__c;
    p.Canton__c = prop.Canton__c;
    p.Caracteristicas_Especiales__c = prop.Caracteristicas_Especiales__c;
    p.Caracteristicas_Especiales_EN__c = prop.Caracteristicas_Especiales_EN__c;
    p.Categoria__c = prop.Categoria__c;
    p.Descripcion__c = prop.Descripcion__c;
    p.DescripcionEN__c = prop.DescripcionEN__c;
    p.EmailDue_o__c = prop.EmailDue_o__c;
    p.Habitaciones__c = prop.Habitaciones__c;
    p.Lote__c = prop.Lote__c;
    p.Nombre__c = prop.Nombre__c;
    p.NombreDue_o__c = prop.NombreDue_o__c;
    p.Precio__c = prop.Precio__c;
    p.Provincia__c = prop.Provincia__c;
    p.Renta__c = prop.Renta__c;
    p.Telefono1__c = prop.Telefono1__c;
    p.Telefono2__c = prop.Telefono2__c;
    p.Tipo__c = prop.Tipo__c;
    p.Venta__c = prop.Venta__c;

   
    update p;
    if (FileCount != null && FileCount != ''){
    SaveAttachments();
    }
    if (language == 'ES'){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm,'Propiedad actualizada con exito.'));
    }
    else{
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm,'Property successfully updated.'));
        }
       
        refreshEdit();
    }
    catch(Exception B){
     ApexPages.addmessages(B);
    }
    }

Prop is filling in the constructor and is bind to my VF that way i can get the new values; but im unable to update

Hi guys ! Lately im having some seriuos troubles inserting Factura__c records because they have a master-detail relationship with accounts (called Empresa_Cliente__c) and sometimes the account doesnt exist and the insert fail. So i was building a trigger that checks if the account exist and if it dont create a new one with the field Codigo_NAF__c of Factura__c object. The problem is that trigger isnt working, it doesnt fire; do you guys now where maybe the issue ? Is that possible ?
Account has a custome field called Codigo_NAF__c just for info and the trigger is already active; but when i create a new record of type Factura__c and try to enter an Account that doesnt exist the trigger doesnt fire and i just receive the validation error that says: Please insert a valid account (something like that).

This is my trigger:
trigger insertAcc on Factura__c (before insert) {

System.debug(Logginglevel.ERROR , ' ::::::: Empresa Cliente :::::::::::::' + trigger.New[0].Empresa_Cliente__c) ; 
List<Account> a = [select name, Codigo_NAF__c from account where Codigo_NAF__c = :trigger.New[0].Empresa_Cliente__c];
System.debug(Logginglevel.ERROR , ' ::::::: List :::::::::::::' + a) ; 
if (a == null){
Account acc = new Account();
acc.Name = trigger.New[0].Empresa_Cliente__c;
acc.Codigo_NAF__c = trigger.New[0].Empresa_Cliente__c;

insert (acc);


System.debug(Logginglevel.ERROR , ' ::::::: acc :::::::::::::' + acc) ;
}

}

I hope someone can help me ! Thanks in advance !

 

Hi everyone ! This is my scenario; i have an object called Facturas__c, when i insert a record in that object it has a lookup to Account (lookup to my custom field Codigo_NAF__C); so my trigger basically search if the Account exist and if the account does not exist, it create a new one so the record can be inserted without any issues.

trigger insertAcc on Factura__c (before insert) {

System.debug(Logginglevel.ERROR , ' ::::::: Empresa Cliente :::::::::::::' + trigger.New[0].Empresa_Cliente__r.Codigo_NAF__c) ; 
List<Account> a = [select name, Codigo_NAF__c from account where Codigo_NAF__c = :trigger.New[0].Empresa_Cliente__r.Codigo_NAF__c];
System.debug(Logginglevel.ERROR , ' ::::::: List :::::::::::::' + a) ; 
if (a == null){
Account acc = new Account();
acc.Name = trigger.New[0].Empresa_Cliente__c;
acc.Codigo_NAF__c = trigger.New[0].Empresa_Cliente__c;
insert (acc);

trigger.New[0].Empresa_Cliente__c = acc.id;

System.debug(Logginglevel.ERROR , ' ::::::: acc :::::::::::::' + acc) ;
}

}

Any help what i am missing would be great ! Thanks for your time !
In my VF page i have a function that allows the user to select the lookup field that he wants and fill an input field (this action works like a charm); after that i have a command link that updates the record but im unable to get the value from the input field, the value is always null. How can i achieve this ? I have been stuck for 3 days now, i would appreciate any help. Thanks in advance.

VisualForce:
<apex:pageBlockTable id="srch_id" value="{!Piezas}" var="o">
            
            <apex:column value="{!o.Name}"> <apex:facet name="header"> </apex:facet> </apex:column>          
            <apex:column value="{!o.Producto__r.Name}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Bodega__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Estado__c}"> <apex:facet name="header"></apex:facet> </apex:column>
            <apex:column value="{!o.Reparaci_n_ETL__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column headerValue="Opciones" >
          
                   ---------------------------------------------------This is the value im trying to get--------------------------------------------------
           
                  <apex:inputField id="Reparacion" value="{!PI.Reparaci_n_ETL__c}" />

           -------------------------------------------------------------------------------------------------------------------------------------------------------------
 
                    <apex:commandLink value="Agregar a Reparacion" action="{!actualizaPieza}">
                            <apex:actionSupport event="onclic"/>    
                            <apex:param name="namePieza"   assignTo="{!piezaActual}" value="{!o.Name}"  />
                            <apex:param name="rep" assignTo="{!idRep}" value="{!PI.Reparaci_n_ETL__c}"  />
                   </apex:commandLink>
                  
            </apex:column>
           
        </apex:pageBlockTable>


Controller:

public class addPiezaController {

public String order {get; set;}
public List<Pieza__c> Piezas = new List<Pieza__c>();
public String piezaActual {get; set;}
public String idRep {get; set;}

private Pieza__c PI = new Pieza__c();

public void setPI(Pieza__c value) {
    PI = value;
}

public Pieza__c getPI() {
    return PI;
}



public PageReference lol(){
System.debug(LoggingLevel.Error, 'Reparacion ID:' + PI.Reparaci_n_ETL__c);
return null;
}



public addPiezaController (){
order = '';
Piezas = null;
piezaActual = '';
}

public List<Pieza__c> getPiezas(){

Piezas = [select Name, Producto__r.Name, Bodega__c, Estado__c, Reparaci_n_ETL__c from Pieza__c where Orden__r.Name =: order ];

return Piezas;
}

public void actualizaPieza(){

//Id repID = ApexPages.currentPage().getParameters().get('idRep');
System.debug(LoggingLevel.Error, 'Reparacion lololo param:' + idRep );
System.debug(LoggingLevel.Error, 'Reparacion ID:' + PI.Reparaci_n_ETL__c);
System.debug(LoggingLevel.Error, 'Name:' + piezaActual);


Pieza__c P = [select name, Reparaci_n_ETL__c, Estado__c  from Pieza__c where name =: piezaActual];
P.Reparaci_n_ETL__c = PI.Reparaci_n_ETL__c;
P.Estado__c = 'Utilizada en reparación';

Update(P);

getPiezas();
}

}
So i have a function that allows me to search and select the lookup value; after i select 1 and the textbox is filled i use a command link to send that value among others to the controller and update the object but no matter what i do the lookup value is alwais null. Any ideas ? I am stucked, thanks in advance for your time!

Visual Force:
<apex:pageBlockTable id="srch_id" value="{!Piezas}" var="o">
            
            <apex:column value="{!o.Name}"> <apex:facet name="header"> </apex:facet> </apex:column>          
            <apex:column value="{!o.Producto__r.Name}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Bodega__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Estado__c}"> <apex:facet name="header"></apex:facet> </apex:column>
            <apex:column value="{!o.Reparaci_n_ETL__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column headerValue="Opciones" >
          

           
                  //This is the value i am unable to get
                  <apex:inputField id="Reparacion" value="{!PI.Reparaci_n_ETL__c}"/>

           
 
                    <apex:commandLink value="Agregar a Reparacion" action="{!actualizaPieza}" immediate="false">
                            <apex:actionSupport event="onclic"/>    
                            <apex:param name="namePieza"   assignTo="{!piezaActual}" value="{!o.Name}"  />
                            <apex:param name="rep" value="Reparacion"  />
                   </apex:commandLink>
                  
            </apex:column>
           
        </apex:pageBlockTable>

Controller :

public class addPiezaController {

public String order {get; set;}
public List<Pieza__c> Piezas = new List<Pieza__c>();
public String piezaActual {get; set;}
public id idRep {get; set;}

private Pieza__c PI = new Pieza__c();

public void setPI(Pieza__c value) {
    PI = value;
}

public Pieza__c getPI() {
    return PI;
}




//This is the method i am trying to execute
public addPiezaController (){
order = '';
Piezas = null;
piezaActual = '';
}

public List<Pieza__c> getPiezas(){

Piezas = [select Name, Producto__r.Name, Bodega__c, Estado__c, Reparaci_n_ETL__c from Pieza__c where Orden__r.Name =: order ];

return Piezas;
}

public void actualizaPieza(){

//Id repID = ApexPages.currentPage().getParameters().get('idRep');

System.debug(LoggingLevel.Error, 'Reparacion ID:' + PI.Reparaci_n_ETL__c);
System.debug(LoggingLevel.Error, 'Name:' + piezaActual);


Pieza__c P = [select name, Reparaci_n_ETL__c, Estado__c  from Pieza__c where name =: piezaActual];
P.Reparaci_n_ETL__c = PI.Reparaci_n_ETL__c;
P.Estado__c = 'Utilizada en reparación';

Update(P);

getPiezas();
}

}
Can i create another map and fill with the results of those AggregateResults and the update the map posiciones with those values i need to add those two values per user to the other values im getting in posiciones MAP. Any ideas i have been stuck all day with this

public class tablaVentas {


public list <Leads__c> puntos = [select ownerid, Puntos__c, Estado__c from leads__c where ownerid IN (select id from user) order by Puntos__c DESC];
public list <User> users= [select name from user];

//I need to get this values per user and insert them into posiociones Map
public AggregateResult[] ventasSemanales = [Select COUNT(Estado__c)Ventas from  Leads__c where Estado__c = 'Vendido' and Fecha_Venta__c = THIS_WEEK group by owner.name ];
public AggregateResult[]  = [Select COUNT(Estado__c)Ventas from  Leads__c where Estado__c = 'Vendido' and Fecha_Venta__c = THIS_MONTH group by owner.name ];

public List<Posicion> getPositions(){
          
             Map<Id,User> user_map = new Map<Id,User>();
                      
             for( User u : users){
             user_map.put(u.id,u);
                         }
          
            Map<Id, Posicion> posiciones = new  Map<Id, Posicion>();
         
            for(leads__c c : puntos){
              
                Posicion temp = posiciones.get(c.ownerId);
                if(posiciones.get(c.ownerId)==null){ temp = new Posicion() ;}
              
                Integer puntos = integer.valueof(c.puntos__c);
                temp.nombre = user_map.get(c.ownerid).name;
                temp.puntostotal += puntos;
                /*
                if (c.Estado__c == 'vendido'){
              
// i need to insert those values here im pretty new to apex what can i do ??
              
                if (ventasSemanales == null)
                temp.VentasSemanales = (integer)ventasSemanales[0].get('Ventas');
              
                else {
                temp.VentasSemanales = 0;            
                }
              
                if (ventasMensuales == null){
                temp.VentasMensuales = 0;
                }
                else{
                temp.VentasMensuales = (integer)ventasMensuales[0].get('Ventas');
                }
              
                }
                */
                posiciones.put(c.ownerid,temp);
              
            }
          
            return posiciones.values();
       }
This is my scenario, i have the following VF page, i need to get the value of Cantidad in my controller so i can update the quantity selected by the user:
<apex:page action="{!init}" controller="mainControllerV2" showHeader="false" standardStylesheets="true">

<apex:outputPanel id="the_outputpanel2">
    <apex:pageBlock >
    <p>Paso #4 - Agregue los productos a la factura.</p>
         
      <apex:form >
                        
        <apex:pageBlockTable id="srch_id" value="{!ListaSRCH}" var="o">
                      
                           
            <apex:column value="{!o.CantidadExistencia__c}"> <apex:facet name="header"> </apex:facet>
            <apex:inputField value="{!o.CantidadExistencia__c}"/>
             </apex:column>
            <apex:column value="{!o.Codigo__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Descripcion__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Precio__c}"> <apex:facet name="header"></apex:facet> </apex:column>
            <apex:column headerValue="Opciones" >
               
                    <apex:commandLink value="AGREGAR" action="{!add2carrito}">
                            <apex:actionSupport event="onclic" rerender="the_outputpanel3"/>    
                            <apex:param name="idz"   assignTo="{!current_prod}" value="{!o.id}"  />                               
                    </apex:commandLink>
                  
            </apex:column>
           
        </apex:pageBlockTable>
       
      </apex:form>
       
    </apex:pageBlock>
</apex:outputPanel>
</apex:page>

Im not sure whats the value of value="{!o.CantidadExistencia__c}" im pretty new to apex i dont know what variable it references to.

This is my controllers methods:

public List<Producto__c> getListaSRCH(){
Operaciones O = new Operaciones();
//ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error al buscar'));
return O.busqueda(STR_SRCH);
}

public PageReference add2carrito(){
//se tiene el id
//Producto__c P = new Producto__c();

try{
  if(CARRITO!=null){
  Producto__c P =[select id, Name, Precio__c, Codigo__c, Tipo__c,CantidadExistencia__c, Descripcion__c from Producto__c where id=:current_prod limit 1];
 
   if (P.CantidadExistencia__c != 0) {
                       
   
  if(is_present(P)==-1){
 
    P.CantidadExistencia__c = 1;
    CARRITO.ADD(P);
    }
  else{
      if(P.CantidadExistencia__c==CARRITO[is_present(P)].CantidadExistencia__c){
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'El item :'+ P.Descripcion__c + ' se encuentra agotado en el inventario.'));
      }
     
           
      else{
        CARRITO[is_present(P)].CantidadExistencia__c++;
      }
    }
    calcular_total();
   
    }
   
    else{
     
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'El item :'+ P.Descripcion__c +' no tiene existencias en el inventario. Asegurese de ingresar existencia antes de facturar.'));
      }
   
  }
 
}
catch(exception j){ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error al agregar elemento al carrito'+j));}
return null;
}

public Integer is_present(Producto__c P){
  Integer counter = 0;
  Integer answ = 0;
  boolean present = false;
  for( Producto__c C : CARRITO){
    if(C.Codigo__c == P.Codigo__c){answ = counter;present=true;}
    else{counter ++;}
  }
  if(present==false){answ=-1;}
  return answ;
}

public void insertarLinea()
    {
       
        try
        {
        List<Linea__c> lines = new list<Linea__c>(); // crea una lista con las lineas de la factura
            //Para cada producto C en carrito
            for(Producto__c C : CARRITO) {

              
                   Linea__c Line = new Linea__c ();
                   Line.Cantidad__c = C.CantidadExistencia__c;
                   Line.Factura__c = current_factura.id;                 
                   Line.Monto_Colones__c = C.Precio__c;
                   Line.Monto_Dolares__c = 0;
               
                   Line.Producto__c = C.id;
 
                   lines.add(Line); // adding line to list
                                         
                 Producto__c P =[select id, CantidadExistencia__c from Producto__c where id=:C.id limit 1];
                 P.CantidadExistencia__c = P.CantidadExistencia__c - Line.Cantidad__c;         
                
                 update (P);                        
                                         

                                     }

            insert (lines); // Insertamos la lista lineas asi evitamos hacer un insert por cada registro que haya en CARRITO
       
       
       
        }
       
        catch(Exception a)
       
        {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error al insertar la linea. '+a));
        }
       

    }

How can i proceed any ideas, suggestions, i have tried sending the value through apex:param but i dont really knew how to proceed i have been stucked with this for 3 days know.

Thank you 
Controller

public class convertirFactura {


      public Cotizacion__c cotizacion { get; set; }
      public List<Lineas__c> lineaC { get; set; }
      public Factura__c factura { get; set; }
      public LineaF__c lineaF { get; set; }
      public Cliente__c cliente { get; set; }
      public Date Today { get { return Date.today(); }}

      
    public PageReference init() {
   
        Id cotizacionId;
       
        //REMOVE AFTER DEV
       
        if(System.currentPagereference().getParameters().get('cotizacionId')==null){
  
             cotizacionId = [select id from Cotizacion__c limit 1].id;  
        }
        else{
            //param from URL
            cotizacionId = System.currentPagereference().getParameters().get('cotizacionId');
        }
       
        cotizacion = new Cotizacion__c();
        //se cargan los fields que se van ha usar del candidato
        cotizacion = [select id, name, Comentarios__c,Email__c,Estado__c, NombreLead__c, Apellidos__c, PorcentajeImpuestos__c from Cotizacion__c where Id= :cotizacionId];
        lineaC = new List<Lineas__c>();
        for (Lineas__c  L : [select CantidadCajas__c, CantidadUnidades__c, Cotizacion__c, Producto__c, Total_Costos_Linea__c, TtotalVentaLinea__c from Lineas__c where Cotizacion__r.id =:cotizacionId]) {
           
         if (L != null){
          lineaC.add(L);
                       }
                           }
        //initialize the variables
       
        factura = new Factura__c();
        cliente = new Cliente__c();
                            
        factura.Comentarios__c = cotizacion.Comentarios__c;
        factura.Estado__c = cotizacion.Estado__c;
        factura.PorcentajeDescuento__c = cotizacion.PorcentajeImpuestos__c ;
        factura.Fecha_de_Entrega__c = Today;
       
        cliente.Name = cotizacion.NombreLead__c;
        cliente.Apellidos__c = cotizacion.Apellidos__c;
      
  
       
       
       
        back();
       
        return null;
    }

    //insert the new objects and create the lines assingned to the invoice
    public PageReference save() {
      
      
        insert cliente;
      
        factura.Cliente__c = cliente.id;
      
        insert factura;
       
        List <LineaF__c> linFactura = new List <LineaF__c>();
       
        for (lineas__c L : lineaC){
       
        if (L != null){
       
           for(Integer i =0; i < lineaC.size();i++){
       
        lineaF = new LineaF__c();
        lineaF.CantidadCajas__c = L.CantidadCajas__c;
        lineaF.CantidadUnidades__c = L.CantidadUnidades__c;
        lineaF.Factura__c = factura.id;
        lineaF.Producto__c = L.Producto__c;
        lineaF.Total_Costos_Linea__c = L.Total_Costos_Linea__c;
        lineaF.Total_Venta_Lineas__c = L.TtotalVentaLinea__c ;
      
        linFactura.add(lineaF);
       
        Producto__c P = new Producto__c();
        P =[select id, InventarioCajas__c, InventarioUnidades__c from Producto__c where id=:L.Producto__c limit 1];
        P.InventarioCajas__c = P.InventarioCajas__c - L.CantidadCajas__c;
        P.InventarioUnidades__c = P.InventarioUnidades__c - L.CantidadUnidades__c;
       
        Update (P);
        }
      
        }
     }
       
        insert(lineaF);
       

        Pagereference p = new Pagereference('/' + factura.id);
        return p;
    }
    
        public PageReference back() {
            Pagereference p = new Pagereference('/' + cotizacion.id);
            return p;
    }
}
Is that possible, what i should do to achieve that i need to print an invoice after every purchase everyting is ready how can i add this functionally ?
How can i achieve that this are the fields in object Line
Cantidad__c   Number(4, 0)  
Factura__c     Master-Detail(Factura)
Producto__c    Lookup(Producto)
Monto_Colones__c        Currency(16, 2)

I need to Update this fiel from Product__c
CantidadExistencia__c  Number(4, 0)

Basically i want to set CantidadExistencia__c = CantidadExistencia__c - Line.Cantidad__c for each line i insert; this is the code that insert every line:
public void insertarLinea()
    {
       
        try
        {
        List<Linea__c> lines = new list<Linea__c>(); // crea una lista con las lineas de la factura
            //Para cada producto C en carrito
            for(Producto__c C : CARRITO) {

              for(Integer i =0; i < CARRITO.size();i++){ // Creamos un loop para que recorra toda la lista CARRITO y los integre a una nueva lista de lineas
                 
                   Linea__c Line = new Linea__c ();
                   Line.Cantidad__c = C.CantidadExistencia__c;
                   Line.Factura__c = current_factura.id;                 
                   Line.Monto_Colones__c = C.Precio__c;

               
                   Line.Producto__c = C.id;
 
                   lines.add(Line); // adding line to list
                                          }

                                     }

            insert (lines); // Insertamos la lista lineas asi evitamos hacer un insert por cada registro que haya en CARRITO
        }
       
        catch(Exception a)
       
        {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error al insertar la linea. '+a));
        }
       
       
    }
How can i achieve that im pretty new to apex basiclly i want to execute the following sql code everytime a line is inserted:
update Producto__c set CantidadExistencia__c = Producto__c.CantidadExistencia__c - Linea__c.Cantidad__c where Linea__c.Producto__c = Producto__c.id
I tried to write and my trigger looks like this:

trigger ActualizaExistencia on Linea__c(before insert, before update){
  //get a list of all the products ID's contained in the records
  //to be updated.
    Set<Id> ids = trigger.newmap.keySet();
    List<Linea__c> inv=[select id,Cantidad__c from  Linea__c where id IN :ids];


  List<Producto__c> ProIDs = new List<Producto__c>();
  for (Linea__c Ite:trigger.new){
   ProIDs.add(Ite.Producto__c);
  }
  //now get a list of all the records for products that contain the
  //above IDs
  List<Producto__c > Pros = new List<Producto__c >([select id, CantidadExistencia__c from Producto__c
  where id in:ProIDs]);
  //now loop again for all the records being updated and then for each
  //one loop through all the products records retrieved above.
  for (Linea__c obj: trigger.new){
    //we do this for loop differently so that it has an inherent check
    //to ensure that our query above returned some records
    for (integer i = 0; i < Pros.size(); i++){
      //now we make sure the record IDs match
      if (Pros.Producto__c == pros[i].id){
        Pros[i].CantidadExistencia__c = Pros[i].CantidadExistencia__c - inv[i].Cantidad__c ;
      }
    }
  }
  //update all the products records
  update Pros;
}

Is not working, i know something are really bad like trying to do this Pros[i].CantidadExistencia__c = Pros[i].CantidadExistencia__c - inv[i].Cantidad__c ;
What can i do, Thanks in advance !
Im stucked here for 3 days now what can i do ?, i insert the parent, but i dont insert any specific ID on the parent and i have child object with a master relationship i need to insert what can i do ?
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 
This is what i write

Cart= new list<Product__c>(); //This list is filled by the client and the products he want to add

try{
        for  ( Product__c C : Cart) {
       
        Line.Quantity__c = C.CantidadExistencia__c;
        //Line.ProductName__c = C.ProductName__c;
        Line.Invoice__c = x; //This field should be filled with the autogenerated number of the invoiceID this is a master relationship from line with Invoice
        Line.Price__c = C.Price__c;

               
        Linea.Product__c = C.Code__c;
    
        insert(Line);
      
        }


How can i make that work im pretty new to SF and apex i hope someone can help me.

Thanks
This is the visualforce code :
Payment Method
    <apex:form >
    <apex:pageMessages />
        <apex:pageBlock >
       
        <p>
        <apex:inputCheckbox value="{!Efectivo}">
         <apex:actionSupport event="onchange" action="{!toogle_a}" rerender="the_outputpanel_0"/> 
        </apex:inputCheckbox> Efectivo <br/>
        <br/>
        <apex:inputText value="{!EfectivoP}" rendered="{!(!Efectivo == false)}"/>
        
        </p>
        <p>
        <apex:inputCheckbox value="{!Tarjeta}">
        <apex:actionSupport event="onchange" action="{!toogle_b}" rerender="the_outputpanel_0"/> 
        </apex:inputCheckbox> Tarjeta
        </p>
       
        <br/>
        <apex:commandButton value="Pagar" >
                       <apex:actionSupport event="onclic"  action="{!Pagar()}"/>
                        
                       </apex:commandButton>
                       <br/>  
                                         
        </apex:pageBlock>
    </apex:form>
</apex:outputPanel>


This is the method i want to call in the controller :

public void Pagar(){
   
   
    if(Efectivo=true && total_str > '0'){
      /*  
        calcular_total();
                     
        current_factura.Descuento__c == ;
        current_factura.Efectivo__c == ;
        current_factura.Estado__c == 'Pagado';
        current_factura.Fecha_y_Hora_de_Factura__c == system.now().addHours(-6);
        current_factura.Forma_de_Pago__c == ;
        current_factura.Porcentaje__c == ;
        current_factura.Subtotal__c == ;
        current_factura.Tarjeta__c == ;
        current_factura.Total__c == ;
        current_factura.Vuelto__c == ;
        
        insert(current_factura):
        */
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Gracias por pagar en Efectivo'));
    }
       
    else if (Tarjeta=true && total_str > '0')
   
    {
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Gracias por pagar con Targeta'));
    }
   
    else
   
    {
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Por favor seleccione un metodo de pago'));
   
    }

}

I also have this already declared

public boolean Efectivo {get;set;}
public boolean Tarjeta {get;set;}

public pageReference toogle_a(){

if(Efectivo==false){Tarjeta=true;}
else{Efectivo=true;Tarjeta=false;}

return null;
}
public pageReference toogle_b(){

if(Tarjeta==false){Efectivo=true;}
else{Tarjeta=true;Efectivo=false;}

return null;
}
<apex:page action="{!init}" controller="mainControllerV1" showHeader="false" standardStylesheets="true">


<apex:outputPanel id="the_outputpanel_00">
    <p>
    Consecutivo: {!current_factura.Consecutivo__c}
    </p>
    <p>
    Fecha: {!current}
    </p>
</apex:outputPanel>

<apex:outputPanel id="the_outputpanel_0">
Método de Pago
    <apex:form >
    <apex:pageMessages />
        <apex:pageBlock >
       
        <p>
        <apex:inputCheckbox value="{!current_factura.Efectivo__c}">
         <apex:actionSupport event="onchange" action="{!toogle_a}" rerender="the_outputpanel_0"/> 
        </apex:inputCheckbox> Efectivo <br/>
        <br/>
        <apex:inputText value="{!Efectivo}" rendered="{!(!current_factura.Efectivo__c == false)}"/>
        
        </p>
        <p>
        <apex:inputCheckbox value="{!current_factura.Tarjeta__c}">
        <apex:actionSupport event="onchange" action="{!toogle_b}" rerender="the_outputpanel_0"/> 
        </apex:inputCheckbox> Tarjeta
        </p>
       
        <br/>
        <apex:commandButton value="Pagar" >
                       <apex:actionSupport event="onclic"  action="{!Pagar}"/>
                        
                       </apex:commandButton>
                       <br/>  
                                         
        </apex:pageBlock>
    </apex:form>
</apex:outputPanel>

Busqueda de productos

<apex:outputPanel id="the_outputpanel">

    <apex:pageBlock >
                <apex:form >
                <div><h4>Búsqueda por código</h4>  <apex:inputText value="{!STR_SRCH}"  >
                       </apex:inputText>
                       <apex:commandButton value="BUSCAR!" >
                       <apex:actionSupport event="onclic" rerender="the_outputpanel2"/> 
                       </apex:commandButton>
                   </div>
                </apex:form>
    </apex:pageBlock>
</apex:outputPanel>

<apex:outputPanel id="the_outputpanel_dec">

    <apex:pageBlock >
                <apex:form >
                <div><h4>Descuento</h4>  <apex:inputText value="{!STR_DESC}"  > %
                       </apex:inputText>
                       <apex:commandButton value="ACTUALIZAR!" >
                       <apex:actionSupport event="onclic" rerender="the_outputpanel3"/> 
                       </apex:commandButton>
                   </div>
                </apex:form>
    </apex:pageBlock>
</apex:outputPanel>

<apex:outputPanel id="the_outputpanel2">
    <apex:pageBlock >
        <apex:pageBlockTable id="srch_id" value="{!ListaSRCH}" var="o">
                               
            <apex:column value="{!o.CantidadExistencia__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Codigo__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Descripcion__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Precio__c}"> <apex:facet name="header"></apex:facet> </apex:column>
            <apex:column headerValue="Opciones" >
                <apex:form >
                    <apex:commandLink value="AGREGAR" action="{!add2carrito}">
                            <apex:actionSupport event="onclic" rerender="the_outputpanel3"/>    
                            <apex:param name="idz"   assignTo="{!current_prod}" value="{!o.id}"  />                               
                    </apex:commandLink>
                </apex:form>   
            </apex:column>
           
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:outputPanel>


CARRITO

<apex:outputPanel id="the_outputpanel3">
    <apex:form >
        <apex:commandButton value="CLEAR" action="{!clear_carr}">
            <apex:actionSupport event="onclic" rerender="srch_id2"/> 
        </apex:commandButton>  
    </apex:form>
    <apex:pageBlock >
        <apex:pageBlockTable id="srch_id2" value="{!ListaCARR}" var="o" >
                               
            <apex:column value="{!o.CantidadExistencia__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Codigo__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Descripcion__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Precio__c}"> <apex:facet name="header"></apex:facet> </apex:column>
           
        </apex:pageBlockTable>
    </apex:pageBlock>
    <apex:pageBlock >
    <h1>
    <p>
    Subtotal: {!total_str}</p> colones
    </h1>
    <h1>
    <p>
    Descuento: {!total_dstr} colones
    </p>
    </h1>
    <h1>
    <p>
    Total: {!total_final} colones
    </p>
    </h1>
    </apex:pageBlock>
</apex:outputPanel>


</apex:page>
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Controller method ;

public void Pagar(){
   
   
    if(current_factura.Efectivo__c=true && total_str > '0'){
      /*  
        calcular_total();
                     
        current_factura.Descuento__c == ;
        current_factura.Efectivo__c == ;
        current_factura.Estado__c == 'Pagado';
        current_factura.Fecha_y_Hora_de_Factura__c == system.now().addHours(-6);
        current_factura.Forma_de_Pago__c == ;
        current_factura.Porcentaje__c == ;
        current_factura.Subtotal__c == ;
        current_factura.Tarjeta__c == ;
        current_factura.Total__c == ;
        current_factura.Vuelto__c == ;
        
        insert(current_factura):
        */
       
    }
       
    else if (current_factura.Tarjeta__c=true && total_str > '0')
   
    {
   
    }
   
    else
   
    {
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Por favor seleccione un metodo de pago'));
   
    }

}

I know i have to add the functionallity, but im unable to understand how to set all the parameters coming from the visualforce page i am really new to sales force and web programming.

Thanks
For example i got a field called origin if it is coming from facebook i want to save FB and if it come from the web save the value WEB, how can i do that im pretty new ?

Thanks
I have to synchronized the data comming from radixx Web Service with salesforce database, is that possible can someone give me an example or any ideas !

Thanks you
Foreign key external ID: 01305906 not found for field Codigo_Factura__c in entity Factura__c
Foreign key external ID: l01-818 not found for field Codigo_NAF__c in entity Account
Foreign key external ID: 01269006 not found for field Codigo_Factura__c in entity Factura__c

The records are not duplicated i already checked and the data is fine, im stuck, help me please!
Hi i have created a trigger that checks before inserting a record of type Factura__c, if the master-relationship field (Empresa_Cliente__c) exist, and if it dont the trigger create a new one with the value contained in the field Empresa_Cliente__c.
The master relationship is between Factura__c (custom object) and Account. But when i try to save a record the trigger doesnt fire and i keep receiving the salesforce validation error (Error: No matches found.) in that field. Any suggestions this is my trigger :

trigger insertAcc on Factura__c (before insert) {
System.debug(Logginglevel.ERROR , ' ::::::: Empresa Cliente :::::::::::::' + trigger.New[0].Empresa_Cliente__c) ;
if(Trigger.isBefore)
  {
     if(Trigger.isInsert)
      {
  
List<Account> a = [select name, CodigoNAF__c from account where CodigoNAF__c = :trigger.New[0].Empresa_Cliente__c];
System.debug(Logginglevel.ERROR , ' ::::::: List :::::::::::::' + a) ;
if (a == null){
Account acc = new Account();
acc.Name = trigger.New[0].Empresa_Cliente__c;
acc.CodigoNAF__c = trigger.New[0].Empresa_Cliente__c;
insert (acc);

System.debug(Logginglevel.ERROR , ' ::::::: acc :::::::::::::' + acc) ;
}

}
}
}

The trigger is not firing when i try to save a record it just keep throwing me an error in the master-relationship field (Error:Error: No matches found) . Remember the value i put in the field doesnt exist that is the point of the trigger, create a new Account with the value provided in Empresa_Cliente__c and then save the new Factura__c record without errors.

Hi i created a trigger that checks before inserting a record of type Factura__c, if the master-relationship field exist, and if it dont the trigger create a new one with the value contained in the field Empresa_Cliente__c.
The master relationship is between Factura__c (custom object) and Account. But when i try to save a record the trigger doesnt fire and i keep receiving the salesforce validation error (Error: No matches found.) in that field. Any suggestions this is my trigger :

trigger insertAcc on Factura__c (before insert) {
System.debug(Logginglevel.ERROR , ' ::::::: Empresa Cliente :::::::::::::' + trigger.New[0].Empresa_Cliente__c) ; 
List<Account> a = [select name, CodigoNAF__c from account where CodigoNAF__c = :trigger.New[0].Empresa_Cliente__c];
System.debug(Logginglevel.ERROR , ' ::::::: List :::::::::::::' + a) ; 
if (a == null){
Account acc = new Account();
acc.Name = trigger.New[0].Compania__c;
acc.CodigoNAF__c = trigger.New[0].Empresa_Cliente__r.CodigoNAF__c;
insert (acc);

System.debug(Logginglevel.ERROR , ' ::::::: acc :::::::::::::' + acc) ;
}

}
Just for information CodigoNAF__c is a custom field i created within Account object.

Hi guys ! Lately im having some seriuos troubles inserting Factura__c records because they have a master-detail relationship with accounts (called Empresa_Cliente__c) and sometimes the account doesnt exist and the insert fail. So i was building a trigger that checks if the account exist and if it dont create a new one with the field Codigo_NAF__c of Factura__c object. The problem is that trigger isnt working, it doesnt fire; do you guys now where maybe the issue ? Is that possible ?
Account has a custome field called Codigo_NAF__c just for info and the trigger is already active; but when i create a new record of type Factura__c and try to enter an Account that doesnt exist the trigger doesnt fire and i just receive the validation error that says: Please insert a valid account (something like that).

This is my trigger:
trigger insertAcc on Factura__c (before insert) {

System.debug(Logginglevel.ERROR , ' ::::::: Empresa Cliente :::::::::::::' + trigger.New[0].Empresa_Cliente__c) ; 
List<Account> a = [select name, Codigo_NAF__c from account where Codigo_NAF__c = :trigger.New[0].Empresa_Cliente__c];
System.debug(Logginglevel.ERROR , ' ::::::: List :::::::::::::' + a) ; 
if (a == null){
Account acc = new Account();
acc.Name = trigger.New[0].Empresa_Cliente__c;
acc.Codigo_NAF__c = trigger.New[0].Empresa_Cliente__c;

insert (acc);


System.debug(Logginglevel.ERROR , ' ::::::: acc :::::::::::::' + acc) ;
}

}

I hope someone can help me ! Thanks in advance !

 

Hi everyone ! This is my scenario; i have an object called Facturas__c, when i insert a record in that object it has a lookup to Account (lookup to my custom field Codigo_NAF__C); so my trigger basically search if the Account exist and if the account does not exist, it create a new one so the record can be inserted without any issues.

trigger insertAcc on Factura__c (before insert) {

System.debug(Logginglevel.ERROR , ' ::::::: Empresa Cliente :::::::::::::' + trigger.New[0].Empresa_Cliente__r.Codigo_NAF__c) ; 
List<Account> a = [select name, Codigo_NAF__c from account where Codigo_NAF__c = :trigger.New[0].Empresa_Cliente__r.Codigo_NAF__c];
System.debug(Logginglevel.ERROR , ' ::::::: List :::::::::::::' + a) ; 
if (a == null){
Account acc = new Account();
acc.Name = trigger.New[0].Empresa_Cliente__c;
acc.Codigo_NAF__c = trigger.New[0].Empresa_Cliente__c;
insert (acc);

trigger.New[0].Empresa_Cliente__c = acc.id;

System.debug(Logginglevel.ERROR , ' ::::::: acc :::::::::::::' + acc) ;
}

}

Any help what i am missing would be great ! Thanks for your time !
In my VF page i have a function that allows the user to select the lookup field that he wants and fill an input field (this action works like a charm); after that i have a command link that updates the record but im unable to get the value from the input field, the value is always null. How can i achieve this ? I have been stuck for 3 days now, i would appreciate any help. Thanks in advance.

VisualForce:
<apex:pageBlockTable id="srch_id" value="{!Piezas}" var="o">
            
            <apex:column value="{!o.Name}"> <apex:facet name="header"> </apex:facet> </apex:column>          
            <apex:column value="{!o.Producto__r.Name}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Bodega__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Estado__c}"> <apex:facet name="header"></apex:facet> </apex:column>
            <apex:column value="{!o.Reparaci_n_ETL__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column headerValue="Opciones" >
          
                   ---------------------------------------------------This is the value im trying to get--------------------------------------------------
           
                  <apex:inputField id="Reparacion" value="{!PI.Reparaci_n_ETL__c}" />

           -------------------------------------------------------------------------------------------------------------------------------------------------------------
 
                    <apex:commandLink value="Agregar a Reparacion" action="{!actualizaPieza}">
                            <apex:actionSupport event="onclic"/>    
                            <apex:param name="namePieza"   assignTo="{!piezaActual}" value="{!o.Name}"  />
                            <apex:param name="rep" assignTo="{!idRep}" value="{!PI.Reparaci_n_ETL__c}"  />
                   </apex:commandLink>
                  
            </apex:column>
           
        </apex:pageBlockTable>


Controller:

public class addPiezaController {

public String order {get; set;}
public List<Pieza__c> Piezas = new List<Pieza__c>();
public String piezaActual {get; set;}
public String idRep {get; set;}

private Pieza__c PI = new Pieza__c();

public void setPI(Pieza__c value) {
    PI = value;
}

public Pieza__c getPI() {
    return PI;
}



public PageReference lol(){
System.debug(LoggingLevel.Error, 'Reparacion ID:' + PI.Reparaci_n_ETL__c);
return null;
}



public addPiezaController (){
order = '';
Piezas = null;
piezaActual = '';
}

public List<Pieza__c> getPiezas(){

Piezas = [select Name, Producto__r.Name, Bodega__c, Estado__c, Reparaci_n_ETL__c from Pieza__c where Orden__r.Name =: order ];

return Piezas;
}

public void actualizaPieza(){

//Id repID = ApexPages.currentPage().getParameters().get('idRep');
System.debug(LoggingLevel.Error, 'Reparacion lololo param:' + idRep );
System.debug(LoggingLevel.Error, 'Reparacion ID:' + PI.Reparaci_n_ETL__c);
System.debug(LoggingLevel.Error, 'Name:' + piezaActual);


Pieza__c P = [select name, Reparaci_n_ETL__c, Estado__c  from Pieza__c where name =: piezaActual];
P.Reparaci_n_ETL__c = PI.Reparaci_n_ETL__c;
P.Estado__c = 'Utilizada en reparación';

Update(P);

getPiezas();
}

}
So i have a function that allows me to search and select the lookup value; after i select 1 and the textbox is filled i use a command link to send that value among others to the controller and update the object but no matter what i do the lookup value is alwais null. Any ideas ? I am stucked, thanks in advance for your time!

Visual Force:
<apex:pageBlockTable id="srch_id" value="{!Piezas}" var="o">
            
            <apex:column value="{!o.Name}"> <apex:facet name="header"> </apex:facet> </apex:column>          
            <apex:column value="{!o.Producto__r.Name}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Bodega__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Estado__c}"> <apex:facet name="header"></apex:facet> </apex:column>
            <apex:column value="{!o.Reparaci_n_ETL__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column headerValue="Opciones" >
          

           
                  //This is the value i am unable to get
                  <apex:inputField id="Reparacion" value="{!PI.Reparaci_n_ETL__c}"/>

           
 
                    <apex:commandLink value="Agregar a Reparacion" action="{!actualizaPieza}" immediate="false">
                            <apex:actionSupport event="onclic"/>    
                            <apex:param name="namePieza"   assignTo="{!piezaActual}" value="{!o.Name}"  />
                            <apex:param name="rep" value="Reparacion"  />
                   </apex:commandLink>
                  
            </apex:column>
           
        </apex:pageBlockTable>

Controller :

public class addPiezaController {

public String order {get; set;}
public List<Pieza__c> Piezas = new List<Pieza__c>();
public String piezaActual {get; set;}
public id idRep {get; set;}

private Pieza__c PI = new Pieza__c();

public void setPI(Pieza__c value) {
    PI = value;
}

public Pieza__c getPI() {
    return PI;
}




//This is the method i am trying to execute
public addPiezaController (){
order = '';
Piezas = null;
piezaActual = '';
}

public List<Pieza__c> getPiezas(){

Piezas = [select Name, Producto__r.Name, Bodega__c, Estado__c, Reparaci_n_ETL__c from Pieza__c where Orden__r.Name =: order ];

return Piezas;
}

public void actualizaPieza(){

//Id repID = ApexPages.currentPage().getParameters().get('idRep');

System.debug(LoggingLevel.Error, 'Reparacion ID:' + PI.Reparaci_n_ETL__c);
System.debug(LoggingLevel.Error, 'Name:' + piezaActual);


Pieza__c P = [select name, Reparaci_n_ETL__c, Estado__c  from Pieza__c where name =: piezaActual];
P.Reparaci_n_ETL__c = PI.Reparaci_n_ETL__c;
P.Estado__c = 'Utilizada en reparación';

Update(P);

getPiezas();
}

}
Can i create another map and fill with the results of those AggregateResults and the update the map posiciones with those values i need to add those two values per user to the other values im getting in posiciones MAP. Any ideas i have been stuck all day with this

public class tablaVentas {


public list <Leads__c> puntos = [select ownerid, Puntos__c, Estado__c from leads__c where ownerid IN (select id from user) order by Puntos__c DESC];
public list <User> users= [select name from user];

//I need to get this values per user and insert them into posiociones Map
public AggregateResult[] ventasSemanales = [Select COUNT(Estado__c)Ventas from  Leads__c where Estado__c = 'Vendido' and Fecha_Venta__c = THIS_WEEK group by owner.name ];
public AggregateResult[]  = [Select COUNT(Estado__c)Ventas from  Leads__c where Estado__c = 'Vendido' and Fecha_Venta__c = THIS_MONTH group by owner.name ];

public List<Posicion> getPositions(){
          
             Map<Id,User> user_map = new Map<Id,User>();
                      
             for( User u : users){
             user_map.put(u.id,u);
                         }
          
            Map<Id, Posicion> posiciones = new  Map<Id, Posicion>();
         
            for(leads__c c : puntos){
              
                Posicion temp = posiciones.get(c.ownerId);
                if(posiciones.get(c.ownerId)==null){ temp = new Posicion() ;}
              
                Integer puntos = integer.valueof(c.puntos__c);
                temp.nombre = user_map.get(c.ownerid).name;
                temp.puntostotal += puntos;
                /*
                if (c.Estado__c == 'vendido'){
              
// i need to insert those values here im pretty new to apex what can i do ??
              
                if (ventasSemanales == null)
                temp.VentasSemanales = (integer)ventasSemanales[0].get('Ventas');
              
                else {
                temp.VentasSemanales = 0;            
                }
              
                if (ventasMensuales == null){
                temp.VentasMensuales = 0;
                }
                else{
                temp.VentasMensuales = (integer)ventasMensuales[0].get('Ventas');
                }
              
                }
                */
                posiciones.put(c.ownerid,temp);
              
            }
          
            return posiciones.values();
       }
This is my scenario, i have the following VF page, i need to get the value of Cantidad in my controller so i can update the quantity selected by the user:
<apex:page action="{!init}" controller="mainControllerV2" showHeader="false" standardStylesheets="true">

<apex:outputPanel id="the_outputpanel2">
    <apex:pageBlock >
    <p>Paso #4 - Agregue los productos a la factura.</p>
         
      <apex:form >
                        
        <apex:pageBlockTable id="srch_id" value="{!ListaSRCH}" var="o">
                      
                           
            <apex:column value="{!o.CantidadExistencia__c}"> <apex:facet name="header"> </apex:facet>
            <apex:inputField value="{!o.CantidadExistencia__c}"/>
             </apex:column>
            <apex:column value="{!o.Codigo__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Descripcion__c}"> <apex:facet name="header"> </apex:facet> </apex:column>
            <apex:column value="{!o.Precio__c}"> <apex:facet name="header"></apex:facet> </apex:column>
            <apex:column headerValue="Opciones" >
               
                    <apex:commandLink value="AGREGAR" action="{!add2carrito}">
                            <apex:actionSupport event="onclic" rerender="the_outputpanel3"/>    
                            <apex:param name="idz"   assignTo="{!current_prod}" value="{!o.id}"  />                               
                    </apex:commandLink>
                  
            </apex:column>
           
        </apex:pageBlockTable>
       
      </apex:form>
       
    </apex:pageBlock>
</apex:outputPanel>
</apex:page>

Im not sure whats the value of value="{!o.CantidadExistencia__c}" im pretty new to apex i dont know what variable it references to.

This is my controllers methods:

public List<Producto__c> getListaSRCH(){
Operaciones O = new Operaciones();
//ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error al buscar'));
return O.busqueda(STR_SRCH);
}

public PageReference add2carrito(){
//se tiene el id
//Producto__c P = new Producto__c();

try{
  if(CARRITO!=null){
  Producto__c P =[select id, Name, Precio__c, Codigo__c, Tipo__c,CantidadExistencia__c, Descripcion__c from Producto__c where id=:current_prod limit 1];
 
   if (P.CantidadExistencia__c != 0) {
                       
   
  if(is_present(P)==-1){
 
    P.CantidadExistencia__c = 1;
    CARRITO.ADD(P);
    }
  else{
      if(P.CantidadExistencia__c==CARRITO[is_present(P)].CantidadExistencia__c){
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'El item :'+ P.Descripcion__c + ' se encuentra agotado en el inventario.'));
      }
     
           
      else{
        CARRITO[is_present(P)].CantidadExistencia__c++;
      }
    }
    calcular_total();
   
    }
   
    else{
     
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'El item :'+ P.Descripcion__c +' no tiene existencias en el inventario. Asegurese de ingresar existencia antes de facturar.'));
      }
   
  }
 
}
catch(exception j){ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error al agregar elemento al carrito'+j));}
return null;
}

public Integer is_present(Producto__c P){
  Integer counter = 0;
  Integer answ = 0;
  boolean present = false;
  for( Producto__c C : CARRITO){
    if(C.Codigo__c == P.Codigo__c){answ = counter;present=true;}
    else{counter ++;}
  }
  if(present==false){answ=-1;}
  return answ;
}

public void insertarLinea()
    {
       
        try
        {
        List<Linea__c> lines = new list<Linea__c>(); // crea una lista con las lineas de la factura
            //Para cada producto C en carrito
            for(Producto__c C : CARRITO) {

              
                   Linea__c Line = new Linea__c ();
                   Line.Cantidad__c = C.CantidadExistencia__c;
                   Line.Factura__c = current_factura.id;                 
                   Line.Monto_Colones__c = C.Precio__c;
                   Line.Monto_Dolares__c = 0;
               
                   Line.Producto__c = C.id;
 
                   lines.add(Line); // adding line to list
                                         
                 Producto__c P =[select id, CantidadExistencia__c from Producto__c where id=:C.id limit 1];
                 P.CantidadExistencia__c = P.CantidadExistencia__c - Line.Cantidad__c;         
                
                 update (P);                        
                                         

                                     }

            insert (lines); // Insertamos la lista lineas asi evitamos hacer un insert por cada registro que haya en CARRITO
       
       
       
        }
       
        catch(Exception a)
       
        {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error al insertar la linea. '+a));
        }
       

    }

How can i proceed any ideas, suggestions, i have tried sending the value through apex:param but i dont really knew how to proceed i have been stucked with this for 3 days know.

Thank you 
Controller

public class convertirFactura {


      public Cotizacion__c cotizacion { get; set; }
      public List<Lineas__c> lineaC { get; set; }
      public Factura__c factura { get; set; }
      public LineaF__c lineaF { get; set; }
      public Cliente__c cliente { get; set; }
      public Date Today { get { return Date.today(); }}

      
    public PageReference init() {
   
        Id cotizacionId;
       
        //REMOVE AFTER DEV
       
        if(System.currentPagereference().getParameters().get('cotizacionId')==null){
  
             cotizacionId = [select id from Cotizacion__c limit 1].id;  
        }
        else{
            //param from URL
            cotizacionId = System.currentPagereference().getParameters().get('cotizacionId');
        }
       
        cotizacion = new Cotizacion__c();
        //se cargan los fields que se van ha usar del candidato
        cotizacion = [select id, name, Comentarios__c,Email__c,Estado__c, NombreLead__c, Apellidos__c, PorcentajeImpuestos__c from Cotizacion__c where Id= :cotizacionId];
        lineaC = new List<Lineas__c>();
        for (Lineas__c  L : [select CantidadCajas__c, CantidadUnidades__c, Cotizacion__c, Producto__c, Total_Costos_Linea__c, TtotalVentaLinea__c from Lineas__c where Cotizacion__r.id =:cotizacionId]) {
           
         if (L != null){
          lineaC.add(L);
                       }
                           }
        //initialize the variables
       
        factura = new Factura__c();
        cliente = new Cliente__c();
                            
        factura.Comentarios__c = cotizacion.Comentarios__c;
        factura.Estado__c = cotizacion.Estado__c;
        factura.PorcentajeDescuento__c = cotizacion.PorcentajeImpuestos__c ;
        factura.Fecha_de_Entrega__c = Today;
       
        cliente.Name = cotizacion.NombreLead__c;
        cliente.Apellidos__c = cotizacion.Apellidos__c;
      
  
       
       
       
        back();
       
        return null;
    }

    //insert the new objects and create the lines assingned to the invoice
    public PageReference save() {
      
      
        insert cliente;
      
        factura.Cliente__c = cliente.id;
      
        insert factura;
       
        List <LineaF__c> linFactura = new List <LineaF__c>();
       
        for (lineas__c L : lineaC){
       
        if (L != null){
       
           for(Integer i =0; i < lineaC.size();i++){
       
        lineaF = new LineaF__c();
        lineaF.CantidadCajas__c = L.CantidadCajas__c;
        lineaF.CantidadUnidades__c = L.CantidadUnidades__c;
        lineaF.Factura__c = factura.id;
        lineaF.Producto__c = L.Producto__c;
        lineaF.Total_Costos_Linea__c = L.Total_Costos_Linea__c;
        lineaF.Total_Venta_Lineas__c = L.TtotalVentaLinea__c ;
      
        linFactura.add(lineaF);
       
        Producto__c P = new Producto__c();
        P =[select id, InventarioCajas__c, InventarioUnidades__c from Producto__c where id=:L.Producto__c limit 1];
        P.InventarioCajas__c = P.InventarioCajas__c - L.CantidadCajas__c;
        P.InventarioUnidades__c = P.InventarioUnidades__c - L.CantidadUnidades__c;
       
        Update (P);
        }
      
        }
     }
       
        insert(lineaF);
       

        Pagereference p = new Pagereference('/' + factura.id);
        return p;
    }
    
        public PageReference back() {
            Pagereference p = new Pagereference('/' + cotizacion.id);
            return p;
    }
}
Is that possible, what i should do to achieve that i need to print an invoice after every purchase everyting is ready how can i add this functionally ?
How can i achieve that this are the fields in object Line
Cantidad__c   Number(4, 0)  
Factura__c     Master-Detail(Factura)
Producto__c    Lookup(Producto)
Monto_Colones__c        Currency(16, 2)

I need to Update this fiel from Product__c
CantidadExistencia__c  Number(4, 0)

Basically i want to set CantidadExistencia__c = CantidadExistencia__c - Line.Cantidad__c for each line i insert; this is the code that insert every line:
public void insertarLinea()
    {
       
        try
        {
        List<Linea__c> lines = new list<Linea__c>(); // crea una lista con las lineas de la factura
            //Para cada producto C en carrito
            for(Producto__c C : CARRITO) {

              for(Integer i =0; i < CARRITO.size();i++){ // Creamos un loop para que recorra toda la lista CARRITO y los integre a una nueva lista de lineas
                 
                   Linea__c Line = new Linea__c ();
                   Line.Cantidad__c = C.CantidadExistencia__c;
                   Line.Factura__c = current_factura.id;                 
                   Line.Monto_Colones__c = C.Precio__c;

               
                   Line.Producto__c = C.id;
 
                   lines.add(Line); // adding line to list
                                          }

                                     }

            insert (lines); // Insertamos la lista lineas asi evitamos hacer un insert por cada registro que haya en CARRITO
        }
       
        catch(Exception a)
       
        {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error al insertar la linea. '+a));
        }
       
       
    }
How can i achieve that im pretty new to apex basiclly i want to execute the following sql code everytime a line is inserted:
update Producto__c set CantidadExistencia__c = Producto__c.CantidadExistencia__c - Linea__c.Cantidad__c where Linea__c.Producto__c = Producto__c.id
I tried to write and my trigger looks like this:

trigger ActualizaExistencia on Linea__c(before insert, before update){
  //get a list of all the products ID's contained in the records
  //to be updated.
    Set<Id> ids = trigger.newmap.keySet();
    List<Linea__c> inv=[select id,Cantidad__c from  Linea__c where id IN :ids];


  List<Producto__c> ProIDs = new List<Producto__c>();
  for (Linea__c Ite:trigger.new){
   ProIDs.add(Ite.Producto__c);
  }
  //now get a list of all the records for products that contain the
  //above IDs
  List<Producto__c > Pros = new List<Producto__c >([select id, CantidadExistencia__c from Producto__c
  where id in:ProIDs]);
  //now loop again for all the records being updated and then for each
  //one loop through all the products records retrieved above.
  for (Linea__c obj: trigger.new){
    //we do this for loop differently so that it has an inherent check
    //to ensure that our query above returned some records
    for (integer i = 0; i < Pros.size(); i++){
      //now we make sure the record IDs match
      if (Pros.Producto__c == pros[i].id){
        Pros[i].CantidadExistencia__c = Pros[i].CantidadExistencia__c - inv[i].Cantidad__c ;
      }
    }
  }
  //update all the products records
  update Pros;
}

Is not working, i know something are really bad like trying to do this Pros[i].CantidadExistencia__c = Pros[i].CantidadExistencia__c - inv[i].Cantidad__c ;
What can i do, Thanks in advance !