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.');

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

<!-- rest of page -->
 function onControllerReturn() {
  • 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 '14 at 22:37

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" />
function getLastMessage() {
    var msg = document.getElementById("{!$Component.lastMessage}");
    if(msg.value) alert(msg.value);
| improve this answer | |

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.