• azu.shaik1.3965080575576013E12
  • NEWBIE
  • 0 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 14
    Questions
  • 5
    Replies
i am able to write test the class for the HttpPost and HttpPAtch but i was stuck to write the test method for the delete method . Please help me how write test class for the below delet method.

@HttpDelete
global static string deleteAccountById() {

    RestRequest req = RestContext.request;
    RestResponse res = RestContext.response;
    // phpId related to Product object
    string phpId = RestContext.request.params.get('phpId');
    // phpId related to Attributes
    List<Account> acc =[ select id from Account where Php_id__c =: phpId];       

   if(acc.size() > 0){

    delete acc;

    return ' sucessfully delete the account';

    }
    else{
           return 'The requested resource not found in system to delete ' + '=' +phpId ;
    }

}

And my test method

@IsTest


Private class AccountCreationTest{


static testMethod void deleteAccountById(){

    Schema.DescribeSObjectResult cfrSchema = Schema.SObjectType.Account;
    Map<String,Schema.RecordTypeInfo> AccountRecordTypeInfo = cfrSchema.getRecordTypeInfosByName();
    string rtId = AccountRecordTypeInfo.get('Affiliate').getRecordTypeId();
      List<Account> acc1= new List<Account>();
        Account acc= new Account(recordtypeid = rtId );
        acc.Name = 'TestName1';
        acc.First_Name__c = 'Test firstname';
        acc.Last_Name__c = 'Test lastname';
        acc.Email__c = 'Testmail@gmail.com';
        acc.Php_id__c ='1234';
        acc.BillingPostalCode= '600119';
        acc.BillingStreet= 'test street';
        acc.BillingCity= 'Nellore';
        acc.BillingState= 'Andhra Pradesh';
        acc.BillingCountry= 'India';
       acc1.add(acc);
        insert acc1;
        if(acc1.size()>0){
            delete acc1;
           
        }
   
    String JSONMsg = JSON.serialize(acc);
   
    RestRequest req = new RestRequest();
   
    req.requestURI = 'https://sandbox-togethersave.cs5.force.com/services/apexrest/restAccount?phpId=123';
    req.httpMethod = 'Delete';
   
    req.requestBody = Blob.valueof(JSONMsg); // Add JSON Message as a POST
   
    RestResponse res = new RestResponse();
    RestContext.request = req;
    RestContext.response = res;
    AccountCreation.deleteAccountById();
                    
}
}
@HttpDelete
    global static void doDelete() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account account = [SELECT Id FROM Account WHERE Id = :accountId];
        delete account;
    }
Iam able to insert the data into object. But iam unable to update the same record using the external id . when i use upsert dml without external id (phpId) i can able to insert the data into custom object . when i use upsert with external id i am not able to insert the data into object . please help where i did worng

Product__c product= createProduct(params);
              
                if(product!=null){
                 body = upsertSObject(product);
                              
                if (body.id != null) {  
                   String name1 =null;
                   String value1 =null;  
                   String phpId=null;               
                   JSONParser parser = JSON.createParser(params.get('attributeValues',false));       
                  
                    while (parser.nextToken() != null) {
                          if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'name1')) {
                                 parser.nextToken();
                                 name1= parser.getText();
                                }
                          if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'value1')) {
                                parser.nextToken();
                                value1 = parser.getText();
                              }
                              if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'phpId')) {
                                parser.nextToken();
                                phpId= parser.getText();
                              }
                          if(name1 !=null && value1 !=null&&phpId !=null) {
                                Attribute__c atrb= createAttributeItem(name1,value1,phpId, body.id);
                                upsertSObject (atrb) ;
                                value1 = null;
                                phpId=null;
                               }
................


public static Attribute__c createAttributeItem(String name1,String value1,string phpId, Id id) {
   
        Attribute__c atb= new Attribute__c ();
        atb.Product_Name__c= id ;
        atb.Attribute_Value__c= value1;
        atb.Php_Id__c = phpId;
        atb.name = name1;
            
        return atb;
    }

..............

private static ResponseBody upsertSObject(SObject sObj) {
        System.debug(JSON.serializePretty(sObj));
        ResponseBody body = new ResponseBody();
        try {
            if (sObj instanceof Product__c)
          
              upsert (Product__c) sObj Php_External_Id__c ;
             else if(sObj instanceof Attribute__c )
           upsert (Attribute__c) sObj ;//here iam inserting attributes but if upsert (Attribute__c) sObj Php_Id__c iam not able to insert the data into object please       help    me  how to insert and update using external id here.
            body.id = sObj.id;
          }
        catch (Exception e) {
            body.addError(e);
          }
        return body;
    }


Hi frnds,

i have a class where json parameters come in string format  among them two values come in decimal format i was not able to parse those values with my object values please help me in modfying the code and how to implement .

please find the below code and let me know waht need to be done

try {
            RestRequest req = RestContext.request;
            res = RestContext.response;
            res.statusCode = HTTP_OK;
            res.addHeader('Content-Type', CONTENT_TYPE);
            System.debug(JSON.serializePretty(req.params));

                 
                Params params = new Params(req.params);
                system.debug(' enter params'+params);
               
                Order__c order= createOrder(params);
              
                if(order!=null){
                 body = upsertSObject(order);
                              
               
                          }
                     }
                    catch (MyException e) {
                        if (body == null)
                             body = new ResponseBody();
                             body.addError(e);
                     }
                    catch (Exception e) {
                         if (res == null) throw e; // something horrible has happened!
                                res.statusCode = HTTP_ERROR;
                         if (body == null)
                                body = new ResponseBody();
                                body.addError(e);
                      }
                        if (body.id != null)
                            res.statusCode = HTTP_CREATED;
                                System.debug(JSON.serialize(body));
                            res.responseBody = Blob.valueOf(JSON.serialize(body));
                         }

     public static Order__c createOrder(Params p) {
       
        Order__c ord= new Order__c();
      //ord.Total_Price__c = getPrice(p.get('totalPrice',false));// not able to convert sting
        ord.Total_Quantity__c= Decimal.valueOf((p.get('totalQuatity',false))); // not able to convert the string into decimal
        ord.Buyer_Account__c = getBuyer(p.get('buyerName',false));
        ord.Order_Status__c  =p.get('status',false);
        ord.Payment_Type__c = p.get('payment',false);
        ord.Php_Id__c= p.get('phpId',false);
        ord.Seller_Account__c = getSeller(p.get('sellerName',false));
        ord.Product_Name__c = getProduct(p.get('productName',false));
         //  ord.Product_Name__c = p.get()
      
        return ord;
     }
   
     Public static id getBuyer(String buyerName){
   
        Account accounts = [Select Id, Name,RecordTypeid from Account where Name =:buyerName];
       
        return accounts.id ;
     }
   
    Public static Id getSeller(String sellerName){
   
        Account accounts = [Select Id, Name, RecordTypeid from Account where Name = :sellerName];
       
        return accounts.id ;
     }
  
    Public static id getProduct(String productName){
   
        Product__c product = [Select Id, Name from Product__c where Name = :productName Limit 1];
       
        return product.id ;
     }
 
    
     
    
    private static ResponseBody upsertSObject(SObject sObj) {
        System.debug(JSON.serializePretty(sObj));
        ResponseBody body = new ResponseBody();
        try {
            if (sObj instanceof Order__c )
                upsert (Order__c ) sObj ;
             
            body.id = sObj.id;
          }
        catch (Exception e) {
            body.addError(e);
          }
        return body;
    }

   
    private class Params {
        Map<String, String> params {get; private set;}
      
        String type {get; private set;}
       
       
        Params(Map<String, String> params) {
            this.params = params;
          //  totalPrice = params.get('totalPrice');
           // type = params.get('type');
           // System.assert(typeToRT.keySet().contains(type));
        }
       
        String get(String key) {
            return get(key, true);
        }
       
        String get(String key, Boolean prependType) {
            String value = params.get((prependType ? type + '_' : '') + key);
            return value == null ? '' : value;
        }
    }

    public class ResponseBody {
        public Id id {get; set;}
        public List<ResponseError> errors {get; set;}
        public String status {get; set;}

        public ResponseBody() {
            errors = new List<ResponseError>();
            status = STATUS_OK;
        }

        public void addError(DmlException e) {
            for (Integer i = 0; i < e.getNumDml(); i++)
                errors.add(new ResponseError(e, i));
        }

        public void addError(Exception e) {
            status = STATUS_FAIL;
            if (e instanceof DmlException)
                addError((DmlException) e);
            else
                errors.add(new ResponseError(e));
        }
    }


thanks,
Hareesh.
Hi floks,

I need to insert Account with mutiple contact records at a time using apex rest api . i will be getting the response in json please help me . i had read many article in google .but i was not able to figure it . please help me to over come this stiuation .

Thanks,
AZU
i need sample code for the following json structure to create master record along child record in apexrest api in salesforce

i have master detail relation ship between product and attributes objects

{
  "mastername": "name",
   "masterdescription" : " decription",
    "attributes":[{
                                 "attributename": "name",
                                  "attributevalue": "value"
                             },
                           {
                                 "attributename": "name",
                                  "attributevalue": "value"
                             },
                              {
                                 "attributename": "name",
                                  "attributevalue": "value"
                             },
             ..........................
           }]

}



Please help me i need create maste record along with multiple child records
I was new i writting the rest api . i have gone through google and find some useful links in writing the rest api , but i was stuck to create the new record based on the record type in account .(eg : i have two recordtypes buyer and seller . i need create record in account object under buyer record ).

can some can help. It will be more great help to me
Hi ,

i had create the below rest api class. when try to access the class getting the url getting  invalid_session id ?

@RestResource(urlMapping='/FieldCase/*')
global with sharing class RESTCaseController {

@HttpPost  
  global static String createNewCase(String companyName, String caseType) {
     System.debug('COMPANY: '+companyName);
     System.debug('CASE TYPE: '+caseType);
     return null ;
    }
}
Hi ,
i have a requirement to get data from php to salesforce. to do this we plan to do it using apex rest api .i have written apex for rest service after writing the class we need to do any configurations.
can some one can explain me how to setup rest web services in salesforce
Acttually i have 4 type of users seller,buyer,product creator, broker in php. i need to setup this users in salesforce using standrd objects and custom objects in salesforce. and i would like to integrate the php to salesforce ,

Conditions to users:

1) There is direct relation between seller and buyer.

<apex:page controller="newemployee" >
<apex:includeScript value="//code.jquery.com/jquery-1.10.1.min.js"/>
<apex:includeScript value="//code.jquery.com/ui/1.10.3/jquery-ui.js"/>
<script>
alert("@@@@@S");
$(document).ready(function(){
  $("#iframes").click(function(){
    $("iframe").hide();
  });

});
</script>
<apex:form >
  <apex:pageBlock id="theBlock">
  <apex:commandButton value="Add"  id="iframes" />
   <apex:iframe frameborder="true" height="200" width="1200" id="iframe" rendered="iframes"/>
     <apex:pageBlockTable value="{!employeeDetails}" var="empDetails">
     <apex:column headerValue="Emp Acccount" value="{!empDetails.EmployeeAccount__c}"/>
     <apex:column headerValue="Name" value="{!empDetails.Employe_name__c}"/>
   </apex:pageBlockTable>
  </apex:pageBlock>
</apex:form>
</apex:page>
Hi Guys iam new to salesforce can some help me how to create the test class for the wapper calss

public with sharing class PlaceNeworders {

   


public String distributorId { get; set; }
public Order__c theOrder {get; set;}
public Order_Item__c theOrderItem {get; set;}
public List<wrapNewOrder> inventoryList { get; set; }
Public List<Inventory_Item__c> invItems {get;set;}
public Date dateName { get; set; }
public String selectedRestaurantId { get; set; }
public Boolean confirmNewOrderFlag {get; set;}


    public List<selectoption> getRestaurants1() {
        List<selectoption> Options = new List<selectoption>();
        Id accountRecordType = [SELECT Id FROM RecordType WHERE Name = 'Restaurant / Buyer'].Id;
        List <Account> accounts = [Select Name, Id from Account where RecordTypeId = :accountRecordType ];
        for (Account a : accounts)
         options.add(new SelectOption(a.Id, a.Name));
         return Options;
    }
   
   /*  public List<selectoption> getDistributor() {
        List<selectoption> Dist = new List<selectoption>();
        Id accountRecordType = [SELECT Id FROM RecordType WHERE Name = 'Distributor'].Id;
        List <Account> accounts = [Select Name, Id from Account where RecordTypeId = :accountRecordType ];
        Dist.add( new SelectOption('','Select'));
        for (Account a : accounts)
         Dist.add(new SelectOption(a.Id, a.Name));
         return Dist;
    
    }*/


   
     // Inserting the OrderItem into ordefullfilment Page and Navigating to OrderFullfilement page.
    public List<SelectOption> getUnitOrders() {
        List<SelectOption> options = new List<SelectOption>();
              
       Schema.DescribeFieldResult fieldResult =  Order_Item__c.Desired_Units__c.getDescribe();
       List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
       
        for( Schema.PicklistEntry f : ple)
        {
          options.add(new SelectOption(f.getLabel(), f.getValue()));
        }      
      
        
        return options;
    }    
   
    public void selectedDistributor() {
        User lgdUsr=[select id,name ,Distributor__c,profileId from User where id=:UserInfo.getUserId()];
      string profileName=[Select Id,Name from Profile where Id=: lgdUsr.profileId].Name;
      inventoryList = new List<wrapNewOrder> ();
   //  set<string>
      if(profileName == 'System Administrator'  ){
            system.debug('@@distributorId'+distributorId);
           
            invItems = [SELECT Id,Cut_and_Size__c,Fresh_Frozen__c,Quantity_Available__c,Species__c,Distributor_Name__c,Price_per_Unit__c,Units__c FROM Inventory_Item__c where Quantity_Available__c > 0 ];
            System.debug('Entered into as system Adminisator'+ invItems + 'assdddddd'+distributorId+'@@Distributor_Name__c'+invItems );
          
          }
      else{
             invItems = [SELECT Id,Cut_and_Size__c,Fresh_Frozen__c,Quantity_Available__c,Species__c,Price_per_Unit__c,Units__c FROM Inventory_Item__c where Distributor_Name__c =: lgdUsr.Distributor__c AND Quantity_Available__c > 0];
          }
    }
   
    // Constructor load the inventory Items to page based on the user profile
   
    Public PlaceNeworders(){
   
    theOrder =new Order__c();
    inventoryList = new List<wrapNewOrder> ();
   
      selectedDistributor();
     
      for(Inventory_Item__c a: invItems) {
                // As each Order is processed we create a new wrapAddOrder object and add it to the inventoryList
                inventoryList.add(new wrapNewOrder(a));
            }
            System.debug(' Print enter'+inventoryList);
   
   
    }





// Insert the order and order items

public PageReference confirmNewOrder() {

  
       if(theOrder.id==null) {
            theOrder.Buyer__c = selectedRestaurantId;
            theOrder.Requested_Delivery_Date__c = datename ;
            insert theOrder;
           
            system.debug('TheOrder inserted'+theOrder);
        }
                         
                         
         List<Order_Item__c> items = new List<Order_Item__c>();
         for(wrapNewOrder wno : inventoryList) {
         
         
                  
            if(wno.selected == true) {
               system.debug('Enter into selected '+wno.selected);
               confirmNewOrderFlag = true ;
               Order_Item__c oItem = new Order_Item__c();
               oItem.Amount_Ordered__c = wno.amount;
               oItem.Comments__c = wno.splInstructions;
               oItem.Desired_Units__c = wno.selectDesiredUnit;
               system.debug('@@oItem.Desired_Units__c'+oItem.Desired_Units__c);
               oItem.Order__c = theOrder.Id;
               oItem.Inventory__c = wno.invItem.Id;
                items.add(oItem);
             
              System.debug('Print Amount'+wno.amount);
              System.debug('Print SpL'+wno.splInstructions);
              System.debug('Print id'+theOrder.Id);
            }
             
        }
         system.debug('Enter confirmNewOrderFlag '+confirmNewOrderFlag);
        if(confirmNewOrderFlag == null){
       
              system.debug('Enter into Not selected loop '+confirmNewOrderFlag) ;
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please select atleast one item');
                ApexPages.addMessage(msg);
            }
       
        if(items.size()>0){
              
              system.debug('Enter into Not  loop ') ;
              if(theOrder.Requested_Delivery_Date__c == null){
              ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,'Enter Requested Delivery Date');
                ApexPages.addMessage(msg);
                }
                else{
              insert items;
              System.debug(' -------item----------- '+ items);
              PageReference orderPage = new PageReference('/apex/'+'/OrderFulfillment2?sfdc.tabName=01rF0000000VOWh');
              orderPage.setRedirect(false);
              return orderPage;
       }
       
    }
       return null;
    }

  public PageReference Cancel() {
     
     PageReference orderItemPage = new PageReference('/apex/'+'/OrderFulfillment2?sfdc.tabName=01rF0000000VOWh');
        orderItemPage.setRedirect(true);
        return orderItemPage;
    }

       // This is our wrapper/container class.
      
         public class wrapNewOrder {
         public Inventory_Item__c invItem {get; set;}
         public Boolean selected {get; set;}
         public String splInstructions { get; set; }
         public Decimal amount { get; set; }
         Public String selectDesiredUnit{get; set;}
       
       

        public wrapNewOrder(Inventory_Item__c a) {
            this.invItem = a;
            this.selectDesiredUnit=a.Units__c;
            this.selected = false;
        }
    }

}
when the page loads the piclist value should be same formula field .

i have to display the data from two different objects i consist of formula fiels and the picklist value  here i need keep the picklist value basedon the formula i differes for every record here mycode  can someone can help will be appericate more 
/

   public List<SelectOption> getUnitOrders() {
        List<SelectOption> options = new List<SelectOption>();
              
       Schema.DescribeFieldResult fieldResult =  Catalog__c.Units__c.getDescribe();
       List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
       
        for( Schema.PicklistEntry f : ple)
        {
          options.add(new SelectOption(f.getLabel(), f.getValue()));
        }      
      
        
        return options;
    }    
   
    // Constructor load the inventory Items to page based on the user profile
   
    Public PlaceNeworders(){
   
    theOrder =new Order__c();
    inventoryList = new List<wrapNewOrder> ();
   
      User lgdUsr=[select id,name ,Distributor__c,profileId from User where id=:UserInfo.getUserId()];
      string profileName=[Select Id,Name from Profile where Id=: lgdUsr.profileId].Name;
      inventoryList = new List<wrapNewOrder> ();
    
      if(profileName == 'System Administrator'){
    
             invItems = [SELECT Id,Cut_and_Size__c,Fresh_Frozen__c,Quantity_Available__c,Species__c,Price_per_Unit__c,Units__c FROM Inventory_Item__c where Quantity_Available__c > 0];
          }
      else{
             invItems = [SELECT Id,Cut_and_Size__c,Fresh_Frozen__c,Quantity_Available__c,Species__c,Price_per_Unit__c,Units__c FROM Inventory_Item__c where Distributor_Name__c =: lgdUsr.Distributor__c AND Quantity_Available__c > 0];
          }
     
      for(Inventory_Item__c a: invItems) {
                // As each Order is processed we create a new wrapAddOrder object and add it to the inventoryList
                inventoryList.add(new wrapNewOrder(a));
            }
            System.debug(' Print enter'+inventoryList);
   
   
    }


// Insert the order and order items

public PageReference confirmNewOrder() {


        if(theOrder.id==null){
            theOrder.Buyer__c = selectedRestaurantId;
            theOrder.Requested_Delivery_Date__c = datename ;
            insert theOrder;
           
            system.debug('TheOrder inserted'+theOrder);
        }
                         
         List<Order_Item__c> items = new List<Order_Item__c>();
         for(wrapNewOrder wno : inventoryList) {
         
          if(wno.selected==false){
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please select atleast one item');
                ApexPages.addMessage(msg);
            }
                   
            if(wno.selected == true) {
        
               Order_Item__c oItem = new Order_Item__c();
               oItem.Amount_Ordered__c = wno.amount;
               oItem.Comments__c = wno.splInstructions;
               oItem.Desired_Units__c = wno.selectDesiredUnit;
               system.debug('@@oItem.Desired_Units__c'+oItem.Desired_Units__c);
               oItem.Order__c = theOrder.Id;
               oItem.Inventory__c = wno.invItem.Id;
                items.add(oItem);
             
              System.debug('Print Amount'+wno.amount);
              System.debug('Print SpL'+wno.splInstructions);
              System.debug('Print id'+theOrder.Id);
            }
             
        }
       
        if(items.size()>0){
              insert items;
              System.debug(' -------item----------- '+ items);
              PageReference orderPage = new PageReference('/apex/'+'/OrderFulfillment2?sfdc.tabName=01rF0000000VOWh');
              orderPage.setRedirect(false);
              return orderPage;
      
       
    }
       return null;
    }

  public PageReference Cancel() {
     
     PageReference orderItemPage = new PageReference('/apex/'+'/OrderFulfillment2?sfdc.tabName=01rF0000000VOWh');
        orderItemPage.setRedirect(true);
        return orderItemPage;
    }

       // This is our wrapper/container class.
      
         public class wrapNewOrder {
         public Inventory_Item__c invItem {get; set;}
         public Boolean selected {get; set;}
         public String splInstructions { get; set; }
         public Decimal amount { get; set; }
         Public String selectDesiredUnit{get; set;}
       
       

        public wrapNewOrder(Inventory_Item__c a) {
            this.invItem = a;
            this.selected = false;
        }
    }

}

I Was not able to save code please some one could help me in resolving the issue



public class PageBlockTableSortingCon {

   private List<Account> accounts;
   private String sortDirection = 'ASC';
   private String sortExp = 'name';

   public String sortExpression
   {
     get
     {
        return sortExp;
     }
     set
     {
       //if the column is clicked on then switch between Ascending and Descending modes
       if (value == sortExp)
         sortDirection = (sortDirection == 'ASC')? 'DESC' : 'ASC';
       else
         sortDirection = 'ASC';
       sortExp = value;
     }
   }

public String getSortDirection()
{
    //if not column is selected
    if (sortExpression == null || sortExpression == '')
      return 'ASC';
    else
     return sortDirection;
}

public void setSortDirection(String value)

   sortDirection = value;
}
 
   public List<Account> getAccounts() {
       return accounts;
   }


   public PageReference ViewData() {
       //build the full sort expression
       string sortFullExp = sortExpression  + ' ' + sortDirection;
     
       //query the database based on the sort expression
       accounts = Database.query('Select id, Name, BillingCity, BillingCountry, Phone from Account order by ' + sortFullExp + ' limit 1000');
       return null;
   }
}
when the page loads the piclist value should be same formula field .

i have to display the data from two different objects i consist of formula fiels and the picklist value  here i need keep the picklist value basedon the formula i differes for every record here mycode  can someone can help will be appericate more 
/

   public List<SelectOption> getUnitOrders() {
        List<SelectOption> options = new List<SelectOption>();
              
       Schema.DescribeFieldResult fieldResult =  Catalog__c.Units__c.getDescribe();
       List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
       
        for( Schema.PicklistEntry f : ple)
        {
          options.add(new SelectOption(f.getLabel(), f.getValue()));
        }      
      
        
        return options;
    }    
   
    // Constructor load the inventory Items to page based on the user profile
   
    Public PlaceNeworders(){
   
    theOrder =new Order__c();
    inventoryList = new List<wrapNewOrder> ();
   
      User lgdUsr=[select id,name ,Distributor__c,profileId from User where id=:UserInfo.getUserId()];
      string profileName=[Select Id,Name from Profile where Id=: lgdUsr.profileId].Name;
      inventoryList = new List<wrapNewOrder> ();
    
      if(profileName == 'System Administrator'){
    
             invItems = [SELECT Id,Cut_and_Size__c,Fresh_Frozen__c,Quantity_Available__c,Species__c,Price_per_Unit__c,Units__c FROM Inventory_Item__c where Quantity_Available__c > 0];
          }
      else{
             invItems = [SELECT Id,Cut_and_Size__c,Fresh_Frozen__c,Quantity_Available__c,Species__c,Price_per_Unit__c,Units__c FROM Inventory_Item__c where Distributor_Name__c =: lgdUsr.Distributor__c AND Quantity_Available__c > 0];
          }
     
      for(Inventory_Item__c a: invItems) {
                // As each Order is processed we create a new wrapAddOrder object and add it to the inventoryList
                inventoryList.add(new wrapNewOrder(a));
            }
            System.debug(' Print enter'+inventoryList);
   
   
    }


// Insert the order and order items

public PageReference confirmNewOrder() {


        if(theOrder.id==null){
            theOrder.Buyer__c = selectedRestaurantId;
            theOrder.Requested_Delivery_Date__c = datename ;
            insert theOrder;
           
            system.debug('TheOrder inserted'+theOrder);
        }
                         
         List<Order_Item__c> items = new List<Order_Item__c>();
         for(wrapNewOrder wno : inventoryList) {
         
          if(wno.selected==false){
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please select atleast one item');
                ApexPages.addMessage(msg);
            }
                   
            if(wno.selected == true) {
        
               Order_Item__c oItem = new Order_Item__c();
               oItem.Amount_Ordered__c = wno.amount;
               oItem.Comments__c = wno.splInstructions;
               oItem.Desired_Units__c = wno.selectDesiredUnit;
               system.debug('@@oItem.Desired_Units__c'+oItem.Desired_Units__c);
               oItem.Order__c = theOrder.Id;
               oItem.Inventory__c = wno.invItem.Id;
                items.add(oItem);
             
              System.debug('Print Amount'+wno.amount);
              System.debug('Print SpL'+wno.splInstructions);
              System.debug('Print id'+theOrder.Id);
            }
             
        }
       
        if(items.size()>0){
              insert items;
              System.debug(' -------item----------- '+ items);
              PageReference orderPage = new PageReference('/apex/'+'/OrderFulfillment2?sfdc.tabName=01rF0000000VOWh');
              orderPage.setRedirect(false);
              return orderPage;
      
       
    }
       return null;
    }

  public PageReference Cancel() {
     
     PageReference orderItemPage = new PageReference('/apex/'+'/OrderFulfillment2?sfdc.tabName=01rF0000000VOWh');
        orderItemPage.setRedirect(true);
        return orderItemPage;
    }

       // This is our wrapper/container class.
      
         public class wrapNewOrder {
         public Inventory_Item__c invItem {get; set;}
         public Boolean selected {get; set;}
         public String splInstructions { get; set; }
         public Decimal amount { get; set; }
         Public String selectDesiredUnit{get; set;}
       
       

        public wrapNewOrder(Inventory_Item__c a) {
            this.invItem = a;
            this.selected = false;
        }
    }

}
Iam able to insert the data into object. But iam unable to update the same record using the external id . when i use upsert dml without external id (phpId) i can able to insert the data into custom object . when i use upsert with external id i am not able to insert the data into object . please help where i did worng

Product__c product= createProduct(params);
              
                if(product!=null){
                 body = upsertSObject(product);
                              
                if (body.id != null) {  
                   String name1 =null;
                   String value1 =null;  
                   String phpId=null;               
                   JSONParser parser = JSON.createParser(params.get('attributeValues',false));       
                  
                    while (parser.nextToken() != null) {
                          if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'name1')) {
                                 parser.nextToken();
                                 name1= parser.getText();
                                }
                          if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'value1')) {
                                parser.nextToken();
                                value1 = parser.getText();
                              }
                              if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'phpId')) {
                                parser.nextToken();
                                phpId= parser.getText();
                              }
                          if(name1 !=null && value1 !=null&&phpId !=null) {
                                Attribute__c atrb= createAttributeItem(name1,value1,phpId, body.id);
                                upsertSObject (atrb) ;
                                value1 = null;
                                phpId=null;
                               }
................


public static Attribute__c createAttributeItem(String name1,String value1,string phpId, Id id) {
   
        Attribute__c atb= new Attribute__c ();
        atb.Product_Name__c= id ;
        atb.Attribute_Value__c= value1;
        atb.Php_Id__c = phpId;
        atb.name = name1;
            
        return atb;
    }

..............

private static ResponseBody upsertSObject(SObject sObj) {
        System.debug(JSON.serializePretty(sObj));
        ResponseBody body = new ResponseBody();
        try {
            if (sObj instanceof Product__c)
          
              upsert (Product__c) sObj Php_External_Id__c ;
             else if(sObj instanceof Attribute__c )
           upsert (Attribute__c) sObj ;//here iam inserting attributes but if upsert (Attribute__c) sObj Php_Id__c iam not able to insert the data into object please       help    me  how to insert and update using external id here.
            body.id = sObj.id;
          }
        catch (Exception e) {
            body.addError(e);
          }
        return body;
    }


Hi frnds,

i have a class where json parameters come in string format  among them two values come in decimal format i was not able to parse those values with my object values please help me in modfying the code and how to implement .

please find the below code and let me know waht need to be done

try {
            RestRequest req = RestContext.request;
            res = RestContext.response;
            res.statusCode = HTTP_OK;
            res.addHeader('Content-Type', CONTENT_TYPE);
            System.debug(JSON.serializePretty(req.params));

                 
                Params params = new Params(req.params);
                system.debug(' enter params'+params);
               
                Order__c order= createOrder(params);
              
                if(order!=null){
                 body = upsertSObject(order);
                              
               
                          }
                     }
                    catch (MyException e) {
                        if (body == null)
                             body = new ResponseBody();
                             body.addError(e);
                     }
                    catch (Exception e) {
                         if (res == null) throw e; // something horrible has happened!
                                res.statusCode = HTTP_ERROR;
                         if (body == null)
                                body = new ResponseBody();
                                body.addError(e);
                      }
                        if (body.id != null)
                            res.statusCode = HTTP_CREATED;
                                System.debug(JSON.serialize(body));
                            res.responseBody = Blob.valueOf(JSON.serialize(body));
                         }

     public static Order__c createOrder(Params p) {
       
        Order__c ord= new Order__c();
      //ord.Total_Price__c = getPrice(p.get('totalPrice',false));// not able to convert sting
        ord.Total_Quantity__c= Decimal.valueOf((p.get('totalQuatity',false))); // not able to convert the string into decimal
        ord.Buyer_Account__c = getBuyer(p.get('buyerName',false));
        ord.Order_Status__c  =p.get('status',false);
        ord.Payment_Type__c = p.get('payment',false);
        ord.Php_Id__c= p.get('phpId',false);
        ord.Seller_Account__c = getSeller(p.get('sellerName',false));
        ord.Product_Name__c = getProduct(p.get('productName',false));
         //  ord.Product_Name__c = p.get()
      
        return ord;
     }
   
     Public static id getBuyer(String buyerName){
   
        Account accounts = [Select Id, Name,RecordTypeid from Account where Name =:buyerName];
       
        return accounts.id ;
     }
   
    Public static Id getSeller(String sellerName){
   
        Account accounts = [Select Id, Name, RecordTypeid from Account where Name = :sellerName];
       
        return accounts.id ;
     }
  
    Public static id getProduct(String productName){
   
        Product__c product = [Select Id, Name from Product__c where Name = :productName Limit 1];
       
        return product.id ;
     }
 
    
     
    
    private static ResponseBody upsertSObject(SObject sObj) {
        System.debug(JSON.serializePretty(sObj));
        ResponseBody body = new ResponseBody();
        try {
            if (sObj instanceof Order__c )
                upsert (Order__c ) sObj ;
             
            body.id = sObj.id;
          }
        catch (Exception e) {
            body.addError(e);
          }
        return body;
    }

   
    private class Params {
        Map<String, String> params {get; private set;}
      
        String type {get; private set;}
       
       
        Params(Map<String, String> params) {
            this.params = params;
          //  totalPrice = params.get('totalPrice');
           // type = params.get('type');
           // System.assert(typeToRT.keySet().contains(type));
        }
       
        String get(String key) {
            return get(key, true);
        }
       
        String get(String key, Boolean prependType) {
            String value = params.get((prependType ? type + '_' : '') + key);
            return value == null ? '' : value;
        }
    }

    public class ResponseBody {
        public Id id {get; set;}
        public List<ResponseError> errors {get; set;}
        public String status {get; set;}

        public ResponseBody() {
            errors = new List<ResponseError>();
            status = STATUS_OK;
        }

        public void addError(DmlException e) {
            for (Integer i = 0; i < e.getNumDml(); i++)
                errors.add(new ResponseError(e, i));
        }

        public void addError(Exception e) {
            status = STATUS_FAIL;
            if (e instanceof DmlException)
                addError((DmlException) e);
            else
                errors.add(new ResponseError(e));
        }
    }


thanks,
Hareesh.
Hi ,

i had create the below rest api class. when try to access the class getting the url getting  invalid_session id ?

@RestResource(urlMapping='/FieldCase/*')
global with sharing class RESTCaseController {

@HttpPost  
  global static String createNewCase(String companyName, String caseType) {
     System.debug('COMPANY: '+companyName);
     System.debug('CASE TYPE: '+caseType);
     return null ;
    }
}
Hi all,

Based on picklist values i need to update Text field. is it possible.

Thanks in adv

Perhaps I'm missing something here but I can't find any docs or way to write unit tests for Apex REST classes for v24. Here's my class:

 

@RestResource(urlMapping='/v.9/member/*/results/*') 
global with sharing class MemberRestSvc {
 
  @HttpGet
  global static String doGet() {
  
    String[] uriKeys = RestContext.request.requestURI.split('/');
    // do awesome programming stuff here

  }
    
}

 

With a v23, I would typically write a test like:

 

RestRequest req = new RestRequest(); 
RestResponse res = new RestResponse();
 
req.requestURI = 'https://cs9.salesforce.com/services/apexrest/v.9/member/me/results/today';  
req.httpMethod = 'GET';

String results = MemberRestSvc.doGet(req, res);
System.assertEquals('awesomeness-happened',results);

 

However, I can't figure out how to specify the requestURI. It looks like the the System.RestContext class is not writeable? I keep getting NPEs. Any help would be greatly appreciated.

 

Thanks

Jeff Douglas

Appirio / CloudSpokes

http://blog.jeffdouglas.com

Hi

I have two users with same profile but  different roles

user1 is created some 3 reports.

Now i want to give access to user2 that all reports......