0

I have if condition in managed bean. I want to display alert when condition is true. How I do that? something like:

    public void catInsert()
        {
            if(abr.searchCategoryByCategoryName(CategoryName)!=null){
    //                msg = "<div style = 'color:red'>CategoryName already exist!</div>";
    //                System.out.println(msg);
//  i want alert here

            }else
            {
            abr.addCategory(CategoryName);
            CategoryName="";
            }
         }

and xhtml page is;

<table class="nostyle">
                <tr>
                    <td align="right">
                    <h:outputText value="Category Name:"></h:outputText>
                    </td>
                    <td>
                        <h:inputText id="txtcatname" value="#{categoryBean.categoryName}" required="true" requiredMessage="Enter category Name" >
                        </h:inputText>
                    </td>
                    <td ><h:message for="txtcatname" style="color: #df0000"></h:message></td>>            
                </tr>
                <tr>
                    <td></td>
                    <td align="left">
                        <h:commandButton id="submit" type="Submit" value="submit" action="#{categoryBean.catInsert()}" >
                        </h:commandButton>
                    </td>

                </tr>
            </table>
user1450369
  • 13
  • 3
  • 7

1 Answers1

2

You're making a conceptual mistake. HTML/JS code doesn't belong in the controller, but in the view. The controller has to inform the view somehow that it has to generate the desired bunch of HTML/JS code.

You could do that by setting a boolean property like so

private boolean showCategoryNameAlert;

public void catInsert() {
    if (abr.searchCategoryByCategoryName(categoryName) != null) {
        showCategoryNameAlert = true;
    } else {
        abr.addCategory(categoryName);
    }
}

public boolean isShowCategoryNameAlert() {
    return showCategoryNameAlert;
}

with

<h:outputScript rendered="#{categoryBean.showCategoryNameAlert}">
    alert("CategoryName already exist!");
</h:outputScript>

By the way, why don't you use FacesContext#addMessage() with <h:messages> or maybe even a normal JSF Validator on the input field? Showing JavaScript alerts is soo 90's and performing input validation in an action method is poor design.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555