anusha(salesforce developer)

Monday 20 June 2016

Dynamically making a field required using Apex in Salesforce

Sample Code:

Visualforce Code:

<apex:page controller="sample">
   
    <apex:form >
   
    <apex:pageMessages/>
   
    <apex:pageBlock>
        <apex:pageBlockSection columns="2">
            <apex:pageblockSectionItem>
                <apex:outputLabel value="Known City"/>
            </apex:pageblockSectionItem>       
            <apex:pageblockSectionItem>               
                <apex:inputCheckbox value="{!knwCity}">            
                    <apex:actionSupport event="onchange" reRender="a"/>
                </apex:inputCheckbox>
            </apex:pageblockSectionItem>
            <apex:pageblockSectionItem>
                <apex:outputLabel value="City"/>
            </apex:pageblockSectionItem>           
            <apex:pageblockSectionItem>
                <apex:inputText value="{!city}" required="{!bool}" id="a"/>
            </apex:pageblockSectionItem>     
            <apex:commandButton value="Save" action="{!save}"/>     
        </apex:pageBlockSection>       
    </apex:pageBlock>

    </apex:form>

</apex:page> 


Apex Class:

public class sample
{
    public String city {get;set;}
    public Boolean knwCity {get;set;}
    public Boolean bool {get;set;}
       
    public void save()
    {
        bool = false;
        if(knwCity == true)
        {
            bool = true;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'City is required when Known city is checked'));
        }
    }
   
    public sample()
    {
        bool = false;
       
    }
     
}

No comments:

Post a Comment