0

I have a custom visual force page. I use Visualforce.remoting.Manager.invokeAction to post data and create a custom object on a custom Apex Controller extension. This action creates my custom object and then returns it. I would like then to redirect to the newly created record page. I have been struggling to do that. Here's the javascript code :

Visualforce.remoting.Manager.invokeAction(
  '{!$RemoteAction.TestController.saveFacture}',
   facture, factureDate.value, factureLines,
  function(result, event){
      console.log("in callback func");

        //redirect
        console.log(result);

       var url = '{! urlfor("facture__c", null)}';

  },
  {escape: true}
);

and here is the controller action Im calling :

  @RemoteAction
    public static Facture__c saveFacture(Facture__c facture, String factureDate, Ligne__c[] lines) {
        // Perform isUpdatable() checking first, then
        System.debug('facture: '+ facture);
        facture.date__c = date.valueOf(factureDate);
        upsert facture;
        for (Ligne__c line : lines){
            line.facture__c = facture.id;
            upsert line;
        }
        return facture;
    }

it returns a facture object that I can Use to build the url where I want to redirect on the client side (result.Id). However I cant find how to correctly build the url to redirect to. I ve been trying to use UrlFor unsuccessfully. How can I achieve that ?

0

You can't use URLFOR() here, because your JavaScript remoting interactions happen outside the Visualforce rendering cycle. The URLFOR() function can't be executed in JavaScript on the client side, and when the page is rendered, you won't have the object details.

Instead, you can use standard JavaScript methods to navigate to a new page. An example is below.

If you're operating in a mobile or Lightning context, rather than setting window.location.href, you should use sforce.one.navigateToSObject.

Visualforce Example

<apex:page controller="TestRemoting">
    <script>
    Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.TestRemoting.runQuery}',
        function(result, event){
            console.log(result);
            window.location.href= '/' + result.Id;
        },
        {escape: true}
    );
    </script>

</apex:page>

Apex Controller

public class TestRemoting {
    @RemoteAction
    public static Account runQuery() {
        return [SELECT Id FROM Account LIMIT 1];
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.