1

I want to show the error message on Javascript alert popup.Is it possible?

I have a custom detail button which calls below page and creates a related record.If related record exists then I want to show an error message saying Related record exists

public class MyController
 {
public void MyActionMethod()
{
  // Checks if record exists else throw below error message
  ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Related record exists.');
        ApexPages.addMessage(myMsg);
}
}

<apex:page controller="MyController" action="{!MyActionMethod}">



<!-- rest of page -->
 <script>
 function onControllerReturn() {
 alert('{!message}')
 }
 </script>
</page>
1
  • 2
    Seems like if you are set on controlling the firing of a pop-up based on the returning of a message response event, that you are best of using Javascript Remoting rather than traditional VF actionFunctions.
    – greenstork
    Dec 15, 2014 at 22:37

1 Answer 1

3

ApexPages.Message is designed to work with the Visualforce managed elements for displaying such messages (apex:pageMessages and apex:messages). You wouldn't use these methods to show a popup in JavaScript, unless you were using an advanced programming technique, such as a lightbox. For a simple alert, you want pure text, not rendered HTML code that you'd have to parse/strip. This means that a @RemoteAction would be more appropriate, although this doesn't let you get to the page state.

If you want to return a simple message, the traditional means of doing so is to expose that message through a rendered element. Consider the following:

<apex:inputHidden value="{!lastMessage}" id="lastMessage" />
<apex:actionFunction action="{!myActionMethod}" reRender="lastMessage" onComplete="getLastMessage()" status="statusElement" />
<script>
function getLastMessage() {
    var msg = document.getElementById("{!$Component.lastMessage}");
    if(msg.value) alert(msg.value);
}
</script>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .