function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
arun kumar.ax887arun kumar.ax887 

How to convert a String to Date

I have a requirement where in  I need to fetch the records from Opportunity standard object based on the closedate field (MM/DD/YYYY) criteria.  For that I have written a visualforce page which takes the close date in the search field which is accepted as a string.  But in the Apex class when I am executing the sql query, i am getting type mismatch error, date cannot be compated to string.   I tried many options to convert string to date, but its not working.   I am  postng  the code snippet.

 

 

Apex Class

 

 

public class OpportunitySearchController1 {

    public OpportunitySearchController1() {

    }

    
    private ApexPages.StandardController controller {get; set;}
  
      public List<opportunity> searchResults {get;set;}
    
          public string searchText {
        get {
            if (searchText == null) searchText = 'Test'; // prefill the serach box for ease of use
            return searchText;
        }
        set;
    }
  
    
 
    public OpportunitySearchController1(ApexPages.StandardController controller) {
 
               this.controller = controller;
       
    }
 
   
    public PageReference search() {
        if (searchResults == null) {
            searchResults = new List<opportunity>(); // init the list if it is null
        } else {
            searchResults.clear(); // clear out the current results if they exist
        }
        // Note: you could have achieved the same results as above by just using:
        // searchResults = new List<categoryWrapper>();
        String date_search= searchText;
 
        // use some dynamic soql to find the related opportunities by name
       
           String qry = 'Select o.Id, o.Name, o.StageName, o.CloseDate, o.Amount from Opportunity o  where  o.closedate LIKE \''+searchText+'%\' Order By o.Name';
      
        searchResults = Database.query(qry);
        return null;
    }
 }

 

 

VisualForce Page

-------------------------

<apex:page standardController="Opportunity" extensions="OpportunitySearchController1" sidebar="true" showHeader="true" >
<style type="text/css">
body {background: #F3F3EC; padding-top: 15px}
</style>
<!-- <b><apex:outputLink value="https://c.ap1.visual.force.com/apex/jeff"> Opportunities </apex:outputLink></b>&nbsp;&nbsp;
<b><apex:outputLink value="https://c.ap1.visual.force.com/apex/subhash"> Contacts </apex:outputLink></b>
-->
<apex:form >
<br/><br/><br/>
<b><apex:outputLink value="https://c.ap1.visual.force.com/apex/GeneralReport"> Opportunities </apex:outputLink></b>&nbsp;&nbsp;
<br/><br/> <b><apex:outputLink value="https://c.ap1.visual.force.com/apex/DisplayReport"> Tasks </apex:outputLink></b>
<br/><br/>
<apex:pageBlock title="Search for Opportunities by Keyword" id="block" mode="edit">
<apex:pageMessages />

<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel for="searchText">Close Date</apex:outputLabel>
<apex:panelGroup >
<apex:inputText id="searchText" value="{!searchText}"/>
<apex:commandButton value="GO" action="{!search}" rerender="resultsBlock" status="status"/>
</apex:panelGroup>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:actionStatus id="status" startText="Searching... please wait..."/>
<apex:pageBlockSection id="resultsBlock" columns="1">
<apex:pageBlockTable value="{!searchResults}" var="o" rendered="{!NOT(ISNULL(searchResults))}">
<apex:column headerValue="Name">
<apex:outputLink value="/{!o.Id}">{!o.Name}</apex:outputLink>
</apex:column>
<apex:column value="{!o.StageName}"/>
<apex:column value="{!o.Amount}"/>
<apex:column value="{!o.CloseDate}"/>

</apex:pageBlockTable>
</apex:pageBlockSection>

</apex:pageBlock>
</apex:form>
</apex:page>

 

If you have any  solution for the above mentioned code kindly post your suggestion. 

 

 

 

 

Regards

 

Arun

 

SteveBowerSteveBower

Rather than prompt for text from the user you might consider using a "dummy" Opportunity to get the closeDate from the user.  Then use that field in the query.  It also gives you the benefits of the Date Picker on the VF page, you don't have to muck about with strings, etc.

 

It's the general pattern of using an instance of an Object to gather search criteria for that Object.  Of course, the permissions, etc. apply to the <inputField> tag.  So, if your users don't have the permissions to enter the closeDate, then you have to do the workaround you're doing.

 

 

In class::

public Opportunity userInputOpportunity {get; set;}

 

In Constructor:

userInputOpportunity = new Opportunity();

 

and then later: 

 

         searchResults = new List<Opportunity> ([Select Id, Name, StageName, CloseDate, Amount from Opportunity  where  closedate = :userInputOpportunity.closeDate Order By Name]);

 

And in the VF:

 

<apex:inputField value="{!userInputOpportunity.closeDate}">

 

 

Best, Steve.

 

p.s. As to why what you're doing isn't working, don't include quotes around the date in the Where clause.  And, I don't think you can use "Like" for a date (although I'd have to look it up to be sure... :-) )
      

arun kumar.ax887arun kumar.ax887

Hi Steve,

 

    I made the required changes in the code as per you suggestion.  The query was executing successfully,  but only for once.  I mean,  when I tried to execute the query with some different date, the query is not working.  So could you please validate the below mentioned code and send a better solution.

 

 

Apex Class

 

public class OpportunitySearchController1 {

    public OpportunitySearchController1() {

    }
    
    public Opportunity userInputOpportunity {get; set;}

    
    private ApexPages.StandardController controller {get; set;}
 
      public List<opportunity> searchResults {get;set;}
        
 
    public OpportunitySearchController1(ApexPages.StandardController controller) {
 
               this.controller = controller;
               userInputOpportunity = new Opportunity();
       
    }
 
   
    public PageReference search() {
        if (searchResults == null) {
                  searchResults = new List<Opportunity> ([Select Id, Name, StageName, CloseDate, Amount from Opportunity  where  closedate = :userInputOpportunity.closeDate Order By Name]);
        }

else {
            searchResults.clear(); // clear out the current results if they exist
        }
       
                 
        return null;
    }
 }

 

 

VisualForce Page

 

 

<apex:page standardController="Opportunity" extensions="OpportunitySearchController1" sidebar="true" showHeader="true" >
    <style type="text/css">
        body {background: #F3F3EC; padding-top: 15px}
    </style>
<!-- <b><apex:outputLink value="https://c.ap1.visual.force.com/apex/jeff"> Opportunities </apex:outputLink></b>&nbsp;&nbsp;
 <b><apex:outputLink value="https://c.ap1.visual.force.com/apex/subhash"> Contacts </apex:outputLink></b>
 -->
    <apex:form >
  <br/><br/><br/>      
 <b><apex:outputLink value="https://c.ap1.visual.force.com/apex/GeneralReport"> Opportunities </apex:outputLink></b>&nbsp;&nbsp;
<br/><br/> <b><apex:outputLink value="https://c.ap1.visual.force.com/apex/DisplayReport"> Tasks </apex:outputLink></b>
<br/><br/>  
            <apex:pageBlock title="Search for Opportunities by Keyword" id="block" mode="edit">
            <apex:pageMessages />
 
            <apex:pageBlockSection >
                <apex:pageBlockSectionItem >
                    <apex:outputLabel for="searchText">Close Date</apex:outputLabel>
                    <apex:panelGroup >
                    <apex:inputField value="{!userInputOpportunity.closeDate}"/>
            
                    <apex:commandButton value="GO" action="{!search}" rerender="resultsBlock" status="status"/>
            
                    </apex:panelGroup>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
            <apex:actionStatus id="status" startText="Searching... please wait..."/>
            <apex:pageBlockSection id="resultsBlock" columns="1">
                <apex:pageBlockTable value="{!searchResults}" var="o" rendered="{!NOT(ISNULL(searchResults))}">
                    <apex:column headerValue="Name">
                        <apex:outputLink value="/{!o.Id}">{!o.Name}</apex:outputLink>
                    </apex:column>
                    <apex:column value="{!o.StageName}"/>
                    <apex:column value="{!o.Amount}"/>
                    <apex:column value="{!o.CloseDate}"/>
                   
                </apex:pageBlockTable>
            </apex:pageBlockSection>
 
        </apex:pageBlock>
    </apex:form>
</apex:page>

 

 

 

Regards

 

Arun

 

SteveBowerSteveBower

Look at your searchResults method... 

 

    public PageReference search() {
        if (searchResults == null) {
                  searchResults = new List<Opportunity> ([Select Id, Name, StageName, CloseDate, Amount from Opportunity  where  closedate = :userInputOpportunity.closeDate Order By Name]);
        }

else {
            searchResults.clear(); // clear out the current results if they exist
        }                 
        return null;
    }

 

If the results are null (as they are in the beginning), then do the search.   However, they will never be null again.  When you come back through the results won't be null, so you'll clear the searchResults (which just gives you an empty list... not a Null), and return null for the value of the PageReference.  So, you're never re-issuing the query.

Since you seem to want to rerun the search every time this method is called, just change it to:

 

public PageReference search() {

    searchResults = new List<Opportunity> ([Select Id, Name, StageName, CloseDate, Amount from Opportunity  where  closedate = :userInputOpportunity.closeDate Order By Name]);

    return null;

}

 

Best, Steve.

NaishadhNaishadh