• ajaybharath
  • NEWBIE
  • 25 Points
  • Member since 2012

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 16
    Replies
I have an issue. My requirement is this, I have a VF page which opens from a custom button located on a Case Detail page. 
The VF Page has a CommandLink and a CommandButton which performs certain update to the Case Owner field on the Case detail page. 
The VF Page is opened as a Sub tab to a Case Primary tab on the console. 

After updating the changes to the owner field on the case detail, I have to refresh my Primary Tab(Case Detail) and along with that i have to close the Sub tab which contains the VF Page.
I find a weird issue here, 
My sub tab is getting closed first and the Primary tab refreshes after sub tab is closed. So what happens now is wierd for me, When the refresh of the primary tab happens it opens the closed VF Page again(that is the sub tab is reopened).
I want to close the sub tab after the save has happened on the primary tab and refresh success. 

Here is my code, 

MY VF PAGE: 
<apex:page standardController="Case" extensions="CIAssignProjectController" name="Assign Project">
    <apex:includeScript value="/support/console/34.0/integration.js"/>

    <script type="text/javascript">

        function setBeforeUnloadEvent(flag) {
            console.log('getting primary tab id');
            sforce.console.getEnclosingPrimaryTabId(getPrimaryTabId);
            console.log('getting current subtab id');
            sforce.console.getEnclosingTabId(getSubtabId);
            if(flag){
                //First find the ID of the current tab to close it
                console.log('refreshing');
                refreshTabsAfterSave();
                //setTimeout(function(){doCloseTab();},5000)
            }
        }
        
        function refreshTabsAfterSave () {
            console.log('getting link');
            sforce.console.getTabLink(sforce.console.TabLink.PARENT_AND_CHILDREN, currentPrimaryTabId, refreshPrimaryTab);
        }

        var refreshPrimaryTab = function refreshPrimaryTab (res) {
            console.log('tab link is: ', res);
            sforce.console.openConsoleUrl(currentPrimaryTabId, res.tabLink, true, [], [], afterRefresh);
        }

        var currentSubTabId; // set on page load
        var currentPrimaryTabId; // set on page load

        var getPrimaryTabId = function getPrimaryTabId (result) {
            console.log('primary tab id is: ', result.id);
            currentPrimaryTabId = result.id;
        }

        var getSubtabId = function getSubtabId (result) {
            console.log('sub tab id is: ', result.id);
            currentSubTabId = result.id;
        }

    var afterRefresh = function afterRefresh (res) {
            console.log('after refresh, get enclosing tab');
            sforce.console.getEnclosingTabId(getEnclosingTab);
        }
        
        var getEnclosingTab = function getEnclosingTab (res) {
            console.log('enclosing tab is: ', res.id);
            sforce.console.closeTab(res.id);
        }

        function doCloseTab() {
            sforce.console.getEnclosingTabId(closeSubtab);
        }      
        var closeSubtab = function closeSubtab(result) {
            var tabId = result.id;
            sforce.console.closeTab(tabId);
        };
        
    </script>

    <apex:form >
        <apex:pageMessages />
        <apex:pageBlock title="Work Assignment">
            <apex:pageBlockSection Title="User Data" columns="1" >
                <apex:pageBlockTable id="UserSkillsTable" value="{!MatchingUserSkills}" var="ms" rendered="{!IF(AND(NOT(ISBLANK(MatchingUserSkillsdata)),MatchingUserSkillsdata.size > 0), true, false)}" >
            <!-- A number of columns goes here -->

                    <apex:column style="width:7%">
                        <apex:facet name="header">Assign Project</apex:facet>

            <!-- This is where i Update the Owner of the Case field -->

                        <apex:commandLink status="loadingStatus" immediate="true" action="{!Assignrecord}" oncomplete="setBeforeUnloadEvent('{!pageswitch}');" value="Assign"> 
                            <apex:param name="Assignrowid" value="{!ms.MatchingUserId}"/> 
                         </apex:commandLink>
                    </apex:column>

                </apex:pageBlockTable>
            </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton status="loadingStatus" action="{!AutoAssignrecord}" value="Auto Assignment" oncomplete="setBeforeUnloadEvent('{!pageswitch}');" /> 
                <apex:commandButton status="loadingStatus" onclick="doCloseTab();" value="Back" />
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form> 

</apex:page>
My Class: (Only Button Logic I have added)
public class CIAssignProjectController {

    Public Boolean pageswitch {get;set;}
    private Case cs {get;set;}
    Private case c1;

    public CIAssignProjectController (ApexPages.StandardController controller) {
        cs =(Case) controller.getRecord();
        pageswitch = false;
        }

    // No Problem with this code, As this is getting the Owner Field updated perfectly
    public pagereference Assignrecord(){ 

        if(cu.Profile.Name == 'CI User'){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,system.label.Projectusererrormessage));
            return null;
        }
        else{
            System.debug('//////////'+lstTask);
        // Some Codes for Update runs here , No errors on this found

            try{
                update c1;
                pageswitch = true;
                if(lstTask.size()>0){
                    update lstTask; 
                }
                
                //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm,system.label.CI_Assign_Project));
                //PageReference updatepageRef = new PageReference('/' + cs.id);
                //updatepageRef.setRedirect(true);
                //return updatepageRef; 

                return null; // I return Null because, If i call PageReference it opens the case detail in the Same Sub tab.
            }
            catch(DmlException ex){
                ApexPages.addMessages(ex);
                return null;        
            }          
        }
    }

}
MY Button Code : 
(Execute javaScript)
{!REQUIRESCRIPT("/soap/ajax/31.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")} 
{!REQUIRESCRIPT("/support/console/27.0/integration.js")} 
var caseId = '{!Case.Id}'; 

var s = caseId.toString(); 
var returnMessage = sforce.apex.execute("AssignProject","checkSLABreach",{recid:s}); 
if(returnMessage!='') 
{ 
alert(returnMessage); 
} 
else 
{ 

if (sforce.console.isInConsole()) { 
sforce.console.getEnclosingPrimaryTabId(function(result){ 
sforce.console.openSubtab(result.id, '/apex/CIAssignProject?id=' + caseId, true, 'Assign Project: {!Case.CaseNumber}', null); 
}); 
} 
else { 
window.open('/apex/CIAssignProject?id=' +caseId); 
} 
}

The main problem that i guess is because the afterRefresh callback function on OpenConsoleURL is called first and then the refresh happens. 
I tried to give setTimeOut(function(){afterRefresh},5000); on openConsoleUrl, But it is not working for me. 

Hi
I would like to use split on a string of Array . for example , i have arrMonth[] array with strings , 'Jan','Feb','Mar' ... 'Dec'.
I wish to split arrMonth[] into 2 sub arrays by means of index position .. when i try using Splice/slice method in salesforce its throwing an error stating
"Method does not exist or incorrect signature: [LIST<String>].splice(Integer, Integer)"


Looking for Split function on string of array or any other alternative way to achieve this w/o manual declaration of 2 sub arrays
Any pointers would be great

thanks in advance
Ajay

Hi

 

I'm trying to query for month value from a date field f my custom object
like say ,
SELECT Id,Date__c from custom_obj__c where . . . . .
using date__c.getMonth() or MONTH(date__c). i get an error that "Invalid aggregate Function"

I dont want to create a formula field and query based on it . Is ter any possibility without creating formula field for date .
Thanks in advance

ajay

Hi

 

I need to auto-populate the account lookup for a new Contact by using custom button.

When i click on the standard Button New Contact , the retUrl and accId denotes the Id's of the account for which a new contact is created , somthing like this .. https://ap1.salesforce.com/003/e?retURL=%2F0019000000FecuW&accid=0019000000FecuW

I dont wanna hard code it so ,
I create a new custom button say New My Contact .. as a list button and content source as URL ..
I gave something like this ,
/003/e?retURL=/{! Account.Id }& accid={!Account.Id}
but its returning null for account Id ..

Please Help


Thanks
Aj

Hi

 

I'm trying to develop a Bar Chart on google chart using simple encoding format .. 
I have tried this to my URL attribute in <apex:image>

 

<apex:pageBlock >
        <apex:image title="Transfer Details" alt="Salary for Employees" url="http://chart.apis.google.com/chart?cht=bvg&chd=s:simpleEncode(Array(20000,30000,40000,50000,60000),70000),simpleEncode(Array(3,4,5,6,7),10)&chxt=x,x,y,y,r,r&chxr=4,0,10,2&chxl=0:|{!name}|1:|Transferee+Name|3:|Salary|5:|Job+Level&chf=b0,lg,0,FFE7C6,0,76A4FB,1|bg,s,000000&chs=800x300&chbh=15,5,15" />
</apex:pageBlock>

I have defined the essential Javascript function for simpleEncode as given in google chart parameters

     <script type="text/javascript">
     var simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
     // This function scales the submitted values so that
     // maxVal becomes the highest value.
     
     function simpleEncode(valueArray,maxValue) {
         var chartData = ['s:'];
         for (var i = 0; i < valueArray.length; i++) {
             var currentValue = valueArray[i];
             if (!isNaN(currentValue) && currentValue >= 0) {
                 chartData.push(simpleEncoding.charAt(Math.round((simpleEncoding.length-1) *currentValue / maxValue)));
             }
             else {
                 chartData.push('_');
             }
         }
         return chartData.join('');
     }
     </script>

I have added this function directly into chd:s element 

 

var valueArray = new Array(0,1,4,4,6,11,14,17,23,28,33,36,43,59,65);
var maxValue = 70;
simpleEncode(valueArray, maxValue);

 

 

P.S please ignore the chxl part

 

I'm new to this and i have no idea about this

Any help would be appreciated

 

Thanks in Advance
Ajay

Hi All

 

My requirement is to generate a console view for 3 objects .. i hv a custom object Order__c and account and contact object .. i have lookup for account and contact in order obj .. now everything is working fine .. rendering elements shud be in the form of a console layout with Account Detail and Contact Detail in the Right pane ..

Now what i get is just as a pageblock such that both Account and Contact is rendered one below the other .. i don know how to get it done ..
Someone please help me out

Class

public class ConsoleCustomOrder { 
    
    //public List<Order__c> allOrd {get;set;}
    public List<Account> showAcct;
    public List<Order__c> showOrder;
    public List<Contact> showCont;
    //public Id chosenOrderId {get;set;}

    public List<Order__c> getAllOrders() {
        List<Order__c> allOrd = [select Id,Name,Accounts_to_look_for__c,Contacts_to_look_for__c from Order__c LIMIT 10];
        return allOrd;
    }
    public void ShowOrderDetail() {
        String ordId = System.currentPagereference().getParameters().get('abc');
        Order__c order = [select Id,Name,Accounts_to_look_for__c,Contacts_to_look_for__c from Order__c where Id =:ordId];
        showOrder = new List<Order__c>();
        showOrder.add(order);

        Id accId = order.Accounts_to_look_for__c;
        showAcct = new List<Account>();
        Account ac = [select Id,Name from Account where Id =: accId];
        showAcct.add(ac);
        
        Id contId = order.Contacts_to_look_for__c;
        showCont = new List<Contact>();
        Contact c = [select Id,Name from Contact where Id =: contId];
        showCont.add(c);
        
    }
    public List<Order__c> getOrderDetail() {
        return showOrder;
    }

    /*public list<SelectOption> getOrderItems() {
        list<SelectOption> opt=new list<SelectOption>();
        for(integer i=0;i<allOrd.size();i++) 
            opt.add(new SelectOption(allOrd[i].id,allOrd[i].Name));
            
        return opt;
    }*/

    public List<Account> getAccDetail() {
        return showAcct;
    }

    Public List<Contact> getContDetail() {
        return showCont;
    }

}

 Vf Page :

 

<apex:page controller="ConsoleCustomOrder" sidebar="false" showHeader="false">
    <apex:form >
        <apex:pageBlock id="mainpb" title="Pick an Order to Display">
            <apex:pageBlockSection >
            <apex:pageblocktable id="mainpbt" value="{!AllOrders}" var="ord">
               
               <apex:column headervalue="Select An Order Item" width="2">                    
                  <apex:actionsupport action="{!ShowOrderDetail}" event="onclick" rerender="orderpb,ordertable,mainpb,mainpbt,accpb,acctable,conpb,contable">  
                   <input type="radio" />                    
                    <apex:param name="abc" value="{!ord.Id}">
                    </apex:param>
                  </apex:actionsupport>
               </apex:column>

               <apex:column headervalue="First Name">
                  <apex:outputfield value="{!ord.Name}">
                  </apex:outputfield>
               </apex:column>  
                    
            </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>

        <apex:pageblock id="orderpb">
            <apex:pageblocktable id="ordertable" value="{!OrderDetail}" var="selord">                       
                <apex:column headerValue="ord det"> 
                   <apex:detail subject="{!selord.Id}" relatedList="false" title="false" inlineEdit="true" />
                </apex:column>
            </apex:pageblocktable>
        </apex:pageblock>

        <apex:pageblock id="accpb">
            <apex:pageblocktable id="acctable" value="{!AccDetail}" var="selacc">                       
               <apex:column headerValue="acc det"> 
                   <apex:detail subject="{!selacc.Id}" relatedList="false" title="false" inlineEdit="true" /> 
               </apex:column>
            </apex:pageblocktable>
        </apex:pageblock>

        <apex:pageblock id="conpb">
            <apex:pageblocktable id="contable" value="{!ContDetail}" var="selcon">                       
               <apex:column headerValue="cont det"> 
                   <apex:detail subject="{!selcon.Id}" relatedList="false" title="false" inlineEdit="true" /> 
               </apex:column>
            </apex:pageblocktable>
        </apex:pageblock>

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

 

Thanks in Advance

 

 

Hi All
i'm new to salesforce . I have been asked to display the records of the Account Object as multiple tabs along with their related lists in a VF layout .

Can anyone please help me out with the code

 

Thanks in Advance

Hi
I'm new to salesforce .. i have been asked to do a dynamic search on the records for the custom object  .. say ratings .. i have 3 fields in it and i have implemented the dynamic search . its working fine .. now i need to add a checkbox for the search results , but its throwing an error ..

P.S leave the standard set controller part of my code .. its working fine too

 

Thanks in advance

my vf page:

 

<apex:page controller="Search" sidebar="false">
  <apex:form >
  <apex:pageMessages id="errors" />
  <apex:pageBlock title="Ratings Search" mode="edit">
  <apex:pageBlockButtons >
        <apex:commandButton action="{!process}" value="Add to Cart"/>
        <apex:commandButton action="{!cancel}" value="Cancel"/>
  </apex:pageBlockButtons>
  <table width="100%" border="0">
  <tr>  
  <td width="200" valign="top">
      <apex:pageBlock title="" mode="edit" id="criteria">
  
      <script type="text/javascript">
      function doSearch() {
        searchServer(
         document.getElementById("name").value,
         document.getElementById("phone").value,
         document.getElementById("status").options[document.getElementById("status").selectedIndex].value
          );
      }
      </script> 
 
      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="name" value="" />
          <apex:param name="phone" value="" />
          <apex:param name="status" value="" />
      </apex:actionFunction>
 
      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">Rating Member Name<br/>
        <input type="text" id="name" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Customer's Phone Number<br/>
        <input type="text" id="phone" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Rating Status<br/>
          <select id="status" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!statuses}" var="stat">
              <option value="{!stat}">{!stat}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>
      </apex:pageBlock>
    </td>
  
    <td valign="top">
    <apex:pageBlock mode="edit" id="results">
        <apex:pageBlockTable value="{!rate}" var="sqrs">
        <apex:column width="25px">
            <apex:inputcheckbox /></apex:column>
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Rating Member Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
       <apex:outputLink value="/{!sqrs.id}">
       <apex:outputField value="{!sqrs.name}"/></apex:outputlink>
            </apex:column>
             
             
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Phone" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Customer_s_Phone_No__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!sqrs.Customer_s_Phone_No__c}"/>
            </apex:column><apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="statuses" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Rating_Status__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!sqrs.Rating_Status__c}"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
  </td>
  </tr>
  </table>
    <apex:pageBlockSection title="Rating Results" columns="1">
                <apex:pageBlockTable value="{!categories}" var="c">
                     <apex:column width="25px">
                          <apex:inputCheckbox value="{!c.checked}"/>
                     </apex:column>
                     <apex:column value="{!c.cat.Name}" headerValue="Name"/>
                     <apex:column value="{!c.cat.Customer_s_Phone_No__c}" headerValue="Phone Number"/>
                     <apex:column value="{!c.cat.Rating_Status__c}" headerValue="Status"/>
                </apex:pageBlockTable>
        </apex:pageBlockSection>

  </apex:pageBlock>
    <apex:panelGrid columns="4">
    <apex:commandLink action="{!first}">First</apex:commandlink>
    <apex:commandLink action="{!previous}" rendered="{!hasPrevious}">Previous</apex:commandlink>
    <apex:commandLink action="{!next}" rendered="{!hasNext}">Next</apex:commandlink>
    <apex:commandLink action="{!last}">Last</apex:commandlink>
    </apex:panelGrid>
  </apex:form>
</apex:page>

 

search class :

public with sharing class Search {
 
  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Rating__c> rate {get;set;}
  public List<categoryWrap> selected {
    get{
    if (selected == null) 
    selected = new List<categoryWrap>();
    return selected;
    }
    set;
  }
  List<categoryWrapper> categories {get;set;}
 
  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }
 
  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'name'; } return sortField;  }
    set;
  }
 
  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }
 
  // init the controller and display some sample data when the page loads
  public Search() {
    soql = 'select id,Name,Comments__c,Customer_s_Phone_No__c,Rating_Status__c FROM Rating__c where Name != null';
    runQuery();
  }
 
  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }
 
  // runs the actual query
  public void runQuery() {
 
    try {
      rate = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }
 
  }
  public ApexPages.StandardSetController con {
        get {
            if(con == null) {
                con = new ApexPages.StandardSetController(rate);
                con.setPageSize(5);
            }
            return con;
        }
        set;
  }
  public List<categoryWrap> getCategories() {
        categories = new List<categoryWrap>();
        for (Rating__c category : (List<Rating__c>)con.getRecords())
            categories.add(new CategoryWrapper(category));
 
        return categories;
  }
 
  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {
 
    String name = Apexpages.currentPage().getParameters().get('name');
    //String lastName = Apexpages.currentPage().getParameters().get('lastname');
    //String accountName = Apexpages.currentPage().getParameters().get('accountName');
    String phone = Apexpages.currentPage().getParameters().get('phone');
    String status = Apexpages.currentPage().getParameters().get('status');
 
    soql = 'select id,name,Comments__c,Customer_s_Phone_No__c,Rating_Status__c FROM Rating__c where name != null';
    if (!name.equals(''))
      soql += ' and name LIKE \''+String.escapeSingleQuotes(name)+'%\'';
    if (!phone.equals(''))
      soql += ' and Customer_s_Phone_No__c LIKE \''+String.escapeSingleQuotes(phone)+'%\'';
    if (!status.equals(''))
      soql += ' and Rating_Status__c = \''+status+'\'';

    // run the query again
    runQuery();
 
    return null;
  }
  public PageReference process() 
  {
  
       for (CategoryWrap cw : categories) {
            if (cw.checked)
               selected.add(new CategoryWrapper(cw.cat));
               //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,cw.cat.name));
         }
	 if (selected.size() > 0) {
             return Page.sel;
         } else {
             ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select at least one Category.'));
             return null;
         }
  }
  public PageReference back() {
        return Page.Search;
  }
  public void clear() {
	selected.clear();
	ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'List Cleared'));
  }
     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 first() {
        con.first();
    }
    public void last() {
        con.last();
    }
    public void previous() {
        con.previous();
    }
    public void next() {
        con.next();
    }
    public void cancel() {
        con.cancel();
    }
}

 
  // use apex describe to build the picklist values
  public List<String> statuses {
    get {
      if (statuses == null) {
 
        statuses = new List<String>();
        Schema.DescribeFieldResult field = Rating__c.Rating_Status__c.getDescribe();
 
        for (Schema.PicklistEntry f : field.getPicklistValues())
          statuses.add(f.getLabel());
 
      }
      return statuses;          
    }
    set;
  } 
}

 category wrap class :

public class CategoryWrap {
 
    public Boolean checked{ get; set; }
    public Rating__c cat { get; set;}
 
    public CategoryWrap(){
        cat = new Rating__c();
        checked = false;
    }
 
    public CategoryWrap(Rating__c c){
        cat = c;
        checked = false;
    }
 
    public static testMethod void testMe() {
 
        CategoryWrap cw = new CategoryWrap();
        System.assertEquals(cw.checked,false);
 
        CategoryWrap cw2 = new CategoryWrap(new Rating__c(name='Test1'));
        System.assertEquals(cw2.cat.name,'Test1');
        System.assertEquals(cw2.checked,false);
 
    }
 
}

 

I have an issue. My requirement is this, I have a VF page which opens from a custom button located on a Case Detail page. 
The VF Page has a CommandLink and a CommandButton which performs certain update to the Case Owner field on the Case detail page. 
The VF Page is opened as a Sub tab to a Case Primary tab on the console. 

After updating the changes to the owner field on the case detail, I have to refresh my Primary Tab(Case Detail) and along with that i have to close the Sub tab which contains the VF Page.
I find a weird issue here, 
My sub tab is getting closed first and the Primary tab refreshes after sub tab is closed. So what happens now is wierd for me, When the refresh of the primary tab happens it opens the closed VF Page again(that is the sub tab is reopened).
I want to close the sub tab after the save has happened on the primary tab and refresh success. 

Here is my code, 

MY VF PAGE: 
<apex:page standardController="Case" extensions="CIAssignProjectController" name="Assign Project">
    <apex:includeScript value="/support/console/34.0/integration.js"/>

    <script type="text/javascript">

        function setBeforeUnloadEvent(flag) {
            console.log('getting primary tab id');
            sforce.console.getEnclosingPrimaryTabId(getPrimaryTabId);
            console.log('getting current subtab id');
            sforce.console.getEnclosingTabId(getSubtabId);
            if(flag){
                //First find the ID of the current tab to close it
                console.log('refreshing');
                refreshTabsAfterSave();
                //setTimeout(function(){doCloseTab();},5000)
            }
        }
        
        function refreshTabsAfterSave () {
            console.log('getting link');
            sforce.console.getTabLink(sforce.console.TabLink.PARENT_AND_CHILDREN, currentPrimaryTabId, refreshPrimaryTab);
        }

        var refreshPrimaryTab = function refreshPrimaryTab (res) {
            console.log('tab link is: ', res);
            sforce.console.openConsoleUrl(currentPrimaryTabId, res.tabLink, true, [], [], afterRefresh);
        }

        var currentSubTabId; // set on page load
        var currentPrimaryTabId; // set on page load

        var getPrimaryTabId = function getPrimaryTabId (result) {
            console.log('primary tab id is: ', result.id);
            currentPrimaryTabId = result.id;
        }

        var getSubtabId = function getSubtabId (result) {
            console.log('sub tab id is: ', result.id);
            currentSubTabId = result.id;
        }

    var afterRefresh = function afterRefresh (res) {
            console.log('after refresh, get enclosing tab');
            sforce.console.getEnclosingTabId(getEnclosingTab);
        }
        
        var getEnclosingTab = function getEnclosingTab (res) {
            console.log('enclosing tab is: ', res.id);
            sforce.console.closeTab(res.id);
        }

        function doCloseTab() {
            sforce.console.getEnclosingTabId(closeSubtab);
        }      
        var closeSubtab = function closeSubtab(result) {
            var tabId = result.id;
            sforce.console.closeTab(tabId);
        };
        
    </script>

    <apex:form >
        <apex:pageMessages />
        <apex:pageBlock title="Work Assignment">
            <apex:pageBlockSection Title="User Data" columns="1" >
                <apex:pageBlockTable id="UserSkillsTable" value="{!MatchingUserSkills}" var="ms" rendered="{!IF(AND(NOT(ISBLANK(MatchingUserSkillsdata)),MatchingUserSkillsdata.size > 0), true, false)}" >
            <!-- A number of columns goes here -->

                    <apex:column style="width:7%">
                        <apex:facet name="header">Assign Project</apex:facet>

            <!-- This is where i Update the Owner of the Case field -->

                        <apex:commandLink status="loadingStatus" immediate="true" action="{!Assignrecord}" oncomplete="setBeforeUnloadEvent('{!pageswitch}');" value="Assign"> 
                            <apex:param name="Assignrowid" value="{!ms.MatchingUserId}"/> 
                         </apex:commandLink>
                    </apex:column>

                </apex:pageBlockTable>
            </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton status="loadingStatus" action="{!AutoAssignrecord}" value="Auto Assignment" oncomplete="setBeforeUnloadEvent('{!pageswitch}');" /> 
                <apex:commandButton status="loadingStatus" onclick="doCloseTab();" value="Back" />
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form> 

</apex:page>
My Class: (Only Button Logic I have added)
public class CIAssignProjectController {

    Public Boolean pageswitch {get;set;}
    private Case cs {get;set;}
    Private case c1;

    public CIAssignProjectController (ApexPages.StandardController controller) {
        cs =(Case) controller.getRecord();
        pageswitch = false;
        }

    // No Problem with this code, As this is getting the Owner Field updated perfectly
    public pagereference Assignrecord(){ 

        if(cu.Profile.Name == 'CI User'){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,system.label.Projectusererrormessage));
            return null;
        }
        else{
            System.debug('//////////'+lstTask);
        // Some Codes for Update runs here , No errors on this found

            try{
                update c1;
                pageswitch = true;
                if(lstTask.size()>0){
                    update lstTask; 
                }
                
                //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm,system.label.CI_Assign_Project));
                //PageReference updatepageRef = new PageReference('/' + cs.id);
                //updatepageRef.setRedirect(true);
                //return updatepageRef; 

                return null; // I return Null because, If i call PageReference it opens the case detail in the Same Sub tab.
            }
            catch(DmlException ex){
                ApexPages.addMessages(ex);
                return null;        
            }          
        }
    }

}
MY Button Code : 
(Execute javaScript)
{!REQUIRESCRIPT("/soap/ajax/31.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")} 
{!REQUIRESCRIPT("/support/console/27.0/integration.js")} 
var caseId = '{!Case.Id}'; 

var s = caseId.toString(); 
var returnMessage = sforce.apex.execute("AssignProject","checkSLABreach",{recid:s}); 
if(returnMessage!='') 
{ 
alert(returnMessage); 
} 
else 
{ 

if (sforce.console.isInConsole()) { 
sforce.console.getEnclosingPrimaryTabId(function(result){ 
sforce.console.openSubtab(result.id, '/apex/CIAssignProject?id=' + caseId, true, 'Assign Project: {!Case.CaseNumber}', null); 
}); 
} 
else { 
window.open('/apex/CIAssignProject?id=' +caseId); 
} 
}

The main problem that i guess is because the afterRefresh callback function on OpenConsoleURL is called first and then the refresh happens. 
I tried to give setTimeOut(function(){afterRefresh},5000); on openConsoleUrl, But it is not working for me. 

For anyone interested, the following Code is a trigger that send an email update to Case Owner, Case Contact and Case Team (users and contacts) in the Case everytime Case has been updated with an new Email-to-Case Message.

 

I have no idea why my list of Attachments is empty in the following lines of code??? The debug logs return 0 although my email test has attachments in the email and I can see this when going to the email Message record in the case.

 

list<Attachment> allAttachmentsInEmail = [Select Name, ContentType, Body From Attachment Where parentId =:e.id];


system.debug('---->number of attachments: ' + allAttachmentsInEmail.size());

 

Hope someone knows if I did something silly with my query?

 

Full code for those interested in using it.

 

trigger SendEmailUpdateOnEmailMessageForCase on EmailMessage (before insert, after insert) { 

	try{	
		for(EmailMessage e: trigger.new){
		
			//system.debug('@@@###$$$%%^^ Inserted email' + 'trigger size = ' + trigger.new.size());
			string caseId = string.valueof(e.ParentId);
						
			if(caseId.startsWith('500')){	//This Email Message is for a Case 
				
				//Look up Case Details
				Case theCase = [SELECT Id, ContactId, OwnerID, Subject, Priority, IsClosed, EntitlementId, Description, CreatedDate, CaseNumber, AccountId, Email_Message_Body_Copy_For_Template__c  FROM Case WHERE Id =: caseId Limit 1];			
				
				if(trigger.isBefore){	
					if(e.TextBody != theCase.Email_Message_Body_Copy_For_Template__c){
						theCase.Email_Message_Body_Copy_For_Template__c = e.TextBody; //This field updates the Case so that we can dynamically merge field in the Template 'CASE_ICT_Customer_New_Case_Update'
						try{
							update theCase;
						}catch(dmlexception e2){
							system.debug('Problem with udpating Case sObject in SendEmailUpdateOnEmailMessageForCase: ' + e2.getMessage());
						}
					}				
					
				}else if(trigger.isAfter){
					
					system.debug('***** the email Id is ' + e.id);
					Set<ID> toEmailId = new Set<ID>();;
					toEmailId.add(theCase.OwnerId);
					//Get Ids of the Case Team Members
					List<CaseTeamMember> member = [Select MemberId From CaseTeamMember where ParentId =:caseId];
					
					for(CaseTeamMember m: member){
						toEmailId.add(m.MemberId);			
					}
					//system.debug('%%%List of Members %%%%% ' + toEmailId);
					
					//Get contact and user list from the set of Id's			
					List<Contact> listContactEmails = [SELECT Email FROM Contact Where ID IN: toEmailId];
					List<User> listUserEmails =  [SELECT Email FROM User Where ID IN: toEmailId]; 
		
					//Get all email address in unique set
					Set<String> setOfContactEmails = new Set<String>();
					Set<String> setOfUserEmails = new Set<String>();
					for(Contact c: listContactEmails){
						setOfContactEmails.add(c.Email);
					}
					for(User u: listUserEmails){
						setOfUserEmails.add(u.Email);
					}
								
					list<String> listOfEmails = new list<String>();
					listOfEmails.addAll(setOfContactEmails);
					listOfEmails.addAll(setOfUserEmails);
					listOfEmails.sort();		
				
					//Create the email message body
					Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
					EmailTemplate emailTemp = [Select id From EmailTemplate Where developerName = 'CASE_ICT_Customer_New_Case_Update' Limit 1]; //A email template for Cases
					email.orgWideEmailAddressId = '0D2D0000000GnPW';	//Our Org Wide default
					email.replyTo = 'support.test@ictnetworks.com.au';
		      		        email.saveAsActivity = false;
					email.settargetObjectId(theCase.ContactId);
					email.setCcAddresses(listOfEmails);
					email.setTemplateId(emailTemp.Id);
					email.setwhatId(theCase.Id);
					
					//Check for Attachments							
					system.debug('H$H$H$H$H Attachment Flag: ' + e.HasAttachment);
					if(e.HasAttachment){
						//Create list of Messageing email File Attachments
						list<Messaging.EmailFileAttachment> fileAttachments = new list<Messaging.EmailFileAttachment>();
						//Query all child Attachments relating to this email Id
					        list<Attachment> allAttachmentsInEmail = [Select Name, ContentType, Body From Attachment Where parentId =:e.id]; 
						//Add to list of Attachments to email
						system.debug('---->number of attachments: ' + allAttachmentsInEmail.size());
						for(Attachment a: allAttachmentsInEmail){
							Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
							efa.setFileName(a.Name);
							efa.setBody(a.Body);
							fileAttachments.add(efa);
						}
						email.setFileAttachments(fileAttachments);
					}	
					
					system.debug('@@@@@targetI ObjectID = ' + email.targetObjectId);
					system.debug('@@@@@emailTemp.Id = ' + emailTemp.Id);
					system.debug('@@@@@whatId = ' + email.whatId);
					//email.setPlainTextBody('Hello!'); 
					//email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); 
					//system.debug(email); 
					//Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
										
				}
			}
		}
	} catch (exception e){
		System.debug('The following exception has occurred: ' + e.getMessage());
	}		

}

 

 

 

Hi

 

I'm trying to query for month value from a date field f my custom object
like say ,
SELECT Id,Date__c from custom_obj__c where . . . . .
using date__c.getMonth() or MONTH(date__c). i get an error that "Invalid aggregate Function"

I dont want to create a formula field and query based on it . Is ter any possibility without creating formula field for date .
Thanks in advance

ajay

Hi

 

I need to auto-populate the account lookup for a new Contact by using custom button.

When i click on the standard Button New Contact , the retUrl and accId denotes the Id's of the account for which a new contact is created , somthing like this .. https://ap1.salesforce.com/003/e?retURL=%2F0019000000FecuW&accid=0019000000FecuW

I dont wanna hard code it so ,
I create a new custom button say New My Contact .. as a list button and content source as URL ..
I gave something like this ,
/003/e?retURL=/{! Account.Id }& accid={!Account.Id}
but its returning null for account Id ..

Please Help


Thanks
Aj

Hi All
i'm new to salesforce . I have been asked to display the records of the Account Object as multiple tabs along with their related lists in a VF layout .

Can anyone please help me out with the code

 

Thanks in Advance

I have few problems on <apex:detail>.

 

  1. Can we use <apex:detail> for custom Objects?
  2. When I use <apex:detail>, do I need to create any kind of page?

Plz anyone clarify about <apex:detail> .