Search code examples
javascriptsalesforcevisualforce

commandbutton action


I have a commandbutton, When click I want it to save a phonecall record and redirect to the record page, after that open a new page in a new window which shows the editing page of a new case related to the call.

I am doing it like this:

//Pseudocode
public PageReference saverecord(){
   create a new phone call record;
   insert record;
   if(createnewcase)
      create case;
      insert case;
      create editcaseURL;
   return phonerecord page;
}

on the client side, In the commandbutton, I use <apex:param name="newcase" value="true" assignTo="{!createNewCase}"/> to set the createnewcase to true. and oncomplete javascript to open the popup window. I have test the phonerecord and caserecord seperately and succeeded. but when I put them in one class, the case was never created. and in the visualforce view state window. I can't even find the boolean createnewcase.

please help.

Thanks


Solution

  • It is easy to implement with Apex / JavaScript:

    The apex code:

    // Defining two variables for the both records (case and phone)
    public String caseId { get; set; }
    public String phoneId { get; set; }
    
    // Defining a boolean to render the JavaScript panel after saving
    punlic Boolean redirectNow { get; set; }
    
    public PageReference saverecord(){
        // Create a new phone call record;
        insert record;
    
        // Now reading a phone record id
        phoneId = record.id;
    
        if(createnewcase){
            create case;
            insert case;
    
            // Now reading a case id
            caseId = case.id;
        }
    
        // If case and phone are OK -> set this flag to true
        redirectNow = true;
    
        // We do not need to return a real page reference 
        // because we will redirecting with javascript
        return null;
    }
    

    And the Visualforce page with JavaScript:

    <!-- A command button, that rerenders a panel with JavaScript -->
    <apex:commandButton value="Save" action="{!saverecord}" reRender="doAfterSave"/>
    
    <!-- This panel renders only after you will save the new records -->
    <apex:outputPanel id="doAfterSave">
        <apex:outputPanel rendered="{!redirectNow}">
            <script>
                // First reading the id's
                var newCaseId = '{!caseId}';
                var newPhoneId = '{!phoneId}';
    
                if(newCaseId != '' && newPhoneId != '')
                {
                    // Now opening a new window with case in edit mode
                    window.open('/' + newCaseId + '/e');
    
                    // And then redirecting the main page to the new phone record
                    window.location = '/' + phoneId;
                }
            </script>
        </apex:outputPanel>
    </apex:outputPanel>