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
Vincent van Drunen LittelVincent van Drunen Littel 

Why is my "add Target" button not working?

Hi all, 

I'm completely lost on why the "add Target" button within my VisualForce page is not working.
Error Code after clicking "add Target" 
Invalid id: [object Object]
Error is in expression '{!addTargets}' in component <apex:commandButton> in page custompaginationvf: External entry point

If anyone would have any idea please help me!
ApexClass

public with sharing class CustomPaginationController 
{

    public Contact acc {get;set;}   
    public ApexPages.StandardSetController con{get; set;} 
    public string selectedlstAccounts {get; set;} 
    Map<Id, Contact> contactMap {get; set;}
    String parentAccountId;
    String parentContactId;

    public CustomPaginationController ()
    {
       acc = new Contact();
       lstAccount = new List<Contact>();
       selectedlstAccounts='';
       contactMap = new Map<Id, Contact>([select Id, Name from Contact]);
       parentContactId = ApexPages.currentPage().getParameters().get('conId');

    }
    public List<Contact> lstAccount 
    {  
        get  
        {  
            if(con != null)  
                return (List<Contact>)con.getRecords();  
            else  
                return null ;  
        }  
        set;
    }  
    
    
    //added by me to test
     public PageReference addTargets() {
     
     system.debug('jjjjj');
     
        List<String> lstAccountsIds = selectedlstAccounts.split(',');
        List<Target__c> Target = new List<Target__c>();
        system.debug('oooo');
        
        for (string s : lstAccountsIds )
        {
            system.debug('yyyyyyy22222222222222');
            system.debug('parentContactId: ' + parentContactId );
            system.debug('contactMap.get(s).Name: ' + contactMap.get(s).Name );
            Target__c newtarget = new Target__c (Target__c = Id.valueOf(parentContactId), Name = contactMap.get(s).Name);
            system.debug('yyyyyyy333333333333333333');
            Target.add(newtarget);
        }
        system.debug('yyyyyyy');
        if (Target.size() > 0)
        {
            system.debug('ppppppp');
            insert Target;
        }
        string strPageRef = '"javascript:window.close();"';
        return new PageReference(strPageRef);
    }   
    
    
    public PageReference Search()
    {
        String query= '';
        String strFilter = '';
        if(acc.Name != null && (acc.Name ).trim() !='')
        {
           strFilter  = strFilter  +  ' where Name Like \''+acc.Name+'%\'' ;
        }
        if(acc.Account.Name != null && (acc.Account.Name).trim() !='' )
        {
            strFilter  = strFilter  +  ' where Name Like \''+acc.Account.Name+'%\'' ;
           
        }
        if(strFilter != '')
        {
            query = 'Select name ,id, Account.Name, Cargo__c from Contact '+strFilter+ ' limit 1000';
            System.debug('Query ---->'+ query );
            con = new ApexPages.StandardSetController(Database.getQueryLocator(query)); 
            con.setPageSize(10);
        }
        else
        {
        }
       return null;
    }
    public Boolean hasNext  
    {  
        get  
        {  
            return con.getHasNext();  
        }  
        set;   
    }  
    
    public Boolean hasPrevious  
    {  
        get  
        {  
            return con.getHasPrevious();  
        }  
        set;  
    }  

    public Integer pageNumber  
    {  
        get  
        {  
            return con.getPageNumber();  
        }  
        set;  
    }  

    public void previous()  
    {  
        con.previous();  
    }  

    public void next()  
    {  
        con.next();  
    }  
 
 
}

VFpage

<apex:page controller="CustomPaginationController" sidebar="false">

 <apex:form >
    
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
   
        
        <apex:pageBlock >
            <apex:pageMessages ></apex:pageMessages>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!Search}" value="Search" />
            </apex:pageBlockButtons>
            
            <apex:pageblockSection >
                <apex:inputText value="{!acc.Name}" label="Name"/> 
                
            </apex:pageblockSection>
        </apex:pageBlock>
        
        <apex:pageBlock id="resultId" rendered="{!if(lstAccount != null && lstAccount.size > 0, true,false )}">
            <apex:pageBlockButtons >
                <div style="text-align:right"> 
                  Total Records Found: {!Con.resultSize}  
                  <apex:image url="/img/search_prevarrow_disabled.gif" styleClass="prevArrow" rendered="{!NOT(Con.HasPrevious)}"/>  
                  <apex:image url="/img/search_prevarrow.gif" title="Previous Page" styleClass="prevArrow" rendered="{!Con.HasPrevious}"/>  
                  <apex:commandLink action="{!Previous}" title="Previous Page" value="Previous Page" rendered="{!Con.HasPrevious}"/>  
                  <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasPrevious)}">Previous Page</apex:outputPanel>           
                  <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(Con.HasNext)}">Next Page</apex:outputPanel>           
                  <apex:commandLink title="Next Page" value="Next Page" rendered="{!Con.HasNext}" action="{!Next}"/>&nbsp;  
                  <apex:image url="/img/search_nextarrow.gif" title="Next Page" styleClass="nextArrow" rendered="{!Con.HasNext}"/>  
                  <apex:image url="/img/search_nextarrow_disabled.gif" rendered="{!NOT(Con.HasNext)}"/> 
                  <img src="/s.gif" title="Last Page" alt="Last Page" class="last"/>         
                
                </div>
                
                <apex:commandButton value="Add Target" action="{!addTargets}"/>
                
            </apex:pageBlockButtons>  
                          
            <apex:inputHidden value="{!selectedlstAccounts}" id="lstAccounts"/>
            <apex:pageBlockSection columns="1">
                <apex:pageBlockTable value="{!lstAccount}" var="contato" >
                <apex:column headerValue="Select" width="100px;"><apex:inputCheckbox onclick="Select1stAccounts(this, '{!contato.Id}');"/></apex:column>
                <apex:column value="{!contato.Name}"/>
                <apex:column value="{!contato.Account.Name}"/>
                <apex:column value="{!contato.Cargo__c}"/>
            </apex:PageblockTable>
            </apex:pageBlockSection>
            
        </apex:pageBlock>
        
        
<script type="text/javascript">
    $ = jQuery.noConflict();
    function Select1stAccounts(chk, lstAccounts)
        {
            //alert( '1' );
            //alert( lstAccounts[1] );
            var lstAccounts = $('input[id$="lstAccounts"]');
            var selectedlstAccounts = lstAccounts.val();
            
            if (chk.checked == true)
            {
                //alert( '2A' );
                if (selectedlstAccounts == '')
                {
                    //alert( '2A1' );
                    selectedlstAccounts = lstAccounts;
                } 
                else
                {
                    //alert( '2A2' );
                    selectedlstAccounts = selectedlstAccounts + ',' + lstAccounts;
                }
            }
            else 
            {
                //alert( '2B' );
                var accountIndex = selectedlstAccounts.indexOf(lstAccounts);
                var accountToRemove = '';

                if (selectedlstAccounts.length == lstAccounts.length) {
                    accountToRemove = lstAccounts;
                }
                else {
                    if (accountIndex == 0){
                        accountToRemove = lstAccounts+ ',';
                    }
                    else{
                        accountToRemove = ',' + lstAccounts;
                    }
                }
            
                selectedlstAccounts = selectedlstAccounts.replace(accountToRemove, '');
            }
            //alert( 'B' );
            lstAccounts.val(selectedlstAccounts);
            //alert (lstAccounts.val());
    }
</script>        
        
        
    </apex:form>
    

       
</apex:page>

Apex trigger

trigger TargetsContacts on Contact (after insert, after update) {
    List<Contact> contacts = [select Id, Name, AccountId, Account.Name from Contact Where Id in :Trigger.new];
    List<Target__c> targetList = new List<Target__c>();
    for(Contact con : contacts){
            Target__c target = new Target__c();
            target.Target_del__c = con.AccountId; 
            target.Name = con.Name;
            target.Target__c = con.Id;
            targetList.add(target);
    }
    if(!targetList.IsEmpty()){
        try{
            insert targetList;
        } catch(DMLException e){
            system.debug('Following Exceptions occurred'+e.getmessage());
        }
    }
}
Button on related list
window.mypopup = window.open('/apex/CustomPaginationVF?contId={!Target__c.Target__c}','mypopup','top=150,left=200,location=1,status=1,scrollbars=1, width=1000,height=600'); 
window.onfocus = function() { 
if (window.mypopup.closed) { 
window.location.reload(); 
} 
};


 

Best Answer chosen by Vincent van Drunen Littel
Amit Chaudhary 8Amit Chaudhary 8
Please try below code:-
public class TargetControllerNew
{
     public Account acc {get;set;}
     public String strName {get;set;}
     public List<wrapContact> wrapContactList {get; set;}    
     public TargetControllerNew() // CHANGE THIS (SelectConcorrenteController TO ConcorrenteController)
    {
  wrapContactList = new List<wrapContact>();
  
        String parentAccountId = ApexPages.currentPage().getParameters().get('accId');
  
  if(parentAccountId != null)
  {
   acc = [select Id, Name from Account where id = :parentAccountId ];
        }
    }
    public PageReference addTarget() 
 {
        List<Target__c> Targets= new List<Target__c>();
        
        for (wrapContact selCont : wrapContactList)
        {
   if(selCont.selected == true)
   {
    Target__c Target= new Target__c(Target__c= selCont.cont.id, Name = selCont.cont.Name , Target_del__c = acc.id); 
    Targets.add(target);
   } 
        }
        if (Targets.size() > 0)
        {
            insert Targets;
        }
        string strPageRef = '"javascript:window.close();"';
        return new PageReference(strPageRef);
    }

 public PageReference Search()
    {
        String query= '';
        String strFilter = '';
        if(strName != null && (strName).trim() !='' )
        {
            query= ' Select name ,id, Account.Name, Cargo__c from Contact where Name Like \''+strName+'%\'' ;
        }
        else
        {
            query = 'Select name ,id, Account.Name, Cargo__c from Contact limit 1000';
        }
    System.debug('Query ---->'+ query );

  System.debug('strName---->'+ strName);
  List<Contact> lstContct =  Database.query(query) ; 
  for(Contact cont : lstContct)
  {
   wrapContactList.add(new wrapContact(cont));
  }
  
  return null;
    }
   
 public class wrapContact 
 {
        public Contact cont {get; set;}
        public Boolean selected {get; set;}
 
        public wrapContact(Contact c) 
  {
            cont = c;
            selected = false;
        }
    }   
}

try below page
<apex:page controller="TargetControllerNew" sidebar="false">

    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    
    <apex:form >
        <apex:pageBlock >
            <apex:pageMessages ></apex:pageMessages>

            <apex:pageBlockButtons >
                <apex:commandButton action="{!Search}" value="Search" />
            </apex:pageBlockButtons>
            
            <apex:pageblockSection >
                <apex:inputText value="{!strName}" label="Company"/> 
            </apex:pageblockSection>
        </apex:pageBlock>
        
        <apex:pageBlock id="resultId" rendered="{!if(wrapContactList != null && wrapContactList.size > 0, true,false )}">
        
                <apex:pageBlockTable value="{!wrapContactList}" var="contWrap" id="table" title="All Contacts">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!contWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!contWrap.cont.name}" />
                    <apex:column value="{!contWrap.cont.Account.Name}" />
                    <apex:column value="{!contWrap.cont.Cargo__c}" />
                </apex:pageBlockTable>
                
                <apex:commandButton value="Add Target" action="{!addTarget}"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>


 

All Answers

Himanshu ParasharHimanshu Parashar

Hi Vincent,

It seems like that error is in line 57 where you are assigning string to PageRef.

 string strPageRef = '"javascript:window.close();"';

As far as I know you can't do that, PageReference class constructor takes URL as parameter instead of string and that is why SFDC is not recognizing that one and throwing external entry point error. 

Try to comment that out and return null from there. It should work.


Here is the Document link for your ref.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_system_pagereference.htm


Thanks,
Himanshu

Salesforce Certified Developer, Administrator, Service Cloud Consultant
P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Vincent van Drunen LittelVincent van Drunen Littel
Hi Himanshu,

I have this page reference in use in a different code (without the pagereference search) and works perfectly fine, this is one of the reasons i'm kinda baffled about why it is not working in this code.. 

If you want i can share the working code with you (my aim is to have my working code in use with a searchbox) 
Himanshu ParasharHimanshu Parashar
Hi Vincent,

Can you please post the working code.
Vincent van Drunen LittelVincent van Drunen Littel
Hi Himanshu,

Hereby the working code,( VFpage with out searchbox)
 
<apex:page controller="ContactsController" sidebar="false" showHeader="false">
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
<script type="text/javascript">
    $ = jQuery.noConflict();
    function SelectContacts(chk, contactId)
        {
            var contactIds = $('input[id$="contactIds"]');
            var selectedContacts = contactIds.val();
            
            if (chk.checked == true)
            {
                //alert( '2A' );
                if (selectedContacts == '')
                {
                    //alert( '2A1' );
                    selectedContacts = contactId;
                } 
                else
                {
                    //alert( '2A2' );
                    selectedContacts = selectedContacts + ',' + contactId;
                }
            }
            else 
            {
                //alert( '2B' );
                var contactIndex = selectedContacts.indexOf(contactId);
                var contactToRemove = '';

                if (selectedContacts.length == contactId.length) {
                    contactToRemove = contactId;
                }
                else {
                    if (contactIndex == 0){
                        contactToRemove = contactId+ ',';
                    }
                    else{
                        contactToRemove = ',' + contactId;
                    }
                }
            
                selectedContacts = selectedContacts.replace(contactToRemove, '');
            }
            //alert( 'B' );
        	contactIds.val(selectedContacts);
            //alert (contactIds.val());
    }
</script>
    <apex:form >
        <apex:inputHidden value="{!selectedContactIds}" id="contactIds"/>
        <apex:pageBlock title="Select Targets">
            <apex:pageBlockTable value="{!contacts}" var="con">
                <apex:column headerValue="Select" width="100px;">
                    <apex:inputCheckbox onclick="javascript:SelectContacts(this, '{!con.Id}');"/>
                </apex:column>
                <apex:column headerValue="AccountName" value="{!con.Account.Name}"/>
                <apex:column headerValue="Contact Name" value="{!con.Name}"/>
                <apex:column headerValue="Cargo" value="{!con.Cargo__c}"/>
            </apex:pageBlockTable>
            <apex:commandButton value="Add Target" action="{!addTarget}"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>
 
public class ContactsController 
{

    public List<Contact> contacts {get; set;}
    Map<Id, Contact> contactMap {get; set;}
    public string selectedContactIds {get; set;}
    string parentContactId;
    
    public ContactsController() // CHANGE THIS (SelectConcorrenteController TO ConcorrenteController)
    {
        //system.debug('xxxxxx');
        parentContactId = ApexPages.currentPage().getParameters().get('conId');
        //system.debug('aaaaaaa');
        contactMap = new Map<Id, Contact>([select Id, Name, Cargo__c, Account.Name from Contact Order by Account.Name]);
         system.debug('bbbbbb');
        contacts = contactmap.Values();
        // system.debug('cccccc');
    }
    
    public PageReference addTarget() {
        //system.debug('sssssssss');
        List<string> contactIds = selectedContactIds.split(',');
        List<Target__c> Target = new List<Target__c>();
        //system.debug('rrrrrrr');
        for (string s : contactIds )
        {
      //system.debug('parentContactId: ' + parentContactId);
            //system.debug('s: ' + s);
            //system.debug('Name: ' + contactMap.get(s).Name);
            Target__c newtarget = new Target__c (Target__c = parentContactId, Name = contactMap.get(s).Name); 
            Target.add(newtarget);
        }
        //system.debug('yyyyyyy');
        if (Target.size() > 0)
        {
            //system.debug('ppppppp');
            insert Target;
        }
        string strPageRef = '"javascript:window.close();"';
        return new PageReference(strPageRef);
    }



 
Amit Chaudhary 8Amit Chaudhary 8
Please try below code:-
public class TargetControllerNew
{
     public Account acc {get;set;}
     public String strName {get;set;}
     public List<wrapContact> wrapContactList {get; set;}    
     public TargetControllerNew() // CHANGE THIS (SelectConcorrenteController TO ConcorrenteController)
    {
  wrapContactList = new List<wrapContact>();
  
        String parentAccountId = ApexPages.currentPage().getParameters().get('accId');
  
  if(parentAccountId != null)
  {
   acc = [select Id, Name from Account where id = :parentAccountId ];
        }
    }
    public PageReference addTarget() 
 {
        List<Target__c> Targets= new List<Target__c>();
        
        for (wrapContact selCont : wrapContactList)
        {
   if(selCont.selected == true)
   {
    Target__c Target= new Target__c(Target__c= selCont.cont.id, Name = selCont.cont.Name , Target_del__c = acc.id); 
    Targets.add(target);
   } 
        }
        if (Targets.size() > 0)
        {
            insert Targets;
        }
        string strPageRef = '"javascript:window.close();"';
        return new PageReference(strPageRef);
    }

 public PageReference Search()
    {
        String query= '';
        String strFilter = '';
        if(strName != null && (strName).trim() !='' )
        {
            query= ' Select name ,id, Account.Name, Cargo__c from Contact where Name Like \''+strName+'%\'' ;
        }
        else
        {
            query = 'Select name ,id, Account.Name, Cargo__c from Contact limit 1000';
        }
    System.debug('Query ---->'+ query );

  System.debug('strName---->'+ strName);
  List<Contact> lstContct =  Database.query(query) ; 
  for(Contact cont : lstContct)
  {
   wrapContactList.add(new wrapContact(cont));
  }
  
  return null;
    }
   
 public class wrapContact 
 {
        public Contact cont {get; set;}
        public Boolean selected {get; set;}
 
        public wrapContact(Contact c) 
  {
            cont = c;
            selected = false;
        }
    }   
}

try below page
<apex:page controller="TargetControllerNew" sidebar="false">

    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    
    <apex:form >
        <apex:pageBlock >
            <apex:pageMessages ></apex:pageMessages>

            <apex:pageBlockButtons >
                <apex:commandButton action="{!Search}" value="Search" />
            </apex:pageBlockButtons>
            
            <apex:pageblockSection >
                <apex:inputText value="{!strName}" label="Company"/> 
            </apex:pageblockSection>
        </apex:pageBlock>
        
        <apex:pageBlock id="resultId" rendered="{!if(wrapContactList != null && wrapContactList.size > 0, true,false )}">
        
                <apex:pageBlockTable value="{!wrapContactList}" var="contWrap" id="table" title="All Contacts">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!contWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!contWrap.cont.name}" />
                    <apex:column value="{!contWrap.cont.Account.Name}" />
                    <apex:column value="{!contWrap.cont.Cargo__c}" />
                </apex:pageBlockTable>
                
                <apex:commandButton value="Add Target" action="{!addTarget}"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>


 
This was selected as the best answer