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
Vasani ParthVasani Parth 

delete button does not work with search by OwnerId


My delete button does not work after putting endless efforts and thought to post here.When i click on Delete button, its just rerendering and not deleting after trying with actionSupport.

Also I'm not able to search by OwnerId though my query is right. Please 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 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;
        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';
          System.debug(qStr); 
          tasks = Database.query(qStr);         
        }
       
           //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;
       
                  
            //  String qStr = 'Select OwnerId,Subject,Status,Priority from Task where Subject like \'%'+searchText+'%\' OR Status like \'%'+searchText+ '%\' Order By ' + sortField;

       //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;
           }
         }
       }


         <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')}">
                         <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')}">
                         <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>


Denis VakulishinDenis Vakulishin
Hi,
You need to assignTo attribute on param to pass parameter.
Check this http://blog.jeffdouglas.com/2010/03/04/passing-parameters-with-a-commandbutton/
Vasani ParthVasani Parth
But if you check my code the search for OwnerId is also not working. I gave all tries, stucked and pressing my head..
Denis VakulishinDenis Vakulishin
String qStr = 'Select OwnerId,Subject,Status,ActivityDate from Task where '+strDate+' limit ' + QueryLimit + ' offset ' + OffsetSize +' and OwnerId in :ownerIds'
You cannot use ":variable" if you use dynamic soql. you should concatinated string like ('id1','id2','id3')
so the end of soql string will look like 
and OwnerId in (\'id1\',\'id2\',\'id3\')'


Vasani ParthVasani Parth
Could  you please help me ..I understood  the point . But how will the implementation will work like in m query . Do you see an issue with the Controller ?
Vasani ParthVasani Parth
If i do something like this it works fine . But the requirement is to search by OwnerId  which is not working ..

/*  if (ownerIds != null && ownerIds.size() > 0){
       
          String qStr = 'Select OwnerId,Subject,Status,ActivityDate from Task where '+strDate+' limit ' + QueryLimit + ' offset ' + OffsetSize +' and OwnerId in (\'id1\')';
          System.debug(qStr); 
          tasks = Database.query(qStr);         
        }*/
       
        //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); 
          tasks = Database.query(qStr);


Denis VakulishinDenis Vakulishin
Heres the method to concatinate ids into string 
private static string JoinSetIds(Set<Id> objIds)
   {
      if(objIds == null || objIds.size() == 0)
      {
         return '';
      }
      List<string> lIds = new List<string>();
      for(Id pId : objIds)
      {
         lIds.add((string)pId);
      }
      return '(\'' + String.join(lIds, '\',\'' ) + '\')';
   }

just add this method and rewrite like this 
String qStr = 'Select OwnerId,Subject,Status,ActivityDate from Task where '+strDate+' limit ' + QueryLimit + ' offset ' + OffsetSize +' and OwnerId in ' + JoinSetIds(ownerIds);


Vasani ParthVasani Parth
Its still giving me an error : System.QueryException: unexpected token: and

Error is in expression '{!findTasks}' in component <apex:commandButton> in page final_task_features: Class.PagingTasksController1.queryTasks: line 135, column 1
Class.PagingTasksController1.findTasks: line 81, column 1

Class.PagingTasksController1.queryTasks: line 135, column 1
Class.PagingTasksController1.findTasks: line 81, column 1

I did something like this.


private static string JoinSetIds(Set<Id> objIds)
     {
       if(objIds == null || objIds.size() == 0)
       {
         return '';
       }
      List<string> lIds = new List<string>();
       for(Id pId : objIds)
       {
         lIds.add((string)pId);
       }
       return '(\'' + String.join(lIds, '\',\'' ) + '\')';
    } 

    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\')';
          System.debug(qStr); 
          tasks = Database.query(qStr);         
        } */
       
        //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); 
        // tasks = Database.query(qStr);         

        
       
       String qStr = 'Select OwnerId,Subject,Status,ActivityDate from Task where '+strDate+' limit ' + QueryLimit + ' offset ' + OffsetSize +' and OwnerId in ' + JoinSetIds(ownerIds);  
       System.debug(qStr); 
      tasks = Database.query(qStr);         
    
//        String qStr = 'Select OwnerId,Subject,Status,Priority from Task where Subject like \'%'+searchText+'%\' OR Status like \'%'+searchText+ '%\' Order By ' + sortField;

      

        //tasks.sort();

    }



Denis VakulishinDenis Vakulishin
private static string JoinSetIds(Set<Id> objIds)
     {
       if(objIds == null || objIds.size() == 0)
       {
         return '';
       }
      List<string> lIds = new List<string>();
       for(Id pId : objIds)
       {
         lIds.add((string)pId);
       }
       return '(\'' + String.join(lIds, '\',\'' ) + '\')';
    } 

    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] + ' ' +' and OwnerId in ' + JoinSetIds(ownerIds);
        }else{
       
           strDate  =  'Subject like \'%'+searchText +'%\' OR Status like \'%' +searchText+ '%\' '+' and OwnerId in ' + JoinSetIds(ownerIds) + ' 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\')';
          System.debug(qStr); 
          tasks = Database.query(qStr);         
        } */
       
        //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); 
        // tasks = Database.query(qStr);         

        
       
       String qStr = 'Select OwnerId,Subject,Status,ActivityDate from Task where '+strDate+' limit ' + QueryLimit + ' offset ' + OffsetSize;  
       System.debug(qStr); 
      tasks = Database.query(qStr);         
    
//        String qStr = 'Select OwnerId,Subject,Status,Priority from Task where Subject like \'%'+searchText+'%\' OR Status like \'%'+searchText+ '%\' Order By ' + sortField;

      

        //tasks.sort();

    }

Denis VakulishinDenis Vakulishin
You should follow the order like 
SELECT whar FROM object WHERE condition ORDER BY field LIMIT count OFFSET count
In your last code you put "and OwnerId in (idsGoesHere)" after OFFSET...
Vasani ParthVasani Parth
Its the same error that is firing. When i click on Search button , it simply doesnt work and give the the same error .
Denis VakulishinDenis Vakulishin
1) This should be look like 
if(mydate != null) {
         // strnormal = String.valueOf(mydate );
  String[] qstr3 = String.valueOf(mydate).split(' ',2); 
  strDate = ' ActivityDate =  '+ qstr3[0] + ' ' +' and OwnerId in ' + JoinSetIds(ownerIds);
  }else{

   strDate  =  ' (Subject like \'%'+searchText +'%\' OR Status like \'%' +searchText+ '%\') '+' and OwnerId in ' + JoinSetIds(ownerIds) + ' Order By '  + sortField;
  }
2) Your ownerIds are always empty
Vasani ParthVasani Parth
Found this silly error and trying to resolve , whats happening here while i find everything correct .

System.QueryException: expecting a colon, found 'Order'
Error is in expression '{!findTasks}' in component <apex:commandButton> in page demo: Class.PagingTasksController2.queryTasks: line 140, column 1
Class.PagingTasksController2.findTasks: line 80, column 1
Denis VakulishinDenis Vakulishin
It would be better if you post query string from debug.
Vasani ParthVasani Parth
Here is what is shows in Developer console :
 
22:22:55:223 USER_DEBUG [139]|DEBUG| Select OwnerId,Subject,Status,ActivityDate from Task where  (Subject like '%Pa%' OR Status like '%Pa%')  and OwnerId in  Order By Subject limit 3 offset 0
Denis VakulishinDenis Vakulishin
As I wrote your ownerIds is empty.
Select OwnerId,Subject,Status,ActivityDate from Task where  (Subject like '%Pa%' OR Status like '%Pa%')  and OwnerId in  Order By Subject limit 3 offset 0

Should be something like
Select OwnerId,Subject,Status,ActivityDate from Task where  (Subject like '%Pa%' OR Status like '%Pa%')  and OwnerId in ('id1','id2') Order By Subject limit 3 offset 0



Vasani ParthVasani Parth
What should be tha favourable reason behind this . ?? Could you please help me understand this ? You really a owe a beer from me :) .If i was there , you would have really got it .

But my search is still not working ..
Denis VakulishinDenis Vakulishin
public void queryTasks(){
        
        String qStr2= searchText;
        Set<Id> ownerIds = new Set<Id>();
        String strnormal = '';
        try{
             mydate = date.parse(qStr2);
        }catch(Exception e)
        { }
        
        String strDate = '';
        String ownerIdsCondition = '';
        if(tasks!=null&&tasks.size()>0)
        {
          for(Task t : tasks)
          {
            if(!ownerIds.contains(t.OwnerId))
              ownerIds.add(t.OwnerId);
          }
          ownerIdsCondition = ' OwnerId IN '+JoinSetIds(ownerIds) + ' and ';
        }
        if(mydate != null) {
         // strnormal = String.valueOf(mydate );
          String[] qstr3 = String.valueOf(mydate).split(' ',2); 
          strDate = ownerIdsCondition+' ActivityDate =  '+ qstr3[0] + ' ';
        }else{
       
           strDate  =  ownerIdsCondition+'(Subject like \'%'+searchText +'%\' OR Status like \'%' +searchText+ '%\') ' + ' Order By '  + sortField;
        }
           

        
       
       String qStr = 'Select OwnerId,Subject,Status,ActivityDate from Task where '+strDate+' limit ' + QueryLimit + ' offset ' + OffsetSize;  
       System.debug(qStr); 
      tasks = Database.query(qStr);         
    
}
But I really don't understand from what objects you want to collect ownerIds. I get them form "tasks" collection. if it's NULL or empty so there will be NO filtering by OwnerId.
This sample shoudn't result an error.
Vasani ParthVasani Parth
The Error has gone and the value also shows up in the Debug. Yes, i'm getting from Task object..It is presently not searching by OwnerId . I have a User called "Nisarg " and when i search it  doesnt display me anything.

  Here it is .
Select OwnerId,Subject,Status,ActivityDate from Task where (Subject like '%Nisarg%' OR Status like '%Nisarg%')  Order By Subject limit 3 offset 0

But as you said if its NULL, it will be empty. When can this condition happen ?
Denis VakulishinDenis Vakulishin
Your constructor is created like Controller Extension. But on page you use it like custom controller.
So logic will not reach your ctor logic(where you assign Tasks for the first time).

Check this artincles:
http://www.salesforce.com/us/developer/docs/pages/Content/pages_controller_custom.htm
http://www.salesforce.com/us/developer/docs/pages/Content/pages_controller_extension.htm
Vasani ParthVasani Parth
Thanks Danis for the information . I did check it  but i guess my code should run right with any alterations in query ?

What should be the workaround to get to this  ?
Denis VakulishinDenis Vakulishin
Could you tell me more about how you use this page ?