+ Start a Discussion
willardwillard 

not sure how to use putSObject method

Hi,

After looking at the documentation for the putSObject method (part of the SObject class), I still can't get it to work.

 

I have a print_pricing__c object and a child object called pricing_discount__c.

 

the getSObject method works fine:

discounts = pricing.getSObjects('print_discounts__r');

 

However, the corresponding putSObject method, I just can't seem to get to work.  It compiles fine, but at runtime, I get the following error:

System.SObjectException: Invalid relationship print_discounts__r for Print_Pricing__c 

 

Here's my code for that:

 

 pricing.putSObject('print_discounts__r', new print_discount__c(name='blah',field2='blah2'));

 I've tried variations of this, i.e.,  pricing.putSObject('print_discount__c', new print_discount__c(name='blah',field2='blah2'));

 

But to no avail.  Any idea how to use this method?  Thanks.

 

mtbclimbermtbclimber

The issue is that you are referring to a child relationship not a lookup relationship. With a child relationship there can be more than one which is why it's called getSObjects (plural). You are then trying to use that same relationship with putSObject (singular and intended for lookups/master/detail relationships). 

 

The reason we support put on sobject is to facilitate foreignkey upsert scenarios. What's your use case for wanting to manually set this relationship? If your query does an aggregate, for example: select name, (select name from contacts) from account the "contacts" child relationship on account will have records in it assuming there are records.  

 

Is this in a test?

willardwillard

Well - here's the full scenario:

 

I have a VF page with print_pricing__c pageBlock and then a print_discounts__r pageBlockTable.

 

I have a button which does some processing and brings back one more discount that I want to add to the print_discounts__r pageBlockTable.

 

I want to be able to do this without saving the page if at all possible and so that's why I figured I'd use putSObject, thinking that it might update the page.  (I'm using the rerender tag to do partial page refreshes).

 

Right now I'm just using a custom list controller to do the processing so that gets past my issue.  I guess in general I want to be able to store a lot of things in the "buffer", and then save everything in one shot, but I feel like salesforce is designed to save one object at a time, correct?

Lawrence-AccentureLawrence-Accenture
Any update on this? I'm in a similar situation... trying to build children relationships out in memory (without a database save) by populating children records into the child relationship reference (i.e. myAccountRec.Contacts.add(new Contact( ... ))) but there doesn't seem to be a way to get it to work. Having this capability would be a huge benefit -- saving us from having to model our data in memory differently than it is modeled in the database.