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
JosephJJosephJ 

Search by OwnerId for Task object???

I tried each and every possibility to know where i'm going wrong but still no luck. My issue is my search (i.e. filter) is working on Subject,Status and Date field for Task object .

Now i want to search for one more column which is "OwnerId" . I know it can be done using if condition something like below  but what should be "IF condition " to get to the goal ?

if (logical condition  to filter by owner) {
    qStr + ' and OwnerId in :ownerIds';


I'm really paralyzed and need help.

public class PagingTasksController1{

    public List<Task> Tasks;

   
    public Task del;
    public Task taskDel;
    public Integer CountTotalRecords{get;set;}
    public String QueryString {get;set;}
    public Integer OffsetSize = 0;
    private Integer QueryLimit =3 ;
    public List<Task> lstTasks {get;set;}
    public String searchText {get;set;}
    public String rowIndex {get;set;}
//   public List<Task> attendeeList {get;set;}
    public Date mydate;
    public Integer totalCount {get;set;}
    public string sortField = 'Subject';  // default sort column
    private string sApplySOQL = '';
   public List<Task> delattendeeList {get;set;}

    public List<Task> delAttendees {get; set;}

    public PagingTasksController1(ApexPages.StandardController controller) {

     taskDel= (Task)controller.getRecord();
     Tasks = [Select id,Subject,Status,ActivityDate from Task where OwnerId =: taskDel.Id];
    // this.Tasks=Tasks[0];
     totalCount = Tasks.size();

     delattendeeList = new List<Task>();
     delattendees = new List<Task>();
}


// the current sort direction. defaults to ascending
    public String sortDir {
        get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
        set;
    }

    // the current field to sort by. defaults to role name
    public String getsortField() {
        return sortField;
    }

    // the current field to sort by.
    public void setsortField(string value) {
        sortField = value;
    }
            
    // toggles the sorting of query from asc<-->desc
    public void toggleSort() {
        // simply toggle the direction
        sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
      
        integer iIndex = sApplySOQL.indexOf('Order By');
        if (iIndex > -1){
          sApplySOQL = sApplySOQL.substringBefore('Order By');
          sApplySOQL = sApplySOQL + ' Order By ' + sortField + ' ' + sortDir +  ' limit ' + QueryLimit + ' offset ' + OffsetSize;
        }
        tasks = Database.query(sApplySOQL );
    }
  
    public PagingTasksController1 (){
        //CountTotalRecords= [select count() from Task];
        //String qStr2= '7/23/2014';
          
    }

   public List<Task> getTasks(){
        if(tasks == null){
            tasks = new List<Task>();
        }
        return tasks;
    }

    public void findTasks(){
        String qStr2 = 'Select count() from Task where Subject like \'%'+searchText+'%\' OR Status like \'%'+searchText+'%\'';
        CountTotalRecords = Database.countQuery(qStr2);
        queryTasks();
    }

    public void  queryTasks(){
        
        String qStr2= searchText;
        String strnormal = '';
        try{
             mydate = date.parse(qStr2);
        }catch(Exception e)
        { }
           
        String strDate = '';
        if(mydate != null) {
         // strnormal = String.valueOf(mydate );
          String[] qstr3 = String.valueOf(mydate).split(' ',2); 
          strDate = ' ActivityDate =  '+ qstr3[0] + ' ';
        }else{
       
           strDate  =  'Subject like \'%'+searchText +'%\' OR Status like \'%' +searchText+ '%\' Order By '  + sortField;
        }
        String qStr = 'Select OwnerId,Subject,Status,ActivityDate from Task where '  + strDate   ;

         System.debug(qStr );
           
//        String qStr = 'Select OwnerId,Subject,Status,Priority from Task where Subject like \'%'+searchText+'%\' OR Status like \'%'+searchText+ '%\' Order By ' + sortField;

       
       
        sApplySOQL = qStr;
      
        tasks = Database.query(sApplySOQL );
        //tasks.sort();

    }

    public Boolean getDisablePrevious(){
        if(OffsetSize>0){
            return false;
        }
        else return true;
    }

    public Boolean getDisableNext() {
        if (OffsetSize + QueryLimit < countTotalRecords){
            return false;
        }
        else return true;
    }

    public PageReference Next() {
        OffsetSize += QueryLimit;
        queryTasks();
        return null;
    }

    public PageReference Previous() {
        OffsetSize -= QueryLimit;
        queryTasks();
        return null;
    }

      public PageReference save() {
        update tasks;
        return ApexPages.CurrentPage();
     }
    
    public void deleteRow(){

         rowIndex = String.valueOf(ApexPages.currentPage().getParameters().get('rowIndex'));
         System.debug('rowIndex ------------'+rowIndex );
         if(rowIndex!=null)
         {
         Task check=[Select id from Task where id=: rowIndex];
         System.debug('row to be deleted ' + check);
         delete check;
         Tasks=[Select Subject,Status,ActivityDate,OwnerId from Task ];
         update Tasks;
         }
     }
     
  }
Peter_sfdcPeter_sfdc
I don't see anything obviously wrong with what you are trying. 

What exactly happens? No results? Error? 

Have you played with or tested your logic in an exec anonymous block in isolation to validate your approach? 
JosephJJosephJ
What'am i looking is , i want to filter the search by OwnerId , but i'm struggling to make it to get the IF condition for the search . It can be done by anystuff  . What should be my source code to search by OwnerId ?

I know that this will come ,but would be the code for the below ? It would be helpful

if (logical condition  to filter by owner) {
    qStr + ' and OwnerId in :ownerIds';


Peter_sfdcPeter_sfdc
Ok. 

Under what circumstances do you want to have your query include this part of the WHERE clause? 

Under what circumstances do you want it to not include this part of the WHERE clause? 

I know nothing about what you are trying to accomplish, and why, and frankly don't have time to read through your code to try to understand it, but if you would explain to me, show me your UI, give me some background, I might be able to help. You haven't even shown in your code where ownerIds is coming from, how it is constructed, or a data type (list or set). So it is difficult to come up with an if condition without some more information. 

For instance, one possible solution could be the following: 

"ownerIds is a set. I need to include this part of the where clause when the ownerIds set has any members" 

In that instance I would do the following: 
if (ownerIds != null && ownerIds.size() > 0){
    ....put my code that adds the where clause fragment...
}

But even this is a shot in the dark without more background from you. 

Thanks. 
JosephJJosephJ

OK..I have implemented Pagination,Search,arror sorting,inline edit on Task object. For the Search ,It is currently working on Subject ,Status and ActivityDate. Now there is one more requirement to filter by OwnerId this is where i'm stucked .

I've not implemented it still in controller becasue there is a confusion. queryTask() is where the whole search is there .below is the code for VF page.Also snapshot shown below.

Hope i'm clear.


<apex:page controller="PagingTasksController1" docType="html-5.0">
    <apex:form >
        <apex:variable var="rowNumber" value="{!0}"/>
        <apex:pageBlock title="Tasks" id="pgBlock" >
      
           <apex:pageBlockButtons >
               <apex:commandButton action="{!save}" id="saveButton" value="Save"/>
               <apex:commandButton onclick="resetInlineEdit()" id="cancelButton" value="Cancel"/>
           </apex:pageBlockButtons>
 
        <apex:inlineEditSupport showOnEdit="saveButton, cancelButton"
                    hideOnEdit="editButton" event="ondblclick"
                    changedStyleClass="myBoldClass" resetFunction="resetInlineEdit"/>
 
          <apex:inputText id="searchBox" value="{!searchText}"/>
           <apex:commandButton value="Search" reRender="pgTable,pgBlock" action="{!findTasks}"/>
          
          <apex:pageBlockTable value="{!Tasks}" var="tsk" id="pgTable">
              
         <apex:column headerValue="Action" >
           <apex:commandButton value="Delete" action="{!deleteRow}" reRender="pgTable">
           <apex:param name="rowIndex" value="{!tsk.id}"/>
          </apex:commandButton>             
        </apex:column>
          
                 
         <!-- <apex:column headerValue="Action" >
            <apex:outputLink value="{!URLFOR($Action.Task.Delete, .id,['retURL'='/apex/New_Test_task_Assignment'])}"> Delete</apex:outputLink>
           </apex:column>  -->
        
          <apex:column headerValue="Subject">
              <apex:facet name="header">
                    <apex:commandLink value="Subject" action="{!toggleSort}" rerender="pgTable" >
                    <apex:param name="sortField" value="Subject" assignTo="{!sortField}"/>
                    <apex:outputPanel rendered="{!BEGINS(sortField,'Subject')}">
                        &nbsp;<apex:image value="{!IF(sortDir = 'desc','/img/arrowDown.gif','/img/arrowUp.gif')}"/>
                    </apex:outputPanel>
                    </apex:commandLink>
                </apex:facet>    
              
                  <apex:outputField value="{!tsk.Subject}"/>
           </apex:column>
          
          
           <apex:column headerValue="Status">
               <apex:facet name="header">
                    <apex:commandLink value="Status" action="{!toggleSort}" rerender="pgTable" >
                    <apex:param name="sortField" value="Status" assignTo="{!sortField}"/>
                    <apex:outputPanel rendered="{!BEGINS(sortField,'Status')}">
                        &nbsp;<apex:image value="{!IF(sortDir = 'desc','/img/arrowDown.gif','/img/arrowUp.gif')}"/>
                    </apex:outputPanel>
                    </apex:commandLink>
              </apex:facet>        
 
             <apex:outputField value="{!tsk.Status}"/>
         </apex:column>

     
        <apex:column headerValue="OwnerId">
            <apex:outputField value="{!tsk.OwnerId}"/>
        </apex:column>
       

        <apex:column headerValue="date">
            <apex:outputField value="{!tsk.ActivityDate}"/>
        </apex:column>  
          
     </apex:pageBlockTable>
       <apex:pageBlockButtons >
                <apex:commandButton value="Previous" action="{!Previous}" rerender="pgTable,pgBlock"
                                    status="status" disabled="{!DisablePrevious}" />
                <apex:commandButton value="Next" action="{!Next}" reRender="pgTable,pgBlock"
                                    status="status" disabled="{!DisableNext}" />
                <apex:actionStatus id="status" startText="Please Wait..."/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
   <apex:enhancedlist type="Activity" height="800" rowsPerPage="50" customizable="False"/>
</apex:page>









The screen looks like this.

JosephJJosephJ
How do i append my query in this IF clause part is what i'm struggling to get.
JosephJJosephJ
Following is what i'm doing and it is giving me an error :  Error: Compile Error: expecting a semi-colon, found ' and OwnerId in :ownerIds' at line 106 column 142


public void  queryTasks(){
        
        String qStr2= searchText;
        Set<Id> ownerIds = new Set<Id>();
        String strnormal = '';
        try{
             mydate = date.parse(qStr2);
        }catch(Exception e)
        { }
           
        String strDate = '';
        if(mydate != null) {
         // strnormal = String.valueOf(mydate );
          String[] qstr3 = String.valueOf(mydate).split(' ',2); 
          strDate = ' ActivityDate =  '+ qstr3[0] + ' ';
        }else{
       
           strDate  =  'Subject like \'%'+searchText +'%\' OR Status like \'%' +searchText+ '%\' Order By '  + sortField;
        }
       
        if (ownerIds != null && ownerIds.size() > 0){
       
          String qStr = 'Select OwnerId,Subject,Status,ActivityDate from Task where '+strDate+' limit ' + QueryLimit + ' offset ' + OffsetSize' and OwnerId in :ownerIds';
        }

       
        //String qStr ='Select OwnerId,Subject,Status,ActivityDate from Task where \''+strDate +'\' limit ' + QueryLimit + ' offset ' + OffsetSize;
        // String qStr = 'Select OwnerId,Subject,Status,ActivityDate from Task where '+strDate+' limit ' + QueryLimit + ' offset ' + OffsetSize;
       

         System.debug(qStr);
           
//        String qStr = 'Select OwnerId,Subject,Status,Priority from Task where Subject like \'%'+searchText+'%\' OR Status like \'%'+searchText+ '%\' Order By ' + sortField;

      
        tasks = Database.query(qStr);
        //tasks.sort();

    }
Peter_sfdcPeter_sfdc
Two things. The error you are recieving is here:
QueryLimit + ' offset ' + OffsetSize + ' and OwnerId in :ownerIds';
//You are missing this plus sign ----^

You need the + between "OffsetSize" and the single quote that follows to tell Apex to append. 

Even when you fix this, you will get a malformed query in its current form. You're appending in the wrong place. 

The fragment of your where clause needs to go into the where clause part of your SOQL query. Here: 
where '+strDate+ /*append new filter here*/' limit

Forum Usage Suggestion

Another suggestion for using these forums: there is a control in the editor that looks like this: 
< >

If you click on that you can add code to your question that is formatted, color-coded, and line numbered. This will make it easier to read. Instead of this: 

String strDate = '';
        if(mydate != null) {
         // strnormal = String.valueOf(mydate );
          String[] qstr3 = String.valueOf(mydate).split(' ',2);
          strDate = ' ActivityDate =  '+ qstr3[0] + ' ';

It will display like this: 
String strDate = '';
        if(mydate != null) {
         // strnormal = String.valueOf(mydate );
          String[] qstr3 = String.valueOf(mydate).split(' ',2); 
          strDate = ' ActivityDate =  '+ qstr3[0] + ' ';



Vasani ParthVasani Parth
@Peter, Didn't catch you by below

The fragment of your where clause needs to go into the where clause part of your SOQL query. Here:

where '+strDate+ /*append new filter here*/' limit

I've written SOQL in iF condition .Now the situation is by search box is not working  after writing IF condition and mentioning the query .Could you please make me move forward ??