• PRO
  • 3645 Points
  • Member since 

  • Chatter
    Feed
  • 104
    Best Answers
  • 0
    Likes Received
  • 13
    Likes Given
  • 1
    Questions
  • 1792
    Replies
Hi folks,

I'm trying to create a sort of "Master Case" window in Visualforce, that shows 3 List Views of the same Cases object.

I'm using the following code to do this.
 
<apex:page>
  <apex:enhancedList type="Case" height="300" rowsPerPage="25" id="Walk_in_Line" customizable="false" />
  <apex:enhancedList type="Case" height="300" rowsPerPage="25" id="Web_Cases" customizable="false" />
  <apex:enhancedList type="Case" height="300" rowsPerPage="50" id="MyOpenCases" customizable="false" />
</apex:page>
And you can see where I'm targetting the same Object, but using a different ID each time, to target different List Views.

The problem is that when the window finaly opens, each of the List Views is set to view the last List View ID that I used.  Meaning that I get a window with 3 List Views, but they're all set to "MyOpenCases".

Is this a bug or am I doing something wrong?

Thank you for any help!
I have a "Add new Task" Button that should be displayed in every row of my visual force table via apex:repeat. The button leads to a rendered output panel, where a new task can be generated. When hitting the button in the according line, the field "Related To" of the new task should already be prefilled with the WhoId of the custom object that is queried within the Apex:repeat of the table.

Thus, how would I pass on the item.Id within the Apex repeat to the controller?
 
<apex:form >
    <apex:pageblock >
    <apex:pageMessages />

        <apex:outputpanel rendered="{!generateTask==false}">
            <table class="list" border="0" cellpadding="0" cellspacing="0" id="maintable">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Start Date</th>
                        <th>New Task</th>
                    </tr>
                </thead>

                <apex:outputPanel id="tableData">
                    <apex:repeat value="{!lstDevRequests_edit}"  var="item">
                        <tbody>
                            <tr>
                                <td>{!item.Name}</td>
                                <td><apex:outputText value="{0,date,MM/dd/yyyy}"> <apex:param value="{!item.Start_Date__c}" /> </apex:outputText></td>
                                <td><apex:commandButton action="{!generateTask}" value="New Task" id="newTaskButton"/></td>
                            </tr>
                        </tbody>
                    </apex:repeat>
                </apex:outputPanel>
            </table>
        </apex:outputpanel> 

        <apex:pageBlockSection title="Create New Task" columns="2" collapsible="false" rendered="{!generateTask==true}" >
            <apex:pageBlockSectionitem >
                    <apex:outputLabel value="Assigned To"/>
                    <apex:inputField value="{!insertnewTask.OwnerId}"/>
            </apex:pageBlockSectionitem>
            <apex:pageBlockSectionitem >
                    <apex:outputLabel value="Subject"/>
                    <apex:inputField value="{!insertnewTask.Subject}"/>
            </apex:pageBlockSectionitem>
            <apex:pageBlockSectionitem >
                    <apex:outputLabel value="Related To"/>
                    <apex:inputField value="{!insertnewTask.WhatId}"/>
            </apex:pageBlockSectionitem>         
        </apex:pageBlockSection>

    </apex:pageblock>
</apex:form>
 
public with sharing class tableRequests {
public List<Dev_Request__c> lstDevRequests_edit {get; set;}
public Task insertnewTask {get;set;}
public boolean generateTask {get;set;}



public tableRequests() {
    generateTask = false;
    lstDevRequests_edit = lstDevRequests_edit();
    insertnewTask = getnewTask();
}

public List<Dev_Request__c> lstDevRequests_edit() {
    if(lstDevRequests_edit == null)
        lstDevRequests_edit = [Select Id, Name, Assignee__c, Assignee__r.Name, Start_Date__c, Due_Date_QA__c, Estimated_Hours__c, Estimated_Completion_Date__c, Status__c, Overview__c, Parent_Dev_Request__c, (SELECT Id, WhatId, ActivityDAte, Owner.Name, Description, Status, Subject from Tasks) from Dev_Request__c];
    return lstDevRequests_edit;
}

public Task getnewTask() {
    Task newTask = new Task();
        newTask.WhatId = 'a0626000000EGH1AAO'; // This needs to be profiled with the corresponding item.Id
    return newTask;
}

public PageReference generateTask(){
    generateTask = true;
    return null;
}
}

Thank you for your help!
  • January 24, 2017
  • Like
  • 0
Hi Guys,
i am very close to developing a vf page on which i get a set of records from which i need to select "one and only one".
The challenges i faced are that i am able to select multiple records but not one. So tried to use radio button but that wouldn;t come for the save.
So pelase tell me how i can select single record and save it.
Below is my code and screenshot : 
<apex:page controller="wrapcontactlist">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
        $j = jQuery.noConflict();
        //$j = jQuery.noConflict();

   $j(document).ready(function() {

    alert('Inside function');
var last_valid_selection = null;
alert('Inside function1'+last_valid_selection);
         $j('#checkb').change(function(event) {
alert('Inside event function1'); // going till here but not below
            if ($j('#checkb').val().length > 1) {
						alert('Cannot choose! already oversized ID: fgbrt46456456546456cdfedf'+$j(this).val().length)
              $j(this).val(last_valid_selection);
            } else {
              last_valid_selection = $j(this).val();
            }
          });
        });
   

        /*$j(document).ready(function() {

          var last_valid_selection = null;

         $j('#checkb').change(function(event) {

            if ($j(this).val().length > 3) {
						alert('Cannot choose! already oversized ID: fgbrt46456456546456cdfedf'+$j(this).val().length)
              $j(this).val(last_valid_selection);
            } else {
              last_valid_selection = $(this).val();
            }
          });
        });*/
    </script>
    </head>
    
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="table"/>
            </apex:pageBlockButtons>
            <!-- In our table we are displaying the cContact records -->
            <apex:pageBlockTable value="{!contacts}" var="c" id="table">
                <apex:column >
                    <!-- This is our selected Boolean property in our wrapper class -->
                    
                        
                   
                            <apex:inputCheckbox value="{!c.selected}" id="checkb"/>

          
                           
                        
                    
                    
                </apex:column>
                <!-- This is how we access the contact values within our cContact container/wrapper -->
                <apex:column value="{!c.con.Name}" />
                <apex:column value="{!c.con.Email}" />
                <apex:column value="{!c.con.Phone}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

User-added image
 
Any clue on error.

/*********************************************VF Page*****************************************/
<apex:page standardController="Account" extensions="getSingleRelatedList">
    <apex:form >
        <apex:detail relatedList="false"/>
            <apex:selectList value="{!selectString }" multiselect="false" size="1">
              <b>Record Type :</b>  <apex:selectoptions value="{!Items}"/>
              <apex:actionSupport event="onchange" action="{!ClientRelatedList}" rerender="conList"/>
            </apex:selectList> <br/> <br/>
    </apex:form>
        <apex:relatedList list="Contacts" title="Employee Contacts" id="conList">
            <apex:facet name="body">
                <apex:pageBlock id="pageBlock">
                    <apex:pageBlockTable value="{!listContactClientRecT}" var="con">
                        <apex:column headerValue="Name">
                            <apex:outputLink value="/{!con.Id}">{!con.FirstName} {!con.LastName}</apex:outputLink>
                        </apex:column>
                    </apex:pageBlockTable>
            </apex:pageBlock>
           </apex:facet>
        </apex:relatedList>
</apex:page>


/**********************************Controller****************************************/

public class getSingleRelatedList {
     public List<Contact> listContactClientRecT{get; set;}
     public List<String>  listRecordType {get; set;}
     public String selectString {get; set;}
     public ID accId {set; get;}
     
     public getSingleRelatedList(ApexPages.StandardController controller) {
        listRecordType = new List<String>();
        listContactClientRecT = new List<Contact>();
        accId = controller.getId();
     }
    
    public pageReference getClientRelatedList(){
        listContactClientRecT  = [Select Id,FirstName,LastName, RecordTypeId from Contact where RecordTypeId =:selectString];  
    }
    
    public List<SelectOption> getItems() {
        List<SelectOption> options = new List<SelectOption>();
        List<Contact> listContactRecTypeId =[Select RecordTypeId from contact where AccountId =: accId]; 
        Set<ID> rectypeID = new Set<ID>();
        for(Contact objContact : listContactRecTypeId ){
            rectypeID.add(objContact.RecordTypeId);
        }
        
        
        if(listContactRecTypeId!=Null && !listContactRecTypeId.isEmpty())
        for(ID objContact: rectypeID){
            options.add(new SelectOption(objContact,objContact));
        }  
          return options;
    }
   
}
Hello,
I'm stuck probably in Syntax Error.
I try to print a QR Code in a VF Page.

This is the formula field content of the field in the custom Object:
IMAGE('https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=https://XXXXXXX.my.salesforce.com/'&Id,'Scan QR code to open record in mobile.')
This works fine in the record.

I try to output with the following:
<apex:image id="QR" value="https://chart.googleapis.com/chart?chs=100x100&cht=qr&chl=https://XXXXXXX.my.salesforce.com/&ID" width="100" height="100"/>
I tried several syntax variations with " and ' at different positions, but nothing worked.
The XXXXXXX part stands for the domain and "&ID" should be the record ID, from with I call the VF page with a button.
I can enter the domain staticly, but it would be nice, if it could be fetched from the instance.

Thanks for your Help.
Rainer


 

Hi, I trying to create a visualforce page to insert OpportunityLineItems, but it's not working, when I click "Salvar" (save) nothing happens, anyone could help me please?

page:

<apex:page controller="ProdOpController">
    <apex:form >
        <apex:pageBlock title="Novo Produto da Oportunidade">
            <apex:pageBlockSection title="Informações do Produto">
                <apex:inputField value="{!prodop.OpportunityId}"/>
                <apex:inputField value="{!prodop.Quantity}"/>
                <apex:inputField value="{!prodop.UnitPrice}"/>
                <apex:selectList multiselect="false" size="1" value="{!prodop.Product2Id}">
                    <apex:selectOptions value="{!prodOptions}"/>
                </apex:selectList>
            </apex:pageBlockSection>
        <apex:pageBlockButtons >
            <apex:commandButton action="{!salvar}" value="Salvar"/>
        </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

controller:
 
public class ProdOpController {
    
    public OpportunityLineItem prodop{ get; private set; }
    
    public ProdOPController(){
        prodop = new OpportunityLineItem();
        System.debug('Entrei no construtor');
    }
    
    public PageReference salvar(){
        System.debug('Entrei em salvar');
        try{
            insert prodop;
        }
        catch(System.DMLException e){
        	System.debug('insert prodop falhou');
            System.debug(e);
            ApexPages.addMessages(e);
            return null;
        }
        PageReference redirectSuccess = new ApexPages.StandardController(prodop).view();
        return (redirectSuccess); 
    }

    public List<SelectOption> getProdOptions(){
        List<PricebookEntry> prods = Database.query(
        	'SELECT Id, name FROM PricebookEntry'
        );
        List<SelectOption> options = new List<SelectOption>();
        for(PricebookEntry p : prods){
            options.add(new SelectOption(p.Id, p.Name));
        }
        System.debug('listei as opcoes de produtos');
        return options;
    }
}

 
Requirement on trigger -- my requirement is if we change the opportunity stage  to "CLosed won" , 
 based on email address present in  Contact role in  opportunity line item  we need to send an automatic reply email to that email address  .
 can any one share sample code or give us idea how to write this trigger.
On creation of a Partner Community User from contact we are creating a account share record for contact's related account.
Also, case share record gets created automatically due to the created account share.
While updating contact's related account with another account, the account share which we have created gets deleted. Why?
We need to delete the case share record as well. But the case share record is not getting deleted. Please let us know the possible solutions.


It will be helpful if someoen can help
Hello All

   I am new to SFDC. I got a requirement please let me know the possible solution. Here is the req:
I have a custom obj and have MD with the accounts obj and lookup with the contacts obj. When i select a particluar account then it should show only the contacts releated to that account in my custom obj. How can i achieve this ?
 
Greetings,

I'm having some trouble with a trigger I've written.  This is intended to create a task based upon certain fields in a custom object.  The tasks are created as expected, except WhatID is not populated in the tasks, therefore they are not linked to the custom object record.
 
/**********************************************************************

  This trigger checks if tax docs are received and/or scanned on
  Tax_Services__c object and assigns tasks accordingly.

**********************************************************************/

trigger Tax_Docs on Tax_Services__c (before insert, before update) {

    List <Task> TasksToCreate = new List <Task> ();

    for(Tax_Services__c e : Trigger.new)
    {
  
        if(Trigger.isUpdate)
        {
            Tax_Services__c oldService = Trigger.oldMap.get(e.ID);
            
            if(e.Tax_Docs_Received__c == TRUE && e.Tax_Docs_Scanned__c == TRUE)
            {
                if(e.Tax_Docs_Received__c != oldService.Tax_Docs_Received__c || e.Tax_Docs_Scanned__c != oldService.Tax_Docs_Scanned__c)
                {
                    TasksToCreate.add(new Task(OwnerID = e.Tax_Advisor__c,
                                               Subject = 'Tax Docs Received and Scanned',
                                               WhatID = e.Id,
                                               ActivityDate = date.today(),
                                               Status = 'Not Started',
                                               Priority = 'Normal',
                                               Hidden__c = 'Tax Docs Received & Scanned'));
                }
            }
            
            if(e.Tax_Docs_Received__c == TRUE && e.Tax_Docs_Scanned__c == FALSE)
            {
                if(e.Tax_Docs_Received__c != oldService.Tax_Docs_Received__c || e.Tax_Docs_Scanned__c != oldService.Tax_Docs_Scanned__c)
                {
                    TasksToCreate.add(new Task(OwnerID = e.Tax_Advisor__c,
                                               Subject = 'Scan Tax Docs',
                                               WhatID = e.Id,
                                               ActivityDate = date.today(),
                                               Status = 'Not Started',
                                               Priority = 'Normal',
                                               Hidden__c = 'Scan Tax Docs'));
                }
            }
        }
    
    
        if(Trigger.isInsert)
        {
            if(e.Tax_Docs_Received__c == TRUE && e.Tax_Docs_Scanned__c == TRUE)
            {
                    TasksToCreate.add(new Task(OwnerID = e.Tax_Advisor__c,
                                               Subject = 'Tax Docs Received and Scanned',
                                               WhatID = e.Id,
                                               ActivityDate = date.today(),
                                               Status = 'Not Started',
                                               Priority = 'Normal',
                                               Hidden__c = 'Tax Docs Received & Scanned'));
            }
            
            if(e.Tax_Docs_Received__c == TRUE && e.Tax_Docs_Scanned__c == FALSE)
            {
                    TasksToCreate.add(new Task(OwnerID = e.Tax_Advisor__c,
                                               Subject = 'Scan Tax Docs',
                                               WhatID = e.Id,
                                               ActivityDate = date.today(),
                                               Status = 'Not Started',
                                               Priority = 'Normal',
                                               Hidden__c = 'Scan Tax Docs'));
            }
        }
    }
            try
            {
                Insert TasksToCreate;
            }
            catch (System.DmlException ex)
            {
                System.Debug (ex);
            }
}

Any thoughts on what may be happening here?
Hello Everyone,

I reset one my user password but I didn't get any email via password. So pleae tell me how I can get the password?
I sthere anything else which I need to do for getting password??

Thank you.
Which Methodology / Model design pattern used in Salesforce1 platform?
Hello,

Is it possible to develope reports (tabular, summary, graphs) using visualforce.

Are there any tutorials I could follow.
Hey I need to transfer the events to another salesforce org using S2S functionality but I can able to find task while I publish but not Events. Please let me know wthr it is possible or not?
1. In DE under manage users | users, I don't have the option to login as the user for testing.
2. When setting up business hours, when I uncheck 24 hours boxes for Saturday and Sunday it keeps reverting back to 24 hours. To try to resolve it, I have created a holiday for Weekend and associated it to the group Business hours but I would rather have the weekend showing as 0 hours.
I had deleted the rule and started again, I'm sure it's correct and now the last step is complaining about the follow up task assignment not being found. I am unable to save it with the name the assignment checker expects because I had previously used the task name. This is unfortunate as I am not able to complete the challenge.
 
hi
is there any way to customise the standard email2case capability?
my customer has a scenario where they email resolutions to atheir customer and close the case
a while later the end customer replies to the email with a new issue, and this automotically attaches to the original case and reopens the old case

they want a rule that even if there is a thread ID, if the reply is after more than a month to create a new case.

or is there a way to de-atatch an email from one case and use it to create a new one?
thanks
when i syncing contacts between salesforce and outlook,i got a error.please rectify my errorhow to rectify this error
I am very new to anything Web to Lead.  We work will some affiliates and we get leads currenty posting into a different system through a URL like this

http://eleads.lafilm.com:8088/Cmc.Integration.LeadImport.HttpPost/ImportLeadProcessor.aspx?Format=Website&leadsource=INC4235&Firstname=Keith&Lastname=Hines&Address1=3777 s guest&Address2=&City=HOUSTON&State=TX&Postalcodeorzip=77063&Country=USA&Email=khines2005@yahoo.com&Phone=8325078883&WorkPhone=&Program=BSDC-O&Campus=MAIN2&PreviousEducation=GED&Agency=NON

How or what do I need to do in order to get these to post into SFDC preferably post as contacts not leads

Thanks In Advance

Sean



 
I'm not a coder so I searched for how to accomplish getting a section to have 3 (or more) columns and I did find something but the code isn't working.  Can someone help?

<apex:page>
<apex:pageBlockSection title="Labor Breakdown" columns="3">
              
<apex:pageBlockSectionItem dataStyle="width:10%" labelStyle="width:23%" >
<apex:outputLabel >Estimate1</apex:outputLabel>
<apex:inputField value="{!obj__c.Estimate__c}" style="width:80px"/>
</apex:pageBlockSectionItem>

<apex:pageBlockSectionItem dataStyle="width:10%" labelStyle="width:23%" >
<apex:outputLabel >Hours1</apex:outputLabel>
<apex:inputField value="{!obj__c.Hours__c}" style="width:80px"/>
</apex:pageBlockSectionItem>
          
<apex:pageBlockSectionItem dataStyle="width:10%" labelStyle="width:23%" >
<apex:outputLabel >Rate1</apex:outputLabel>
<apex:inputField value="{!obj__c.Rate__c}" style="width:80px"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:page>
Where are Chatter Files stored in the Database?

Is it the content Object?
  • October 07, 2014
  • Like
  • 0
Hello, I have a VF page containing a pageBlockTable with a number of rows. Each row has a command button added to it. I am trying to learn how to populate one of the fields on the row containing the command button when it is clicked. In the code below, I would just like to place a sample value in the comment field just to the left of the Start button. I've seen some jQuery samples, but can't seem to get the code to update only the comment field for the row that has the button.
<apex:pageBlockTable id="itemRows" value="{!woLineItems }" var="woitem">
	<apex:column headerValue="Line Item">{!woitem.LineItemNumber}</apex:column>
	<apex:column headerValue="Description">{!woitem.Description}</apex:column>
	<apex:column headerValue="Comments"><apex:inputField value="{!woitem.Comments__c}"/></apex:column>
	<apex:column headerValue="Start"><apex:commandButton value="Start"/></apex:column>
</apex:pageBlockTable>

Thank you in advance.
Scott
 
Hi guys,
          I'm now working with a community based on Napili template. Here my task is to fetch the record id from the record page and to display the details of the record in a separate page. I've wrote some coding for it but Since I'm new to lightning concept I'm not able to achieve this. I have given my code below.
<aura:component controller="ParamController" implements="force:lightningQuickAction,force:hasRecordId">
 <aura:attribute name="recordId" type="String" default="___"/>
    Record Id is {!v.recordId}
<ui:button label="Call server" press="{!c.echo}"/>
 </aura:component>
({
    echo : function(cmp,event,helper){
        
      
        var recordId = cmp.getParam("v.recordId");
     //   console.log("Current Record Id: " + attributeValue);

      //  var target = event.getSource();
        //cmp.set("v.recordId", target.get("v.recordId"));
     

        var action = cmp.get("c.serverEcho");
      
        action.setParams({ recordId : cmp.get("v.recordId") });

        action.setCallback(this, function(response) {
            var state = response.getState();
            
            if (state === "SUCCESS") {
              
                alert("From server: " + response.getReturnValue());

           
            }
            //else if (cmp.isValid() && state === "INCOMPLETE") {
            else if (state === "INCOMPLETE") {
                // do something
            }
            //else if (cmp.isValid() && state === "ERROR") {
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });

        $A.enqueueAction(action);
    }
})
public class ParamController {
     @AuraEnabled
 public static Account serverEcho(Id recordId) {

      
  Account acct=[SELECT Type,Industry,Rating FROM Account WHERE Account.Id=:RecordId];
  return acct;
  
    }

}

I want to pass the fetched record Id to the apex class and to display the record dtails using SOQL query.Please help me in accompolishing my task.
Thanks and Regards
Aruna

 
Hi folks,

I'm trying to create a sort of "Master Case" window in Visualforce, that shows 3 List Views of the same Cases object.

I'm using the following code to do this.
 
<apex:page>
  <apex:enhancedList type="Case" height="300" rowsPerPage="25" id="Walk_in_Line" customizable="false" />
  <apex:enhancedList type="Case" height="300" rowsPerPage="25" id="Web_Cases" customizable="false" />
  <apex:enhancedList type="Case" height="300" rowsPerPage="50" id="MyOpenCases" customizable="false" />
</apex:page>
And you can see where I'm targetting the same Object, but using a different ID each time, to target different List Views.

The problem is that when the window finaly opens, each of the List Views is set to view the last List View ID that I used.  Meaning that I get a window with 3 List Views, but they're all set to "MyOpenCases".

Is this a bug or am I doing something wrong?

Thank you for any help!
Hi Everyone,
I have created a Lightning component to retrieve list of tasks , while running the code i am getting this error : Action failed: c:Tasklist$controller$gettask [helper.gettask is not a function.

Please find my code and help me out to resolve this issue.
<aura:component controller="LightTaskListController" implements="force:appHostable">

     <aura:attribute name="Tasks" type="Task[]"/>
	 
    <aura:handler name="init" value="{!this}" action="{!c.gettask}" />
	
    <table class="slds-table slds-table--bordered slds-max-medium-table--stacked-horizontal">
	
        <thead>
            <tr class="slds-text-heading--label ">
                <th class="" scope="col">Task Name</th>
                <th class="slds-is-sortable" scope="col">Number Of Seats</th>
                <th class="slds-is-sortable" scope="col">License Plate</th>
                <th class="slds-is-sortable" scope="col">License Expiration Date</th>
                <th class="slds-is-sortable" scope="col">Fuel</th>                
            </tr>  
        </thead>
		
        <tbody>
		
            <aura:iteration items="{!v.Tasks}" var="tsk">
			
                <tr class="slds-hint-parent">
                    <td class="" data-label="Status" >
                        <a href="{! '#/sObject/' + tsk.Id + '/view'}">{!tsk.Status}</a>
                    </td>
					
                    <td data-label="Subject" style="padding-left:0;">
					        <ui:outputtext value="{!tsk.Subject}" />
					</td>
					
                    <td data-label="Priority" style="padding-left:0;">
                        <a href="{! '#/sObject/' + tsk.Id + '/view'}">{!tsk.Priority}</a>
				    </td>
						
                    <td data-label="Activity Date" style="padding-left:0;">{!tsk.ActivityDate}</td>
					
                    <td data-label="Description " style="padding-left:0;">{!tsk.Description }</td>                
                </tr>
				
            </aura:iteration>
			
        </tbody>
		
    </table>  
</aura:component>
 
Controller : 

({
gettask : function(component, event, helper) {
        helper.gettask(component);
    	}
})
 
Helper class : ({
  getVehicle : function(component) {
        var action = component.get("c.gettaskList");
        action.setCallback(this, function(a) {
            component.set("v.Tasks", a.getReturnValue());
        });
        $A.enqueueAction(action);
    
	}
})
 
Apex class : public with sharing class LightTaskListController{
    @AuraEnabled
    public static List<Task> gettaskList() {
        return [select Id,Priority,ActivityDate,Subject,Status,Description from Task];
    }    
}
Thanks in advance..
 
I'm getting multiple system error dialog when trying to execute System Events in Lightning Components (in Console Navigation app).

I've tried a link action and action button, and both return errors. My code is as follows:

Error in using force:navigateToSObject :
On a Link onclick, I'm opening the record's detail view by using force:navigateToSObject event as follows:
var navEvt = $A.get("e.force:navigateToSObject"); 
navEvt.setParams({ "recordId": recordId }); 
navEvt.fire();


And it throw following 2 error dialog, dialog 1 appear first, and then dialog 2 show up after clicking OK on dialog 1:
Error dialog 1:
Uncaught Error in $A.getCallback() [Cannot read property 'setParams' of undefined] throws athttps://pk1-dev-ed.lightning.force.com/auraFW/javascript/h_soHR8Rt2_c3cVcuaSlUA/aura_proddebug.js:18473:9Object.fireEvent()@https://pk1-dev-ed.lightning.force.com/components/force/navEventManager.js:159:16 Object.fireTranslatedEvent()@https://pk1-dev-ed.lightning.force.com/components/force/navEventManager.js:146:22 Object.fireTranslatedStateEvent()@https://pk1-dev-ed.lightning.force.com/components/force/navEventManager.js:177:18 Object.force:navigateToSObject()@https://pk1-dev-ed.lightning.force.com/components/force/navEventManager.js:214:18 Object.handleSimpleTranslation()@https://pk1-dev-ed.lightning.force.com/components/force/navEventManager.js:135:20


Error dialog 2:
Access Check Failed! EventService.getEventDef():'markup://force:navigateToState' is not visible to 'markup://pk1:ListContactRecord {3:1967;a}'. Object.fireEvent()@https://pk1-dev-ed.lightning.force.com/components/force/navEventManager.js:157:22 Object.fireTranslatedEvent()@https://pk1-dev-ed.lightning.force.com/components/force/navEventManager.js:146:22 Object.fireTranslatedStateEvent()@https://pk1-dev-ed.lightning.force.com/components/force/navEventManager.js:177:18 Object.force:navigateToSObject()@https://pk1-dev-ed.lightning.force.com/components/force/navEventManager.js:214:18 Object.handleSimpleTranslation()@https://pk1-dev-ed.lightning.force.com/components/force/navEventManager.js:135:20
Error in using force:editRecord :
On a Link onclick, I'm opening edit dialog for the record by using force:editRecord event as follows:
var editRecordEvent = $A.get("e.force:editRecord"); 
editRecordEvent.setParams({ "recordId": recordId }); 
editRecordEvent.fire();



This results in single error dialog, but it still opens up the Edit Modal dialog as well. Edit Record modal appears behind the System Error modal dialog with following error details:
 
Access Check Failed! AttributeSet.get(): attribute 'editOverriddenKeyPrefixes' of component 'markup://one:consoleLayoutContainer {1:0;p}' is not visible to 'markup://one:consoleLayoutContainer {1:0;p}'. Object.hasEditOverride()@https://pk1-dev-ed.lightning.force.com/libraries/one/centerStageLibrary/Record.js:154:29Object.handler_force_editRecord()@https://pk1-dev-ed.lightning.force.com/libraries/one/centerStageLibrary/Record.js:105:28 eval()@https://pk1-dev-ed.lightning.force.com/components/one/consoleLayoutContainer.js:1921:29Object.handleCenterStageEvent()@https://pk1-dev-ed.lightning.force.com/components/one/consoleLayoutContainer.js:1907:17handleCenterStageEvent()@https://pk1-dev-ed.lightning.force.com/components/one/consoleLayoutContainer.js:194:16



I'm running clueless as both these Edit and Record View actions work fine in Lightning Component, when the Lightning App is using Standard Navigation, and breaks with errors in Lightning Appwith Console Navigation in it.

Is there any other way available for accessing record view or edit? I've already tried following:
  1. Setting a direct URL = #/sObject/<recordId>/view
  2. Setting a direct URL = #/sObject/<recordId>/edit
Though, [1] URL works fine and opens record, but [2] still throws same error which happens on force:editRecord event navigation. Plus, I don't think setting direct URL formatting is ideal way to code, it seems more hackishh kind of way to me. Though I surely need some help if someone has ideas on this.
  • February 14, 2017
  • Like
  • 0
Our company currently has several businesses utilizing one Salesforce org. Most need to have the reference Id placed in the Subject and Body; which is how it is globally setup. We have one business that would like to utilize Email to Case, but cannot because they DO NOT want the reference Id in the subject line; they mainly deal with customers regarding sales questions.

Is there a way, declaratively or programmatically to remove the subject reference id or "hide" it based on a profile or email template?

The option to make the change globally is off the table.

Thanks for your help!

Shannon
Hi Everyone ,
      I have 2 visualforce pages given below . One works , other does not . I am trying to grey out the page upon click of  a button , so I am trying to call out an action status from command button .  In this page given below it works perfectly well:

<apex:page standardController="Account">
<style>
    /* This is for the full screen DIV */
    .popupBackground {
        /* Background color */
        background-color:black;
        opacity: 0.20;
        filter: alpha(opacity = 20);
    
        /* Dimensions */
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 998;
        position: absolute;
        
        /* Mouse */
        cursor:wait;
    }
 
    /* This is for the message DIV */
    .PopupPanel {
        /* Background color */
        border: solid 2px blue;
        background-color: white;
 
        /* Dimensions */
        left: 50%;
        width: 200px;
        margin-left: -100px;
        top: 50%;
        height: 50px;
        margin-top: -25px;
        z-index: 999;
        position: fixed;
        
        /* Mouse */
        cursor:pointer;
    }
</style>
<apex:actionStatus id="statusSaveTrip" stopText="">
    <apex:facet name="start">
        <div>
            <div class="popupBackground" />
            <div class="PopupPanel">
                <table border="0" width="100%" height="100%">
                    <tr>
                        <td align="center"><b>Please Wait</b></td>
                    </tr>
                    <tr>
                        <td align="center"><img src="{!$Resource.ProgressBar}"/></td>
                    </tr>
                </table>
            </div>
        </div>
    </apex:facet>
</apex:actionStatus>
<apex:form id="myForm">
    <apex:pageMessages />
    <apex:pageBlock >
        <apex:pageBlockButtons location="Top">
            <apex:commandButton value="Click Me" action="{!quicksave}" rerender="myForm" status="statusSaveTrip" />
        </apex:pageBlockButtons>
        <apex:pageBlockSection >
            <apex:inputField value="{!Account.Name}" />
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>


When I try to imitate the same piece of code in this page it does not work , can I please know why this is the case? What am I doing wrong here:

<apex:page controller="ProposalSearchControllerModified" sidebar="false" readonly="True">

<style>
    /* This is for the full screen DIV */
    .popupBackground {
        /* Background color */
        background-color:black;
        opacity: 0.20;
        filter: alpha(opacity = 20);
    
        /* Dimensions */
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 998;
        position: absolute;
        
        /* Mouse */
        cursor:wait;
    }
 
    /* This is for the message DIV */
    .PopupPanel {
        /* Background color */
        border: solid 2px blue;
        background-color: white;
 
        /* Dimensions */
        left: 50%;
        width: 200px;
        margin-left: -100px;
        top: 50%;
        height: 50px;
        margin-top: -25px;
        z-index: 999;
        position: fixed;
        
        /* Mouse */
        cursor:pointer;
    }
</style>
<apex:actionStatus id="statusSaveTrip" stopText="">
    <apex:facet name="start">
        <div>
            <div class="popupBackground" />
            <div class="PopupPanel">
                <table border="0" width="100%" height="100%">
                    <tr>
                        <td align="center"><b>Please Wait</b></td>
                    </tr>
                    <tr>
                        <td align="center"><img src="{!$Resource.ProgressBar}"/></td>
                    </tr>
                </table>
            </div>
        </div>
    </apex:facet>
</apex:actionStatus>


  <apex:form >
  <apex:pageMessages id="errors"/>

  <apex:pageBlock title="Search Proposal Records" mode="edit" id="OuterPageBlock">

  <table width="100%" border="0">
  <tr>  
    <td width="200" valign="top">

      <apex:pageBlock title="Search Parameters" mode="edit" id="criteria">

      <script type="text/javascript">
      function stopRKey(evt) {
       var evt = (evt) ? evt : ((event) ? event : null);
       var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
       if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
       }

       document.onkeypress = stopRKey; 
       
      function doSearch() {
        searchServer(
          document.getElementById("Name").value,
          document.getElementById("OpportunityID").value
         
          );

      }
     
   

      </script> 

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors,size,size1,size2">
          <apex:param name="Name" value="" />
          <apex:param name="OpportunityID" value="" />

      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">Opportunity ID<br/>
        <input type="text" id="OpportunityID" />
        </td>
      </tr>
    
      <tr>
        <td><br/>
         <apex:commandButton onclick="doSearch();return false;" value="Search Proposals”/ status=“statusSaveTrip”>&nbsp;&nbsp;
         <apex:commandButton value="Reset Filters" action="{!reset}"/>



        </td>      
      </tr>


      
      <tr>
        <td>
               
        </td>  
      </tr>
      

       
   </table>
  </apex:pageBlock>

    </td>

    <td valign="top">
    <table style="width: 100%;">
    <td>
    
    <apex:pageBlock mode="edit" id="results">    

        <div style="overflow: auto; height: 300px;">
          
        <apex:pageBlockTable value="{!Opportunities}" var="opp">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Opportunity Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>

                <apex:commandlink value="{!opp.Name}" rerender="RecordDetailSection" action="{!ClearOrder}">                
                 <apex:param name="DetailRecordId"  value="{!opp.Id}" assignTo="{!DetailRecordId}"/>   
                </apex:commandlink>               

            </apex:column>
            


            
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Opportunity ID" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="OpportunityID" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!opp.Opportunity_ID__c}"/>
            </apex:column>
            
          

        </apex:pageBlockTable>
       </div>
       
    </apex:pageBlock>
    
    </td>

    <tr>
        <td>
                        </td>
            </tr>
            </table>
    
    
        </td>

  </tr>

  </table>

   

  </apex:pageBlock>

  </apex:form>
   
 
I have a custom button on the opportunity object that generates a visualforce page. This Visualforce page is populated with the information in the opportunity record fields. I created a validation for the button to make sure that some fields are populated in order to execute the visualforce page. The problem is that with this validation the visualforce page is no longer pulling information from the opportunity record so I end up only with the skeleton of the page but no content. 

The code is as follows 

{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")}


if({!ISBLANK(Opportunity.Fecha_inicio_contrato__c)}){
alert("No todos los campos necesarios para la ODC están llenos");
}
else{
window.open('/apex/Quote');
}

Is there any way to have a validation on a custom button but still make it possible for it to pull information from the record?
Hi,

i have some unique requirement now. i have to make report that show like this table below.(i changed the theme to pokemon to make easily understanding).
Pokemon NamePokemon LocationElement Lightning DefenceElement Fire DefenceElement Water DefenceElement Earth Defence
BulbasaurForest0010050
PikachuGrass5000100
CharizardMountain0501000
LaprasSea0100500

i have 3 List =
1. list a<Master_Element>
2. List b<Pokemon_Name>
3. List c<Defence_Atrribute_Each_Pokemon>

the requirement are :
1. not hardcode for the element.if someone add master element, automatically the report will show the new element with the attribute. dont have to change the Visualforce Page.

for the table header i already succesfull make like this below.
<table>
<thead>
<tr>
                    <td align="Center"> Pokemon Name </td>
                    <td align="Center"> Pokemon Location </td>
                        <apex:repeat value="{!Element}" var="e"> 
                        <td align="center">{!e.Element_Name__c}</td>
                        </apex:repeat>
</tr>
</thead>
<tbody>
<apex:repeat value="{!Pokemon}" var="f">
                    <tr>
                        <td>{!f.Pokemon_Name__c}</td>
                        <td>{!f.Pokemon_Location__c}</td>
                         <apex:repeat value="{!DefElementValue}" var="g"> 
                        	<td  align="center">{!g.Def_Pokemon_Element__c}</td>
                        </apex:repeat>
                      <tr>
</apex:repeat>
</tbody>
</table>

my question are:
1. me stuck on show up the def element (remember that the value will follow how many master element exist automatically)
2. Is there any other idea to solve this requirement?maybe like {!defElementValue} get the pokemon name first (filter the list based on what pokemon on that row)

me really desperate for this one, deadline already close anyway. T_T
thank you guys.


TJ

Hi Everyone,

I have a outputField which is uder repeat component. I have inlineEditSupport for inline editing. Now i made a html buttton on the top, my requirement is button should be dislayed only in inline edit mode.

i made a javascript fuction to display the button.

<script>
    	function showSave() {
    		alert('##');
    		document.getElementById('saveButton').style.display ="block";
    	}
    </script>
but i am not sure how to call this on double click for outputField.

i tried putting actionSupport in the outputField, but i am not sure.

Any help would be appreciated.

Thanks,

Manohar

 

I am facing issue with pagination as its not working correctly. its droping records. could you please help me out.
Here is my code.

Apex class: 


public with sharing class SearchController{

    public integer PageSize {get;set;}
    public integer PageNumber {get;set;}
    public integer RecordCount {get;set;}
    public List<contactwrapper> objAWList {get;set;}
    private Set<id> selectedContactIds;
    public boolean displayPopup {get; set;}  
    public List<contact> objSelectedContacts {get; set;}
    private String soql {get;set;}  
      
    public SearchController() {
        PageSize = 10;
        PageNumber = 1;   
        RecordCount = 0;
        selectedContactIds = new Set<id>();
        objAWList = new List<contactwrapper>();
        objSelectedContacts = new List<contact>();
          
    }
      

    public void closePopup() {        
        displayPopup = false;    
    }     
      

    public void showPopup() {  
        setSelectedContacts();      
        displayPopup = true;    
        objSelectedContacts  = GetSelectedcontacts();
    }
      
    public Integer getSelectedCount(){
        return this.selectedContactIds.size();
    }
      
    public List<contact> GetSelectedContacts(){    
        List<contact> objConList = [Select Id, Name,Email,Account.Name,Account_Cust__c,Job_Title__c 
                                    From Contact Where ID IN : selectedContactIds];       
        system.debug('objConList :'+objConList);
        return objConList;
    }
      
      
    private void setSelectedContacts()
    {
        for(contactwrapper item: objAWList)
        {
            if(item.IsSelected)
            {    
                if(!this.selectedContactIds.contains(item.ContactId))
                {
                    this.selectedContactIds.add(item.ContactId);
                }
            }
            else
            {
                if(this.selectedContactIds.contains(item.ContactId))
                {
                    this.selectedContactIds.remove(item.ContactId);
                }
            }
        }        
    }
      
    public integer PageIndex {
        get { return (PageNumber - 1); }
    }    
      
    public integer PageCount {
        get { return getPageCount(); }
    }
      
    public integer Offset {
        get { return (PageSize * PageIndex); }
    }
      
  
    public void runSearch() {
        objAWList = new List<contactwrapper>();
        try {
                List<Contact> objConList = new List<Contact>(); 
                String contactName = Apexpages.currentPage().getParameters().get('ContactName');
         
                if (!contactName.equals('')){
                    soql = 'select firstname, lastname, Name,account.name,Job_Title__c,Account_Cust__c from contact where account.name != null';
                    soql += ' and name LIKE \'%' + contactName + '%\'';
                    soql += ' order by firstName ASC limit '+PageSize +' offset '+Offset;
                    system.debug('soqlfinal::'+soql);
                    objConList = Database.query(soql);
                    RecordCount = objConList.size();
                    
                }else if(contactName.equals('')){
                    RecordCount = objConList.size();
                    objConList.clear();
                }
          
                 system.debug('objConList---'+objConList);                    
                 if(!objConList.isEmpty()){                         
                     for(Contact Con : objConList){
                            ContactWrapper objAW = new ContactWrapper();
                            objAW.ContactId = Con.Id;
                            objAW.ContactName = Con.Name;
                            objAW.AccountCust= Con.Account_Cust__c ;
                            objAW.JobTitle= Con.Job_Title__c;
                            
                            if(this.selectedContactIds.contains(con.Id)){
                                objAW.IsSelected = true;
                            }
                            else{
                                objAW.IsSelected = false;
                            }
                            objAWList.Add(objAW);
                     }
                 }             
             
        }
        catch (QueryException e) {
            ApexPages.addMessages(e);   
            
        }
    }
      
    public integer LNumber {
        get { return RecordCount == 0 ? 0 : (Offset + 1); }
    }
  
    public integer UNumber {
        get { 
            integer iUNum = ((LNumber + PageSize) - 1);
            return (iUnum > RecordCount) ? RecordCount : iUNum; 
        }
    }
      
    public boolean AllowMoveNext {
        get{ return ((PageIndex + 1) < PageCount); } } public boolean AllowMovePrev { get{ return (PageIndex > 0); }
    }
      
    public void Prev() {
        setSelectedContacts();
        PageNumber--;
  
        if (PageNumber <= 0) { PageNumber = 1; } } public void Next() { setSelectedContacts(); PageNumber++; if (PageNumber > PageCount) {
            PageNumber = PageCount;
        }
    }
      
    public void Last() {
        setSelectedContacts();
        PageNumber = PageCount; 
    }
  
    public void First() {
        setSelectedContacts();
        PageNumber = 1;
    }
      
    private integer getPageCount() {
        integer iPageCount = 1;
  
        if (RecordCount != 0 && PageSize != 0) {
            iPageCount = (RecordCount/PageSize) + ((Math.mod(RecordCount, PageSize)) > 0 ? 1 : 0);
        }
        return iPageCount;
    }
      
    public class Contactwrapper
    {
        public Id ContactId {get;set;}
        public String ContactName {get;set;}
        public String AccountCust {get;set;}
        public String JobTitle {get;set;}
        public Boolean IsSelected{get;set;}
        public Contactwrapper()
        {
    
        }
    }    
}
 
I added the flying saucer specific CSS to maintain the header of a dataTable when a table continues after a page break but now the table borders show double lines. Below a screen shot along with the visualforce page and static CSS file. Is there a cleaner way to implement continual table dataTable headers and how can I remove the double border to just one line ?

User-added image

 
CSS file; 

.allPDFdatatables {
    text-align: right;
    font-family: 'Arial'; 
    font-size: 75%;   
    vertical-align: middle;
    border-collapse: collapse; 
    border: 1px solid black;
    padding: 5px 5px 5px 5px;
    color: blue;
    border-bottom: 1px solid #ddd;
    -fs-table-paginate: paginate;
    border-spacing: 0;	
}

.allPDFdatarows {
    text-align: right;
    font-family: 'Arial'; 
    font-size: 75%;   
    vertical-align: middle;
    border-collapse: collapse; 
    border: 1px solid black;
    padding: 5px 5px 5px 5px;
    color: black;    
    border-bottom: 1px solid #ddd;
}

.allPDFdatacols {
    border-collapse: collapse; 
    border: 1px solid black;
    }

.alldatatables {
    text-align: right;
    font-family: 'Arial'; 
    font-size: 90%;   
    vertical-align: middle;
    border-collapse: collapse; 
    border: 1px solid black;
    padding: 5px 5px 5px 5px;
    color: blue;
    border-bottom: 1px solid #ddd;	
}

.alldatarows {
    text-align: right;
    font-family: 'Arial'; 
    font-size: 90%;   
    vertical-align: middle;
    border-collapse: collapse; 
    border: 1px solid black;
    padding: 5px 5px 5px 5px;
    color: black;    
    border-bottom: 1px solid #ddd;

}

.alldatacols {
    border-collapse: collapse; 
    border: 1px solid black;
    }




.odd {
 border-bottom: 1px solid #000;
 padding: 1px 1px 2px 2px;
 background-color: #ccf2ff;
}

.even {
 border-bottom: 1px solid #000;
 padding: 1px 1px 2px 2px;
 background-color: white;
}

@page {
/* Landscape orientation */
size: ledger landscape;

/* Put page numbers in the top right corner of each
   page in the pdf document. */
@bottom-right {
 content: "Page " counter(page) "of " counter(pages);
}
   margin-top:1cm;
   margin-left:1cm;
   margin-right:1cm;
   margin-bottom:1cm;
 
}

Visual Force :
  <apex:pageBlockSection columns="1" id="section8" title="Bound Terrorism & Cyber Information" showHeader="true" rendered="{!NOT(TerrorCyberSectionList.size == 0)}" > 
 
             <apex:outputPanel id="out8">
                <apex:actionstatus startText="loading...">
                    <apex:facet name="stop" >
                        <apex:outputPanel >
                         <apex:outputText style="font-style:italic;color:blue" value="Terrorism" />
                            <apex:dataTable id="dt8a"  styleClass="allPDFdatatables" headerClass="allPDFdatacols" columnClasses="allPDFdatacols" rowClasses="allPDFdatarows" value="{!TerrorCyberSectionList}" var="tc" rules="all" cellpadding="5" >
                            
                                <apex:column value="{!tc.Name}" headerValue="Contract"/>
                                <apex:column value="{!tc.Terror_Limit_Amount__c}" headerValue="Additional Limit Maiden Share"/>
                                <apex:column value="{!tc.Terror_Limit_Type__c}" headerValue="Limit Type"/> 
                                <apex:column value="{!tc.Terror_Limit_Description__c}" headerValue="Description (Terrorism)"/>
         
                            </apex:dataTable>  
                         <br></br>                           
                         <apex:outputText style="font-style:italic;color:blue" value="Cyber" /> 
                           <apex:dataTable id="dt8b" styleClass="allPDFdatatables" headerClass="allPDFdatacols" columnClasses="allPDFdatacols" rowClasses="allPDFdatarows" value="{!TerrorCyberSectionList}" var="tc" rules="all" cellpadding="5" >
                                <apex:column value="{!tc.Name}" headerValue="Contract"/>
                                <apex:column value="{!tc.Cyber_Limit_Amount__c}" headerValue="Additional Limit Maiden Share"/>
                                <apex:column value="{!tc.Cyber_limit_Type__c}" headerValue="Limit Type"/> 
                                <apex:column value="{!tc.Cyber_Limit_Description__c}" headerValue="Description (Cyber)"/>
                                                           
                            </apex:dataTable> 

                                                    
                        </apex:outputPanel>
                    </apex:facet>
                </apex:actionstatus>
                
            </apex:outputPanel>

 </apex:pageBlockSection>



 
I have a commandButton that call two actionfunctions the two actionfunctions call to methods that return a String, but one of the methods some time return null, and when the method return null the visualforce page is reloaded , I try putting a rerender attribute but is not working the visualforce page reload everything when the method return null, the button is "Exportar" this is my code:

<apex:page standardController="npe03__Recurring_Donation__c" extensions="ReporteCompromisosExportacionController" tabStyle="Reporte_Compromisos__tab">

    <script type="text/javascript">
        function loading(val) {
            //document.getElementById('{!$Component.theForm1.theBlock.theSection.theSectionItemTipo.typeCard}').value;
            if (val) {
                document.getElementById('contentLoading').style.display = 'block';
                document.getElementById('contentLoaded').style.display = 'none';
            } else {
                document.getElementById('contentLoading').style.display = 'none';
                document.getElementById('contentLoaded').style.display = 'block';
            }
        }
    </script>
    <apex:form id="theForm1">
        <apex:pageBlock title="Reporte Donaciones Recurrentes" id="theBlock">
            <apex:pageMessages id="errors" />
            
            <apex:actionFunction name="showbn" action="{!chooseCardType}" reRender="theSection,theSectionItemBanco,theSectionItemBlank" status="loading">
                <apex:param name="mediodePago" value="" />
            </apex:actionFunction>
            <apex:actionFunction name="showpn" action="{!showPreNotificacion}" reRender="theSection,theSectionItemBlank" status="loading">
                <apex:param name="nombreBanco" value="" />
            </apex:actionFunction>
            
            <apex:actionFunction name="generate" action="{!generateURL}" reRender="{!If(cards=='Visa','errors,buttons','')}" status="{!If(cards=='Visa','loading','')}"/>
            <apex:actionFunction name="disable" action="{!runUpdate}" reRender="errors,buttons" status="loading"/>
            <apex:actionFunction name="redirectPre" action="{!redirectPreURL}"/>
            <apex:actionFunction name="enable" action="{!enableExport}" reRender="buttons" status="loading"/>

            <apex:actionStatus id="loading" onstart="loading(true)" onstop="loading(false)" />

            <apex:pageblockSection id="theSection" title="Filtros de búsqueda">
                <apex:pageBlockSectionItem id="theSectionItemMedio" rendered="{!showFinancia}">
                    <apex:outputLabel value="Medio de Pago" for="medioCard" />
                    <apex:inputField value="{!Donation.Medio_de_Pago__c}" id="medioCard" onchange="showbn(this.value);"/>
                </apex:pageBlockSectionItem>

                <apex:pageBlockSectionItem id="theSectionItemTipo" rendered="{!showFinancia}">
                    <apex:outputLabel value="Tipo de Tarjeta" for="typeCard" />
                    <apex:selectList id="typeCard" multiselect="false" size="1" value="{!card}" disabled="{!!cardt}">
                        <apex:selectOptions value="{!cards}" />
                    </apex:selectList>
                </apex:pageBlockSectionItem>
                
                <apex:pageBlockSectionItem id="theSectionItemBanco" rendered="{!bank}">
                    <apex:outputLabel value="Entidad de Cobro" for="entidadCobro" />
                    <apex:selectList id="cobrador" multiselect="false" size="1" value="{!cobra}" onchange="showpn(this.value);">
                        <apex:selectOptions value="{!cobradores}" />
                    </apex:selectList>
                </apex:pageBlockSectionItem>
                
                <apex:pageBlockSectionItem id="theSectionItemBlank" rendered="{!bank}">
                    <apex:outputLabel value="Pre Notificación" for="preNotificacion" rendered="{!preNotificacion}"/>
                    <apex:inputField value="{!Donation.Pre_Notificado__c}" id="preNotificado" rendered="{!preNotificacion}"/>
                </apex:pageBlockSectionItem>
                
                <apex:pageBlockSectionItem id="theSectionItemDesde">
                    <apex:outputLabel value="Fecha Desde" for="fromDate" />
                    <apex:inputField value="{!Donation.npe03__Date_Established__c}" id="fromDate" />
                </apex:pageBlockSectionItem>

                <apex:pageBlockSectionItem id="theSectionItemHasta">
                    <apex:outputLabel value="Fecha Hasta" for="toDate" />
                    <apex:inputField value="{!DonationHasta.npe03__Date_Established__c}" id="toDate" />
                </apex:pageBlockSectionItem>

                <apex:pageBlockSectionItem id="theSectionItemSemana">
                    <apex:outputLabel value="Semana de Cobro" for="weekPay" />
                    <apex:selectList id="weekPay" multiselect="true" size="5" value="{!semana}" style="width:50px;">
                        <apex:selectOptions value="{!semanas}" />
                    </apex:selectList>
                </apex:pageBlockSectionItem>

                <apex:pageBlockSectionItem id="theSectionItemEstado">
                    <apex:outputLabel value="Estado" for="status" />
                    <!--  <apex:inputField value="{!npe03__Recurring_Donation__c.npe03__Open_Ended_Status__c}" id="status"/>  -->
                    <apex:selectList id="status" multiselect="true" size="3" value="{!estado}">
                        <apex:selectOptions value="{!estados}" />
                    </apex:selectList>
                </apex:pageBlockSectionItem>

                <!--  <apex:pageBlockSectionItem id="theSectionItemInStop" >
                    <apex:outputLabel value="En pausa" for="inStop"/>
                    <apex:inputField value="{!npe03__Recurring_Donation__c.En_Pausa__c}" id="inStop"/> 
                </apex:pageBlockSectionItem> -->
            </apex:pageblockSection>
            <div id="contentLoaded">
                <apex:pageblockSection id="buttons">
                    <apex:pageBlockSectionItem >
                        <apex:commandButton value="Buscar" action="{!runSearch}" reRender="grilla,debug,errors,buttons" status="loading"/>
                    </apex:pageBlockSectionItem>
                    <apex:pageBlockSectionItem >
                        <apex:commandButton value="Pre Visualizar" onclick="redirectPre();" oncomplete="enable();" disabled="{!!exportedPre}" />
                        <apex:commandButton value="Exportar" onclick="generate();" oncomplete="disable();" disabled="{!!exported}" />                     
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSection>
            </div>
            <div id="contentLoading" style="display: none;">
                <div style="text-align: center;">
                    <img src="/img/loading.gif" alt="Procesando..." />
                </div>
            </div>
            <br/>
            <apex:pageblockSection id="grilla" columns="1">
                <apex:pageBlockTable value="{!resultado}" var="c">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="Id Donación" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="Id" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.Id}" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="PSN" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="PSN__c" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.PSN__c}" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="Nombre Cuenta" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="AccountId" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.Nombre_Cuenta__c}" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="Nombre" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="Nombre__c" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.Nombre__c}" />
                    </apex:column>                  
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="Apellido" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="Apellidos__c" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.Apellidos__c}" />
                    </apex:column>                  
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="DNI" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="N_mero_de_Documento__c" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.N_mero_de_Documento__c}" rendered="{!c.N_mero_de_Documento__c!=null}"/>
                        <apex:outputField value="{!c.Account.N_Fiscal__c}" rendered="{!c.N_mero_de_Documento__c==null}"/>
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="Monto" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="Amount" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.Amount}" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="Tipo Tarjeta" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="Tipo_de_Tarjeta__c" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.Tipo_de_Tarjeta__c}" />
                    </apex:column>                  
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="Número Tarjeta" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="Numero_de_Tarjeta__c" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.Numero_de_Tarjeta__c}" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="Fecha Vencimiento" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="Fecha_de_Vencimiento__c" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.Fecha_de_Vencimiento__c}" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="Número Cuenta" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="Numero_de_Tarjeta__c" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.Numero_de_Cuenta__c}" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">
                            <apex:commandLink value="Frecuencia" action="{!toggleSort}" rerender="grilla,debug">
                                <apex:param name="sortField" value="Frecuencia__c" assignTo="{!sortField}" />
                            </apex:commandLink>
                        </apex:facet>
                        <apex:outputField value="{!c.Frecuencia__c}" />
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageblockSection>
            <apex:pageMessages />
        </apex:pageBlock>
    </apex:form>

</apex:page>
Hello,

I'm having an issue changing the Account owner on my production environment due to the following error:
 
19:54:05.0 (166999959)|CODE_UNIT_STARTED|[EXTERNAL]|Validation:Account:0011400001cjq0g
19:54:05.0 (167016943)|VALIDATION_RULE|03d30000000fi7e|Sponsored_Merchant
19:54:05.0 (167220072)|VALIDATION_FORMULA|AND( ISPICKVAL(  Merchant_Type__c , "SPONSORED" ), ISBLANK( IPSP__c ) )|IPSP__c=null , Merchant_Type__c=DIRECT
19:54:05.0 (167227568)|VALIDATION_PASS
19:54:05.0 (167277354)|CODE_UNIT_FINISHED|Validation:Account:0011400001cjq0g
19:54:05.0 (451026437)|CODE_UNIT_STARTED|[EXTERNAL]|01q140000000GUT|AccountTrigger on Account trigger event AfterUpdate for [0011400001cjq0g]
19:54:05.0 (452368872)|SYSTEM_MODE_ENTER|false
19:54:05.0 (453035097)|SOQL_EXECUTE_BEGIN|[245]|Aggregations:0|SELECT Id, OwnerId, IsRecurrence, RecurrenceActivityId FROM Task WHERE (IsClosed = FALSE AND (IsRecurrence = TRUE OR RecurrenceActivityId = '') AND AccountId = :tmpVar1)
19:54:05.0 (495584380)|SOQL_EXECUTE_END|[245]|Rows:1
19:54:05.0 (496143245)|DML_BEGIN|[251]|Op:Update|Type:Task|Rows:1
19:54:05.0 (570382518)|DML_END|[251]
19:54:05.0 (571909416)|SOQL_EXECUTE_BEGIN|[258]|Aggregations:0|SELECT OwnerId, Name, AccountId FROM Opportunity o WHERE o.AccountId = :tmpVar1
19:54:05.0 (575827437)|SOQL_EXECUTE_END|[258]|Rows:1
19:54:05.0 (576343858)|DML_BEGIN|[264]|Op:Update|Type:Opportunity|Rows:1
19:54:05.0 (591807513)|DML_END|[264]
19:54:05.0 (591887610)|EXCEPTION_THROWN|[264]|System.DmlException: Update failed. First exception on row 0 with id 0061400001BE4EZAA1; first error: INSUFFICIENT_ACCESS_OR_READONLY, insufficient access rights on object id: []
19:54:05.0 (592744047)|SYSTEM_MODE_EXIT|false
19:54:05.0 (592895440)|FATAL_ERROR|System.DmlException: Update failed. First exception on row 0 with id 0061400001BE4EZAA1; first error: INSUFFICIENT_ACCESS_OR_READONLY, insufficient access rights on object id: []
Class.AccountHandler.afterUpdate: line 264, column 1
Class.TriggerFactory.execute: line 153, column 1
Class.TriggerFactory.createHandler: line 29, column 1
Trigger.AccountTrigger: line 3, column 1
19:54:05.0 (592922730)|FATAL_ERROR|System.DmlException: Update failed. First exception on row 0 with id 0061400001BE4EZAA1; first error: INSUFFICIENT_ACCESS_OR_READONLY, insufficient access rights on object id: []
Class.AccountHandler.afterUpdate: line 264, column 1
Class.TriggerFactory.execute: line 153, column 1
Class.TriggerFactory.createHandler: line 29, column 1
Trigger.AccountTrigger: line 3, column 1
19:54:05.592 (592930478)|CUMULATIVE_LIMIT_USAGE

The error happens only for one Account record when I try to change the Owner of that Account record.

I do not have issues and do not receive the above error when I change the Owner for other account records.

Here is the code of the afterUpdate() method:
 
public void afterUpdate(SObject oldSo, SObject so) {
    if(Trigger.isUpdate) {

        // Cast the SObject to an Account
        Account newAccount = (Account)so;
        Account oldAccount = (Account)oldSo;

        List<Task> tasksList = new List<Task>([SELECT Id, OwnerId, IsRecurrence, RecurrenceActivityId FROM Task WHERE IsClosed=false AND (IsRecurrence = true OR RecurrenceActivityId = '') AND AccountId = :oldAccount.Id]);

        for (Task tl: tasksList) {
             for(Task to: tasksFromDatabase) {
                 if(tl.Id == to.Id) {
                    tl.OwnerId = to.OwnerId;
                    update tl;
                 }
             }
         }

        if(newAccount.OwnerId != oldAccount.OwnerId) {
            List<Opportunity> opportunityExists =
            [select OwnerId, Name, AccountId from Opportunity o
            where o.AccountId = :newAccount.Id];
            for (Opportunity opp : opportunityExists) {
                opp.OwnerId = oldAccount.OwnerId;
            }
            sObject[] sObjects = opportunityExists;
            update(sObjects);
        }
    }
}

Could you please advise what is the causing the error and help me find a solution.

Thank you
Hi Guys,
i am very close to developing a vf page on which i get a set of records from which i need to select "one and only one".
The challenges i faced are that i am able to select multiple records but not one. So tried to use radio button but that wouldn;t come for the save.
So pelase tell me how i can select single record and save it.
Below is my code and screenshot : 
<apex:page controller="wrapcontactlist">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
        $j = jQuery.noConflict();
        //$j = jQuery.noConflict();

   $j(document).ready(function() {

    alert('Inside function');
var last_valid_selection = null;
alert('Inside function1'+last_valid_selection);
         $j('#checkb').change(function(event) {
alert('Inside event function1'); // going till here but not below
            if ($j('#checkb').val().length > 1) {
						alert('Cannot choose! already oversized ID: fgbrt46456456546456cdfedf'+$j(this).val().length)
              $j(this).val(last_valid_selection);
            } else {
              last_valid_selection = $j(this).val();
            }
          });
        });
   

        /*$j(document).ready(function() {

          var last_valid_selection = null;

         $j('#checkb').change(function(event) {

            if ($j(this).val().length > 3) {
						alert('Cannot choose! already oversized ID: fgbrt46456456546456cdfedf'+$j(this).val().length)
              $j(this).val(last_valid_selection);
            } else {
              last_valid_selection = $(this).val();
            }
          });
        });*/
    </script>
    </head>
    
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="table"/>
            </apex:pageBlockButtons>
            <!-- In our table we are displaying the cContact records -->
            <apex:pageBlockTable value="{!contacts}" var="c" id="table">
                <apex:column >
                    <!-- This is our selected Boolean property in our wrapper class -->
                    
                        
                   
                            <apex:inputCheckbox value="{!c.selected}" id="checkb"/>

          
                           
                        
                    
                    
                </apex:column>
                <!-- This is how we access the contact values within our cContact container/wrapper -->
                <apex:column value="{!c.con.Name}" />
                <apex:column value="{!c.con.Email}" />
                <apex:column value="{!c.con.Phone}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

User-added image
 
This is a section of a table PDF VF page - I do not this section of the table to display if the value of DSP_eval__c.xvb5__c = "X".

                         <table border="1" cellspacing="0" width="100%" align="center" style="height:150 px; font-size:12px; font-weight:normal">
                          <tr style="text-align:left">                                      
                          <td style="text-indent:10px; font-weight:normal"> Skill 5: Supports the self direction of services. </td>                         
                          <td style="text-align:center; font-weight:normal ">{!DSP_eval__c.xvb5__c}</td>                         
                          </tr>                         
                          </table>
Hello guys,

We need to delete 2 Scheduled jobs from workbench through SOQL query as these jobs are not visible at from front end.
However when we try yo delete those jobs we are getting error 'INSUFFICIENT_ACCESS_OR_READONLY. Insufficient Access Rights On Object Id'
We are using below query in workbench: 

SELECT Id, CronJobDetail.Id, CronJobDetail.Name, CronJobDetail.JobType
FROM CronTrigger where CronJobDEtailID = '08aV0000006LlFTIA0' ORDER BY CreatedDate


PFB screenshot for error. What I need to to do to delete these jobs?
User-added image

Hi, I trying to create a visualforce page to insert OpportunityLineItems, but it's not working, when I click "Salvar" (save) nothing happens, anyone could help me please?

page:

<apex:page controller="ProdOpController">
    <apex:form >
        <apex:pageBlock title="Novo Produto da Oportunidade">
            <apex:pageBlockSection title="Informações do Produto">
                <apex:inputField value="{!prodop.OpportunityId}"/>
                <apex:inputField value="{!prodop.Quantity}"/>
                <apex:inputField value="{!prodop.UnitPrice}"/>
                <apex:selectList multiselect="false" size="1" value="{!prodop.Product2Id}">
                    <apex:selectOptions value="{!prodOptions}"/>
                </apex:selectList>
            </apex:pageBlockSection>
        <apex:pageBlockButtons >
            <apex:commandButton action="{!salvar}" value="Salvar"/>
        </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

controller:
 
public class ProdOpController {
    
    public OpportunityLineItem prodop{ get; private set; }
    
    public ProdOPController(){
        prodop = new OpportunityLineItem();
        System.debug('Entrei no construtor');
    }
    
    public PageReference salvar(){
        System.debug('Entrei em salvar');
        try{
            insert prodop;
        }
        catch(System.DMLException e){
        	System.debug('insert prodop falhou');
            System.debug(e);
            ApexPages.addMessages(e);
            return null;
        }
        PageReference redirectSuccess = new ApexPages.StandardController(prodop).view();
        return (redirectSuccess); 
    }

    public List<SelectOption> getProdOptions(){
        List<PricebookEntry> prods = Database.query(
        	'SELECT Id, name FROM PricebookEntry'
        );
        List<SelectOption> options = new List<SelectOption>();
        for(PricebookEntry p : prods){
            options.add(new SelectOption(p.Id, p.Name));
        }
        System.debug('listei as opcoes de produtos');
        return options;
    }
}

 
I'm getting above error message when I try to create child records based on the External Id of the Parent Record. Here is the scenario. Please note that both reference1 and reference2 are related to the same Master object (Master_record__c). And reference1 is Master-Detail relationship and reference2 is just a lookup to Master record
String aExtId = helper.createMasterRecord(param1, param2);//Master Record (Master_record__c) creates with the External Id Child_rec__c aRec = new Child_rec__c(); aRec.reference1__r = new Master_record__c(External_Id__c = aExtId); aRec.reference2__c = 'a2w2C0000005vaVQAQ'; objectsToInsert.add(aRec); //Same List has the Master record to be inserted too.
Here's what happens inside the createMasterRecord()
Master_record__c aMaster = new Master_record__c(); aMaster.Name = 'Test'; code.. code.. aMaster.External_Id__c = 'random text'; return aMaster.External_Id__c;
Any idea how to fix this?
Hi, 

We have a new user that is experiencing an issue that no one in their same team is facing. We have a custom object which has a button that redirects to send an email window. This issue pops up when this user clicks this custom button, no other user in the same profile/role is facing this problem. Why is this happening ? How can we fix this ? 

Error msg: 'This page isn't available in Salesforce Lightning Experience or Salesforce1.'

However other standard users can click that button and works perfectly for them in lightning. 

Thank you, 
  • November 02, 2016
  • Like
  • 0
Replace each query by schema describe call:
Replcae this:
//REPLACE THIS LINE
RecordType closedWonRecordType = [SELECT Id from RecordType WHERE SobjectType = 'Opportunity' AND Name = 'Closed Won
' LIMIT 1];

//FROM
Id closedWonRecordTypeId = Opportunity.getDescribe().getRecordTypeInfosByName().get('Closed Won').getRecordTypeId();
Hai,iam tried to create some custom object homepage in visualeforce page.i get some issues,please guide me how  to create that one
In the 'Getting Started with APEX Triggers' (http://goo.gl/5YJ01q) module, an error message appears when attempting the first example/exercise. 
 The instructions read: 
  • 1. In the Developer Console, click File | New | Trigger. (The menu path is actually File | New | APEX Trigger).
  • 2. Enter helloWorldTrigger for the trigger name, and then select Account for the sObject. ClickSubmit. (stet)
When clicking submit in step 2, an error message appears: "The Trigger "HelloWorldTrigger " is not a legal name." The parenthesis around HelloWorldTrigger are not entered in step 2. 

Work Around:  
In Setup go Develop | Apex Triggers
Launch the Dev Console (DC) from setup UI. 
Removed previous text from within the Query Editor tab which contained an invalid query, and was promtping an error message itself.
Continued with set 2, above. 

I was able to save the new trigger in the Dev Console. I then deleted it, closed the DC, and repeated the steps from the Trailhead exercise (where the DC was launched from Name | Dev Console, not Setup | Develop). I was then able to save the trigger without error. 

Take Away: it may have been the erronous text in the query editor, when the DC was launched from Name | DC. Subsequently adding erronous text back into the query editor, and repeating set 2 above did not throw a naming error the second time.  
 
Hi,
It is not a question, I share my experience because I spent hours on this...
on my visualforce page, chrome kept telling me (in the Javascript console):
XMLHttpRequest cannot load https://eu3.salesforce.com/_ui/common/request/servlet/JsLoggingServlet.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://c.eu3.visual.force.com' is therefore not allowed access.
Browsing the net, I didn't find info on this error.
At the end, It appears this was due to a call to the "alert" javascript box just before the call to an "<apex:actionFunction". See below,
Javascript is:
function jsRemoveLineItemCatBtn() {
alert( 'CURRENT ID ' + vLICInProgressNum );
afRemoveLineItemCatBtn( String(vLICInProgressNum) );
}
where afRemoveLineItemCatBtn is the name of my action function.
Since I commented the call to alert, I don't have the error message anymore...
Hope to help few to save time.
 
Hi ,
I have posted this to provide solution on custom buttons which actually does not follow the security model in Apex code developement.
I created a utility class which could be referenced on custom button to make sure whether the user who is edititng or accessing the particualr object is authorized to do or not. The code is posted below;

global class  RoleWisePermissionCheck {

   webService static Boolean checkUserPermissions (Id userId, Id oppownerid, Id oppid) {
   Set<ID> usersRolesHierachy = new Set<ID>();
   Boolean checkUserperm = false;
   usersRolesHierachy = getRoleSubordinateUsers(userId);
   List<User> lstUsers = new List<User>();
   List<Profile> lstProfiles = new List<Profile>();
   List<OpportunityTeamMember> lstOppTeamMembers = new List<OpportunityTeamMember>();
   lstUsers = [SELECT profileid from user WHERE id = :userId];
   if(lstUsers.size()>0)
   lstProfiles = [SELECT name from profile WHERE id = :lstUsers[0].profileid ];
   if(lstProfiles.size()>0) {
       if(lstProfiles[0].name == 'System Administrator' || userId == oppownerid) {
       checkUserperm = true;
       return checkUserperm;
       }
   }
   lstOppTeamMembers  = [select id, Userid,OpportunityAccessLevel from OpportunityTeamMember where Opportunityid = :oppid];
   for(OpportunityTeamMember o :lstOppTeamMembers) {
       if(o.Userid!=null && userId!=null){
           if(o.Userid == userId && o.OpportunityAccessLevel == 'Edit') {
               checkUserperm = true;
               return checkUserperm;
           }
           
       }
   }
   
   System.debug('hiiiiiii'+usersRolesHierachy);
   if(usersRolesHierachy!=null && usersRolesHierachy.size()>0){
   For(ID ids : usersRolesHierachy){
       if(ids == oppownerid)
       checkUserperm = true;
   }
   
   }
    return checkUserperm;  
  
  }    

   public static Set<ID> getRoleSubordinateUsers(Id userId) {
    Id roleId = null;
    List<User> lstuserswdrole = new List<User> ();
    Map<Id,User> users = new Map<Id,User>();
    if(userId!=null) {
    lstuserswdrole = [select UserRoleId from User where Id = :userId];
    if(lstuserswdrole.size()>0)
    roleId = lstuserswdrole[0].UserRoleId;
    if(roleId!=null) {
    // get all of the roles underneath the user
    Set<Id> allSubRoleIds = getAllSubRoleIds(new Set<ID>{roleId});
    // get all of the ids for the users in those roles
    users = new Map<Id, User>([Select Id, Name From User where 
    UserRoleId IN :allSubRoleIds]);
    // return the ids as a set so you can do what you want with them
    }
    }
    System.debug('hiiiiiii'+users);
    if(users.size()>0)
    return users.keySet();
    else
    return null;

  }

  public static Set<ID> getAllSubRoleIds(Set<ID> roleIds) {

    Set<ID> currentRoleIds = new Set<ID>();
    // get all of the roles underneath the passed roles
    for(UserRole userRole :[select Id from UserRole where ParentRoleId 
      IN :roleIds AND ParentRoleID != null])
    currentRoleIds.add(userRole.Id);
    // go fetch some more rolls!
    if(currentRoleIds.size() > 0)
      currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds));

    return currentRoleIds;

  }

}
Well guys my code is 88% covered but i want to increase more this value, but i'm stucked in some points for example i would like to know how can i test the message error of my method isEmpty,and how to test the insert into the list of my doSave method. if someone could give me example i would be very thankful! 

My apexClass
public with sharing class PaymentManager {

	/*
	 * PRIVATE VARIABLES
	 */
	 
	 private Map<Id, MetodoPagamentoEndereco__c> mapPaymentsOriginal;

	/*
	 * PUBLIC VARIABLES
	 */
	 
	public String title											{get;set;}

	public Payment_cls paymentAux								{get;set;}

	public List<Payment_cls> listPaymentsAddress				{get;set;}
	
	public Integer selectedPrincipalId							{get;set;}
	
	public Integer paymentIdSelected 							{get;set;}
	
	
	/*
	 * SUBCLASSES
	 */
	 
	private class Payment_cls {
		public Integer id										{get;set;}			
		public MetodoPagamentoEndereco__c payment				{get;set;}
		public boolean isDeleted								{get;set;}
		public Payment_cls() {
			payment = new MetodoPagamentoEndereco__c();
		}
	}
	
	
	/*
	 * CONSTRUCTOR
	 */
	public PaymentManager(){
		title = 'Métodos de Pagamento';
		paymentAux = new Payment_cls();
	}
	
	/*
	 * PRIVATE METHODS
	 */
	 
	 /*
	  * este método identifica se já exsite um método de pagamento cadastrado para o endereço.
	  */
	 private boolean hasMethod(String pMethodId){
	 	boolean result = false;
	 	for (Payment_cls iPayment: listPaymentsAddress){
	 		if (iPayment.payment.MetodoPagamento__c == pMethodId) {
	 			result = true;
	 			break;	
	 		}
		}
	 	return result;
	 }
	 
	 	

	private boolean isEmpty(list<Payment_cls> pList){
		boolean result = false;
		
		if (pList.isEmpty()) {
			ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR,'É necessårio informar ao menos um método de pagamento para prosseguir.'));	
			result = true;
		}
		
		return result;
	}
	 
	 	
	
	private boolean existingPaymentIsValid(MetodoPagamentoEndereco__c pMetodo){
		boolean result = true;
		MetodoPagamentoEndereco__c old = mapPaymentsOriginal.get(pMetodo.Id);
		
		if (pMetodo.Inicio__c < old.Inicio__c) {
			pMetodo.Inicio__c.addError('Não é permitido alterar a data de início para uma data anterior a previamente cadastrada: ' + old.Inicio__c.format());
			result = false;
		}
		else
			result = finalDateIsMajor(pMetodo);
		
		return result;
	}
	 
	 	

	private boolean newerPaymentIsValid(MetodoPagamentoEndereco__c pMetodo){
		boolean result = true;
		
		if (pMetodo.Inicio__c < Date.Today()) {
			pMetodo.Inicio__c.addError('Não é permitido o cadastramento de um novo método de pagamento com data retroativa.');
			result = false;
		}
		else
			result = finalDateIsMajor(pMetodo);
		
		return result;
	}
	

	private boolean finalDateIsMajor(MetodoPagamentoEndereco__c pMetodo){
		boolean result = true;
		
		if ( pMetodo.Fim__c != null){
			if (pMetodo.Inicio__c > pMetodo.Fim__c) {
				pMetodo.Inicio__c.addError('A data de início não pode ser maior que a data final.');
				result = false;
			}
		}
		return result;
	}
	 
	 
	
	 private Integer getMajorId() {
		Integer retorno = 0;
		for (Payment_cls icPayment : listPaymentsAddress) {
			if (icPayment.id > retorno) {
				retorno = icPayment.id; 
			}
		}
		return retorno + 1;
	}
	 
	 
	 /*
	  * PUBLIC METHODS
	  */
	
	public void loadPaymentsByAddress(Endere_o_Relacionado__c pEndereco) {

		if (listPaymentsAddress == null) {

			listPaymentsAddress = new List<Payment_cls>();
			
			if (Functions.isNotEmptyOrNull(pEndereco.Id)) {
				
				list<MetodoPagamentoEndereco__c> listPaymentsOriginal = [
						SELECT Id, Name, Inicio__c, Fim__c, Principal__c, MetodoPagamento__c
						  FROM MetodoPagamentoEndereco__c
						 WHERE Endereco__c = :pEndereco.Id
					  ORDER BY Name
				];
				
				if (!listPaymentsOriginal.isEmpty()) {
				
					Integer i = 1;
					mapPaymentsOriginal = new Map<Id,MetodoPagamentoEndereco__c >();
					for (MetodoPagamentoEndereco__c iPayment : listPaymentsOriginal) {
						mapPaymentsOriginal.put(iPayment.Id, iPayment.clone(true, true, true, true)); 
						Payment_cls cPayment = new Payment_cls();
						cPayment.payment = iPayment;//.clone(true, true, true, true);
						cPayment.id = i;
						cPayment.isDeleted = false;
						listPaymentsAddress.add(cPayment);
						//setando o Id do método pagamento selecionado como principal.
						if (cPayment.payment.Principal__c) {
							selectedPrincipalId = cPayment.Id;
						}
						i++;
					}
				}
			}
		}
	}


	public PageReference deletePayment() {
		for (Payment_cls icPayment : listPaymentsAddress) {
			if (icPayment.id == paymentIdSelected) {
				icPayment.isDeleted = !icPayment.isDeleted;
				break;  
			}
		}
		return null;
	}
	
	

	public PageReference savePaymentInList() {
		
		paymentAux = new Payment_cls();
		
		String methodPaymentId = Apexpages.currentPage().getParameters().get('methodPaymentId'); 
		String methodPaymentName = Apexpages.currentPage().getParameters().get('methodPaymentName'); 
		
		if (hasMethod(methodPaymentId)) {
			ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR,'O método de pagamento "' + methodPaymentName + '" já está cadastrado.'));
		} 
		else {		
			paymentAux.payment = new MetodoPagamentoEndereco__c(
				Inicio__c = Date.today(),
				Principal__c = true,
				MetodoPagamento__c = methodPaymentId,
				Name = methodPaymentName
			);
			
			Payment_cls cPayment = new Payment_cls();
			cPayment = paymentAux;
			//cPayment.payment.Principal__c = listPaymentsAddress.isEmpty();
			cPayment.id = getMajorId();
			cPayment.isDeleted = false;
			listPaymentsAddress.add(cPayment);			
			
			selectedPrincipalId = cPayment.id ;
		}
		return null;
	}

	

	public void doSelectPrincipal() {
		for (Payment_cls icPayment : listPaymentsAddress) {
			boolean isPrincipal = icPayment.id == selectedPrincipalId;
			icPayment.payment.Principal__c = isPrincipal;
		}
	}
	
	

	public boolean isValid(){
		boolean result = true;
		
		result = !isEmpty(listPaymentsAddress);
		if (result) {
			list<Payment_cls> listWithoutDelete = new list<Payment_cls>(); 
			for (Payment_cls iPayment :listPaymentsAddress){
				if (!iPayment.isDeleted) {
					listWithoutDelete.add(iPayment);
					
					if (Functions.IsNotEmptyOrNull(iPayment.payment.Id)){
						if (!existingPaymentIsValid(iPayment.payment))
							result = false;
					}
					else {
						if (!newerPaymentIsValid(iPayment.payment))
							result = false;
					}
					
				}
			}
			
			if (result )
				result = !isEmpty(listWithoutDelete);
		} 
		
		return result;
	}
	

	
	public void doSave(Endere_o_Relacionado__c pEndereco) {
		
		if (pEndereco != null && Functions.isNotEmptyOrNull(pEndereco.Id)) {
			List<MetodoPagamentoEndereco__c> auxListInsertPayment = new List<MetodoPagamentoEndereco__c>();
			List<MetodoPagamentoEndereco__c> auxListUpdatePayment = new List<MetodoPagamentoEndereco__c>();
			List<MetodoPagamentoEndereco__c> auxListDeletePayment = new List<MetodoPagamentoEndereco__c>();
			
			for (Payment_cls cPayment : listPaymentsAddress) {
				if (!Functions.isNotEmptyOrNull(cPayment.payment.Id)) {
					if (!cPayment.isDeleted) {
						cPayment.payment.Endereco__c = pEndereco.Id;
						auxListInsertPayment.add(cPayment.payment);
					}
				}
				else {
					if (cPayment.isDeleted) {
						auxListDeletePayment.add(cPayment.payment);
					} 
					else {
						auxListUpdatePayment.add(cPayment.payment);
					}		
				}						
			}
			
			if (!auxListDeletePayment.isEmpty()) {
				delete auxListDeletePayment;
			}
			if (!auxListUpdatePayment.isEmpty()) {
				update auxListUpdatePayment;
			}
			if (!auxListInsertPayment.isEmpty()) {
				insert auxListInsertPayment;
			}
		}
	}
}
My testClass
private class PaymentManager_tst {

    static testMethod void myUnitTest() {
    	
    	//istancia do construtor
        PaymentManager payment = new PaymentManager();
		List<MetodoPagamentoEndereco__c> MetodoPagamentoEnderecoVazio = new List<MetodoPagamentoEndereco__c>();
		
        Endere_o_Relacionado__c endereco = new Endere_o_Relacionado__c(
        		Name = 'teste'
        );
        insert endereco;
        
        
        MetodoPagamento__c metodoPagamento = new MetodoPagamento__c(
        	Codigo__c = 'teste',
        	Fim__c = Date.valueOf(Datetime.now().addDays(-10)),
        	Inicio__c = Date.valueOf(Datetime.now().addDays(-9)),
        	Observacao__c = 'teste de Observação'
        
        );
        insert metodoPagamento;
        
        MetodoPagamentoEndereco__c metodoPagamentoEndereco = new MetodoPagamentoEndereco__c(
        	Name = 'Teste',
        	Endereco__c = endereco.Id,
        	Fim__c = Date.valueOf(Datetime.now().addDays(-10)),
        	Inicio__c = date.today(),
        	Principal__c = true,
        	MetodoPagamento__c = metodoPagamento.Id
        );
        insert metodoPagamentoEndereco;

  		//Métodos publicos do construtor
        payment.loadPaymentsByAddress(endereco);
        payment.doSave(endereco);
        payment.savePaymentInList();
        payment.savePaymentInList();
        payment.isValid();
        payment.doSelectPrincipal();
        payment.deletePayment(); 
    }

}

 
Hi,

I was trying to synchronize on real time, my Salesforce account with SQL Server through the informatica platform, but looks like it works very well for insertions and updates, but I wanted to implement the deletion as well. But I couldnt found the option, below I attached an image to clarify what options I have available.
 
Any alternative way to synchronize using outbound messages?

Options
   
I will apreciate any help!
Thanks a lot !
 
For anyone who may have faced the same task, here is a sample code for displaying filtered tasks and events to display in Account details.
As you may see, I've filtered the results via SOQL, you may extend the code to improve or anything else :)
I used a workaround for reading the events, because they are not readable via the 15 digits AccountId but with the 18 digit once. Crazy, but it works. All of you may correct me, if this may not be usable in future.

1) Add a apex class:
public with sharing class RelatedActivitesTest {
public List<Task> tasksLimited {get;set;}
public List<Event> eventsLimited {get;set;}
public List<Contact> conts {get;set;}
public RelatedActivitesTest(ApexPages.StandardController con){
conts = [SELECT id FROM Contact WHERE AccountId =:ApexPages.currentPage().getParameters().get('id')];
tasksLimited= [select id,activitydate,createdbyid,description,subject,whoid,type,ownerid from task
where (
accountid=: ApexPages.currentPage().getParameters().get('id') or
WhoId in :conts
) and
subject not in ('Rechnung per E-Mail','Rechnung erstellt','Box-Austausch erstellt','Support angelegt','Gutschrift erstellt','Lizenzdatei per E-Mail','Webroot-Lizenzzertifikat per E-Mail','Teilgutschrift erstellt','PreSales angelegt','Angebot per E-Mail')
order by activitydate desc limit 1000];
// Used convertID to get the external url repesantation of Account Id, which helps me getting all events. Internal Ids won't work somehow.
eventsLimited= [select id,activitydate,createdbyid,description,subject,whoid,type,ownerid,whatid FROM Event
WHERE (
WhatId =:convertID(ApexPages.currentPage().getParameters().get('id')) or
WhoId =:convertID(ApexPages.currentPage().getParameters().get('id')) or
AccountId =:convertID(ApexPages.currentPage().getParameters().get('id')) or
WhoId in :conts
) and
subject not in ('Rechnung per E-Mail','Rechnung erstellt','Box-Austausch erstellt','Support angelegt','Gutschrift erstellt','Lizenzdatei per E-Mail','Webroot-Lizenzzertifikat per E-Mail','Teilgutschrift erstellt','PreSales angelegt','Angebot per E-Mail')
order by activitydate desc limit 1000];
}
public static String convertID(String id){
if(id.length() == 18) return id;
String suffix = '';
for(Integer i=0;i<3;i++){
Integer flags = 0;
for(Integer j=0;j<5;j++){
String c = id.substring(i*5+j,i*5+j+1);
if(c.compareTo('A') >= 0 && c.compareTo('Z') <= 0){
flags += 1 << j;
}
}
if (flags <= 25) {
suffix += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.substring(flags,flags+1);
}else suffix += '012345'.substring(flags-26,flags-26+1);
}
return id+suffix;
}
}


Create a visual force page:
<apex:page standardController="Account" extensions="RelatedActivitesTest" tabStyle="Account">
<apex:pageBlock title="Filtered Events">
<apex:outputPanel layout="block" style="overflow:auto;width:100%;height:200px">
<apex:dataTable value="{!eventsLimited}" var="eventLimited" cellpadding="4" bgcolor="white" rowClasses="even,odd">
<apex:column headerValue="Subject">
<apex:outputLink value="/{!URLFOR(eventLimited['id'])}">{!eventLimited.subject}</apex:outputLink>
</apex:column>
<apex:column headerValue="Description">
<apex:outputtext value="{!LEFT(eventLimited.description, 150)}" />
</apex:column>
<apex:column value="{!eventLimited.whoid}" headerValue="Member" />
<apex:column value="{!eventLimited.type}" headerValue="Type" />
<apex:column value="{!eventLimited.activitydate}" headerValue="Activity Date" />
<apex:column value="{!eventLimited.ownerid}" headerValue="Assigned To" />
</apex:dataTable>
</apex:outputPanel>
</apex:pageBlock>
<apex:pageBlock title="Filtered Tasks">
<apex:outputPanel layout="block" style="overflow:auto;width:100%;height:200px">
<apex:dataTable value="{!tasksLimited}" var="taskLimited" cellpadding="4" bgcolor="white" rowClasses="even,odd">
<apex:column headerValue="Subject">
<apex:outputLink value="/{!URLFOR(taskLimited['id'])}">{!taskLimited.subject}</apex:outputLink>
</apex:column>
<apex:column headerValue="Description">
<apex:outputtext value="{!LEFT(taskLimited.description, 150)}" />
</apex:column>
<apex:column value="{!taskLimited.whoid}" headerValue="Member" />
<apex:column value="{!taskLimited.type}" headerValue="Type" />
<apex:column value="{!taskLimited.activitydate}" headerValue="Activity Date" />
<apex:column value="{!taskLimited.ownerid}" headerValue="Assigned To" />
</apex:dataTable>
</apex:outputPanel>
</apex:pageBlock>
</apex:page>


The visualforce page is connected to Account so you can add it to the Account view in your pagelayout.
If you want to change the filter, just change them to fit your needs.

Anyway, if you like my first post, give me a "like".

Thanks
Thimo
 
  • November 26, 2014
  • Like
  • 6
Hi All
FORCCE.COM DEVELOPER GUIDE(Advanced Programming Techniques for cloud computing) chapter 2:page no:46,Bullet point 6.. we need to get the "Location.csv" file from code share project.Unable to locate the project in the Code Share.
Even  Mr.kumar(skr00) provided the link 
http://wiki.developerforce.com/page/Developers_Guide_Load_Instructions   .In that link zip code is not downloading. please help me.
Here is the code....Image is not displaying

<apex:page controller="Task_Picklist_onChange">
<apex:form id="show">
  <apex:pageblock >
  <apex:pageblockSection >
      <apex:outputPanel >
          <apex:selectList value="{!colors}" size="1">
              <apex:actionSupport event="onChange" action="{!display}" reRender="show" />
              <apex:selectOptions value="{!images}"/>
          </apex:selectList>
      </apex:outputPanel>
  </apex:pageblockSection>
  </apex:pageblock>
  <apex:outputPanel >
  <apex:image rendered="{!colors = 'Green'}" value="{!$Resource.Green}" width="200" height="200"/>
  <apex:image rendered="{!colors = 'Red'}" value="{!$Resource.Red}" width="200" height="200"/>
  <apex:image rendered="{!colors ='Yellow'}" value="{!$Resource.Yellow}" width="200" height="200"/>
  <apex:image rendered="{!colors ='Orange'}" value="{!$Resource.Orange}" width="200" height="200"/>
  </apex:outputPanel>
</apex:form>
</apex:page>



public with sharing class Task_Picklist_onChange {

    String Color;
   
    public PageReference display() {
        return null;
    }

    public String images { set; }
    
    public list<selectoption> getimages() {
    
        list<selectoption> image = new list<selectoption>();
        image.add(new selectoption('None','No'));
        image.add(new selectoption('Green','Green'));
        image.add(new selectoption('Red','Red'));
        image.add(new selectoption('yellow','Yellow'));
        image.add(new selectoption('Orange','Orange'));
        return image;
    }

    public String colors { get; }
    
    Public String setcolors(String colors) {
    System.debug(colors);
    color = colors;
    return color;
}
}
It is a salesforce standard functionality that when two objects are in a Master-detail relatonship with each other then if the Master record is deleted, all the related child records get delted automatically. However, what if we have a vice-versa situation? i.e. when a child record is deleted then the Master record without any child should also get deleted. This can be achieved by a trigger!! :)

Below is the code for the same. (Note: this code does not work for deleting records in bulk. Will be soon posting that as well. Also we need to have a unique key on both the objects)

if(Trigger.isAfter){
            if(Trigger.isDelete){
 
                List<ChildObjName__c> IdSetC = new List<ChildObjName__c>(); 
                List<MasterObjName__c  IdSetM = new List<MasterObjName__c>();
                Set<Id> IdSet = new Set<Id>();
               
                for(ChildObjName__c Cobj : Trigger.Old){
                     IdSet.add(Cobj.RelationshipName__c);
                     }
                List<MasterObjName__c> MobjLst = new List<MasterObjName__c>( [select id from MasterObjName__c where id =:IdSet]);
   
                    IdSetM=[select KeyField__c from MasterObjName__c where id=:IdSet];
                    IdSetC = [select id  from ChildObjName__c where KeyField__c =:IdSetM[0].KeyField__c];
   
                    if (IdSetC.size()==0)
                        {
                            delete MobjLst;
                        }
                    }
                } 

Solution by Abinash Sahoo and Srishti Goyal
  • October 22, 2014
  • Like
  • 1
I work in a Salesforce consultant team and often, when we need to sync objects with an external service, our developpers run in some data consistency problem, governor limit issue and all kind of pretty hard to resolved. 

I wrote an article this morning one way one we solve a customer need, I guess it can be of some help to those of you having simmilar issues :