0

First, I'm just a starter and now writing a visual force page and apex

Basically, I have objects A and B, A is master and B is detail, every time creating a B I will set the default balance value as the same as A, my code is as below:

 //visual force page:
 <apex:inputField value="{!acc.A__c}"/>

 //apex code:
 public void upgrade(){
        A__c bc;
        bc.Id  = acc.A__c;
        Decimal str = bc.Balance__c;
        acc.Balance__c = str;
        insert acc;
}

it didn't work for some reasons, so is there any way to get the value of the master A_c and copy it into the same field B_c??

any helps are welcomed!!!

user1804033
  • 53
  • 1
  • 6

1 Answers1

0

You don't need Visualforce to achieve that, a workflow rule or maybe form prepopulation trick is sufficient.

Make a new rule on the detail object with criteria "every time record is created" and the action would be a field update that sets details Balance field. The formula to which it should be set is simply Master__r.Balance__c, A__r.Balance__c or hovewer you have named the master-detail field.

If you insist on using visualforce - your code is completely messed up (starting from the fact that in normal circumstances you never assign anything to Id field).

If the idea is that your user will fill in the lookup from B to A (the A__c field), then:

B__c b = new B__c();
// Some time later user fills in the lookup
// b.A__c = 'some id here';
// and hits save button.

public void save(){
    if(b.A__c != null){
        A__c selectedA = [SELECT Id, Name, Balance__c FROM A__c WHERE Id = :b.A__c];
        b.Balance__c = selectedA.Balance__c;
    }
    insert b;
}
eyescream
  • 18,088
  • 2
  • 34
  • 46