• Vishal Negandhi 16
  • NEWBIE
  • 259 Points
  • Member since 2015
  • Consultant
  • Deloitte USI


  • Chatter
    Feed
  • 7
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 75
    Replies
Hi,

Could you please help me on changing the below trigger (which is written by Sandeep sankhla) , so that Plan__c status will be changed based on Account. That is if Account status is Active, then Plan__ c status should be Active, if Account status is InActive, then Plan__ c status should be InActive, if Account status is null, then Plan__ c status should be null.

Here
1. Account and Plan objects with many to many relationship and Accountplan as a Junction Object
2. Account obj with status field Active and inactive.
3. and Plan obj with status field Active and inactive

Trigger AccountTrigger on Account(After Update)
{
    set<Id> setAccIds = new set<Id>();
    list<Plan__c> lstPlanToUpdate = new list<Plan__C>();
    
    
    for(Id objAcc : trigger.newmap.Keyset())
    {
        if((trigger.newmap.get(objAcc).Status__c == 'InActive')  &&(trigger.newmap.get(objAcc).Status__c != trigger.oldMap.get(objAcc).Status__c))
        {
            setAccIds.add(objAcc);
        }
    }
    
    for(AccountPlan__c objAP : [Select Id, Plan__c, Account__c from AccountPlan__c where Account__c IN :setAccIds])
    {
            Plan__c objPlan = new Plan__c(Id = objAP.Plan__c);
            objPlan.Status__C = 'InActive';
            lstPlanToUpdate.add(objPlan);
    }
    
    update lstPlanToUpdate;

}

Thank You
Hi, 
The following apex visualforce page and the controller retrieves the response which is getting captured in the debug log but does not get displayed on the vf page.

Apex Controller
============
public class BankDetailsController {
    
    public Id accId {get;set;}
    public Account acc {get;set;}
    public String accname {get; set;}
    public String Response {get; set;}
    public AsyncSoapSforceComSchemasClassGetbankdet.getBankDetailsResponse_elementFuture resp;
    public Object startAsyncCall() 
    {
         Account acc =  [select Name from Account where Id =: ApexPages.currentPage().getParameters().get('id')];
        Continuation con = new Continuation(60);
        con.ContinuationMethod = 'processResponse';
        
        //string accname = 'GoGlobalStrategies';
        partnerSoapSforceCom.Soap myPartnerSoap = new partnerSoapSforceCom.Soap(); 
        partnerSoapSforceCom.LoginResult partnerLoginResult = myPartnerSoap.login('somnath.paul4@cognizant.com', '**********');
        soapSforceComSchemasClassGetbankdet.SessionHeader_element webserviceSessionHeader=new soapSforceComSchemasClassGetbankdet.SessionHeader_element();
        webserviceSessionHeader.sessionId = partnerLoginResult.sessionId;
       // soapSforceComSchemasClassGetbankdet.GetBankDetailsofAccount getBankdet=new soapSforceComSchemasClassGetbankdet.GetBankDetailsofAccount();
        //getBankdet.SessionHeader=webserviceSessionHeader;*/
         AsyncSoapSforceComSchemasClassGetbankdet.AsyncGetBankDetailsofAccount asyngetbnkdet = new AsyncSoapSforceComSchemasClassGetbankdet.AsyncGetBankDetailsofAccount();
        
        asyngetbnkdet.SessionHeader = webserviceSessionHeader;
        system.debug('session header'+ asyngetbnkdet.SessionHeader);
        resp = asyngetbnkdet.beginGetBankDetails(con, acc.Name);
        system.debug('resp from action'+ resp);
        return con;
    }
    public Object processResponse()
    {
        Response = resp.getValue();
        system.debug('Response from get Value'+ Response);
        return null;
    }
        
}

VF Page
========
<apex:page controller="BankDetailsController">
     <apex:form >
   <apex:pageBlock >
         <apex:pageBlockSection >
               Congratulations {!$User.FirstName}
             Following are the Bank Details:
                   <apex:commandButton value="Get Bank Details" action="{!startAsyncCall}" reRender="Response"/>
       </apex:pageBlockSection>
  </apex:pageBlock>
  </apex:form>
    <apex:outputText value ="{!Response}"/>
</apex:page>


Can any body please reply what went wrong in the VF page. 
I am trying to take whoever the primary user is in an opportunity's contact roles and populate a Lookup(user) field with this person but need a little help.  This is what I have but i am missing some understanding of contactrole and user's id relationship.  How would I accomplish this?
 
trigger UpdateOpportunityContact on Opportunity (after update, after insert) {
    List<OpportunityContactRole> contactRoles = new List<OpportunityContactRole>();
    
    for( Opportunity acc : [ Select Id, (SELECT OpportunityId,IsPrimary,ContactId  FROM OpportunityContactRoles) FROM Opportunity ])
    {
        contactRoles.addALL(acc.OpportunityContactRoles);
    }
    for(Opportunity opp : trigger.new)
    {
    for(OpportunityContactRole role : contactRoles)
    {
        if(role.IsPrimary)
        {
            opp.Primary_Contact__c = new User(ContactId = role.ContactId);
            upsert opp.Primary_Contact__c;
        }
    }
    }

}

 
  • November 05, 2015
  • Like
  • 0
Hi
What is the purpose of the "immediate= true"  and immediate= false in salesforce.please tell me explanation
Hi Guys,
I have wrote a vf page which is used to display input fields based on LeadSource. If LeadSource == 'web' then it should dispaly Description. But below code is not working..
Help me regarding this. Thank You

<apex:page standardController="Contact">
    <apex:form >
        <apex:pageBlock title="Enter Contact Information">
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!Save}" />
            
            </apex:pageBlockButtons>
            <apex:pageBlockSection columns="1">
                <apex:inputField value="{!Contact.LastName}" />
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Lead Source"/>
                    <apex:actionRegion >
                    <apex:inputField value="{!Contact.LeadSource}" >
                        <apex:actionSupport event="onChange" reRender="ajaxrequest" />
                        </apex:inputField>
                    </apex:actionRegion>
               
                </apex:pageBlockSectionItem>
            
            </apex:pageBlockSection>
        
            <apex:outputPanel id="ajaxrequest">
                <apex:pageBlockSection rendered="{!Contact.LeadSource=='Web'}">
                    <apex:inputField value="{!Contact.Description}"/>
  
                </apex:pageBlockSection>
                <apex:pageBlockSection rendered="{!Contact.LeadSource=='Phone Inquiry'}">
                <apex:inputField value="{!Contact.Phone}"/>
                   </apex:pageBlockSection>
                </apex:outputPanel>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Dear Folks,

I'm new bee to salesforce and please help to get me a sample code if possible, as I didn't find it anywhere.

Requirement: I have picklist filed with 2 values (val 1, Val2)
Scenario (trigger):

If (picklist value = 'Val1') {
 code here...
}

But I encounter bellow error, can you please suggest.
Error: Compile Error: Comparison arguments must be compatible types: Schema.SObjectField, String at line 5 column 12
 
Hello folks, 

Today we were trying to work on a utility that will list out all references to a field. This is intented to help the business to analyze a field before they plan to update/delete it. 

What we are trying to achieve?
- Once the user selects an object and one of its fields, we want to list out all possible components where the selected field is referenced. 

What were we able to achieve, using what?
- We first tried the Standard SOQL approach and queried objects such as ApexClass, ApexComponent, ApexPage and ApexTrigger : this helped us to find out references of a field in the code by scanning their body/markup. 
- We then thought of utilizing the Tooling API that has a SOSL feature, using which we were able to retreive all the codes where the field was referenced. 
Code snippet:
/services/data/v34.0/tooling/search/?q=FIND{BillingCity}

This gives me a list of all code where there is "BillingCity" referred. 

However, none of the approaches has helped us to touch other components such as:
- formula field
- report filters
- workflow field updates

Wanted to understand how do we get around this?
I know this is possible using Tooling API but then if I end up making one http callout for each component then I am going to make a lot of callouts. 
Is there something I am missing here? 
Need some guidance around this. 

Many thanks in advance!
Hello Experts,

We are using external objects in our salesforce instance and it works fine. However, we use a VF page to display the data in these objects for grouping. Now, we do not use any custom connector so every time we run a SOQL on the external object, there's a callout made to the system and data fetched. 

How do we capture this in test classes?
We tried a few approaches like
     - mock callouts but it doesn't work for this case.  
     - entering dummy data in the external object but that's not possible. 

Code snippet below:
externalSalesHistoryList = [select ExternalId, some_other_fields from CUSTOMER_SALES_HISTORY__x where SAP_CUSTOMER_NUMBER__c =:currentAccountRecord.SAP_CUSTOMER_NUMBER__c order by PRODUCT_TYPE__c, PRODUCT_LINE__c LIMIT : Limits.getLimitQueryRows()- Limits.getQueryRows()];

This is the query and this is when the salesforce sends out a callout. Now, everytime this code runs from a test class - it returns no data. 

We have some how managed to get a good coverage using Test.isRunningTest() method, but would like to understand if there's a better way of handling this. 
 
hai all 
i need a write dynamically add a pagelayouts to the profile through apex code using vfpage also
how can i do that
Can somebody explain what are the scenarios for both and how to implement them:
1. Calling controller method from JavaScript
2. Calling Javascript Function from controller
Hi,

Could you please help me on changing the below trigger (which is written by Sandeep sankhla) , so that Plan__c status will be changed based on Account. That is if Account status is Active, then Plan__ c status should be Active, if Account status is InActive, then Plan__ c status should be InActive, if Account status is null, then Plan__ c status should be null.

Here
1. Account and Plan objects with many to many relationship and Accountplan as a Junction Object
2. Account obj with status field Active and inactive.
3. and Plan obj with status field Active and inactive

Trigger AccountTrigger on Account(After Update)
{
    set<Id> setAccIds = new set<Id>();
    list<Plan__c> lstPlanToUpdate = new list<Plan__C>();
    
    
    for(Id objAcc : trigger.newmap.Keyset())
    {
        if((trigger.newmap.get(objAcc).Status__c == 'InActive')  &&(trigger.newmap.get(objAcc).Status__c != trigger.oldMap.get(objAcc).Status__c))
        {
            setAccIds.add(objAcc);
        }
    }
    
    for(AccountPlan__c objAP : [Select Id, Plan__c, Account__c from AccountPlan__c where Account__c IN :setAccIds])
    {
            Plan__c objPlan = new Plan__c(Id = objAP.Plan__c);
            objPlan.Status__C = 'InActive';
            lstPlanToUpdate.add(objPlan);
    }
    
    update lstPlanToUpdate;

}

Thank You
how can i call relationship object fields in trigger?
Hi,

I have created a custom object named Project_Sheet__c, within that object I have a lookup field to the associated Opportunity.
I want to display a list of the opportunity line items on the Project Sheet page layout.
I'm new to Apex and VF, so spologies if this is an easy thing and I've gone about it all wrong.
The code is compiling ok, but I'm getting the following message on the page 
Content cannot be displayed: SObject row was retrieved via SOQL without querying the requested field: Project_sheet__c.Project_sheet_Opportunity__r

I've tried creating a formula field that returns the OpportunityID, and used that in the query instead, but the error message just changes it's reference to the new field instead.
Any help would be gratefully appreciated.

I have the following for my controller and VF page:

Controller:
public class ProjectSheetOpportunityProductsAP {
    public Project_sheet__c custObj;
        
    public ProjectSheetOpportunityProductsAP(){
                   }
    
    public ProjectSheetOpportunityProductsAP(ApexPages.StandardController controller){
        custObj= (Project_sheet__c)controller.getRecord();
           }
    
    public List<OpportunityLineItem> getOppProducts(){
        List<OpportunityLineItem> lstOLI = [SELECT Quantity,PriceBookEntry.Name FROM OpportunityLineItem WHERE OpportunityID =: custObj.Project_Sheet_Opportunity__r.ID];
        return lstOLI;
    }
    }

VF:
<apex:page standardController="Project_Sheet__c" extensions="ProjectSheetOpportunityProductsAP" showHeader="false" sidebar="false">
    <apex:pageBlock title="Product list">
    <apex:pageblocktable value="{!OppProducts}" var="oli">
        <apex:column value="{!oli.Quantity}"/>
    </apex:pageblocktable>
    </apex:pageBlock>
</apex:page>

I haven't referenced all of the columns in the VF page yet.

Many thanks
Hi All,

In Contact Object, Acivity History related list having Log a Call Button. When i click on Button then open a page and prepopulate some fields like Assigned To, Priority and Related To etc.. But here my problem is that "Related To" field(Picklist) is prepopulated with Opportunity object, Now i want to change that as "Patient" custom object.
Related To field having some values like Asset, Campaign, Case, Contact,Patient,Opportunity etc..

Can i change that field value ? Please let me know with appropriate solution.

Thanks
Rakesh
Hi techi's,

Please solve this issue

constructor;
try
        {
            orderDetails = (OrderItem)controller.getRecord();
            system.debug('orderdetails'+orderdetails);
            orderDetails = [select id,Stage__c,OrderItemNumber,Quantity from OrderItem where id=:orderDetails.Id];
            Production = new Production_Stage__c();
            Production.Order_Product__c = orderDetails.id;
            system.debug('inputstatus is '+inputstatus);
            productionStageMap=new Map<String,Decimal>();
            productionStageSeqMap=new Map<Decimal,String>();
            
            Map<String,ProductionStage__c> tempMap = ProductionStage__c.getAll();
            
            for(String stageName : tempMap.KeySet())
            {
                if(tempMap.get(stageName)!=null)
                {
                    ProductionStage__c tempObj =tempMap.get(stageName);
                    productionStageMap.put(tempObj.Name,tempObj.Sequence_Number__c);
                    productionStageSeqMap.put(tempObj.Sequence_Number__c,tempObj.Name);
                }
            }
            system.debug('productionStageMap ' + productionStageMap);
            system.debug('productionStageSeqMap ' + productionStageSeqMap.keySet());
        }
        catch(exception ex)
        {
            system.debug('mesg '+ ex.getLineNumber() +'  no '+ex.getMessage());
        }
Method :
 public PageReference saveAndnew()
    {
        
        system.debug('The entered production object is ' + Production );
        system.debug('The input stage is ' + inputstatus);   
        system.debug('The production stages are ' + productionStageMap );
        
        PageReference pr;
        
        decimal Quantity = Production.Quantity__c;
        Production_Stage__c previousProductionstages = new Production_Stage__c();
        decimal completedquantity=0;
        decimal DateQty;
        decimal stageqty=0;
        decimal qty=0;
        decimal quan;
        decimal tqty;
        List<decimal> ldec;
        set<string> stageName=new set<string>();
        List<Production_Stage__c>  ProdMap;
        List<Production_Stage__c> stagelist = [select id,Quantity__c,Stage__c from Production_Stage__c where Stage__c=:inputstatus and Order_Product__c =:orderDetails.id];//stagelist here am getting null value&&inputstatus is null
        system.debug('stagelist is'+stagelist);
        
        for(Production_Stage__c ps : stagelist)
        {
            system.debug('Production Qty is'+Production.Quantity__c);
            qty= qty+ps.Quantity__c;
            //stageqty= Production.Quantity__c+quan;
            //completedquantity=stageqty+Production.Quantity__c;
        }
        
        quan = qty+Production.Quantity__c;

Mytest class:
 Production_Stage__c pstage2=new Production_Stage__c();
        pstage2.Date_In__c=system.today();
        pstage2.Date_Out__c=date.newInstance(2015,12,20);
        pstage2.Order_Product__c=oi.id;
        pstage2.Stage__c ='Schedule';
        pstage2.Sequence_Number__c=1;
        pstage2.Quantity__c=5;
        insert pstage2;
        system.debug('SSSSSSS'+pstage2);
        //insertion of custom settings
      
         
        ProductionStage__c ps1=new ProductionStage__c();
        ps1.Name=pstage.Stage__c;
        ps1.Sequence_Number__c=1;
        insert ps1;
       
        system.debug('ProductionStageps1'+ps1);
        
        PageReference pageRef = Page.ProductionProcessVf;
        test.setCurrentPage(pageRef);
        ApexPages.StandardController con = new ApexPages.StandardController(oi);
        system.debug('CCCCCCCCCon'+con);
        
         
        Production_Controller proc= new Production_Controller(con);
        system.debug('CCCCCCCCCon'+proc);
        
      
        proc.inputstatus='PreProcessing';
        proc.getstatusOptions();
        proc.saveAndnew();//Here getting Null pointer Exception 
        proc.cancel();
can any one help?
Hi,

I have a picklist with 6 values (1, 2, 3, 4, 5, 6)

The default value is 1.

When someone chooses another value from that picklist (imagine 2), I would like that value 1 and 2 were not able to be picked again.

How can I do this?

Thanks
i need to stop this trigger firing everytime contact record is edited
here is trigger:


trigger newoppty on contact (after insert, after update) {

     
    
    list<opportunity> opplist = new list<opportunity>();
    
    for (contact con : trigger.new) {

        if(con.Stage__c == 'Lead' && con.contacttype__C =='Seller') {
            opportunity newopp = new opportunity ();
            
            newopp.ownerid = con.allocated_user__c;
            newopp.name = 'Market Appraisal'; 
            newopp.accountid = con.accountid;
            newopp.CurrencyIsoCode = con.currencyisocode;
            newopp.stagename = 'Lead';
            newopp.recordtypeid = '012250000000Jev';
            newopp.contact__c = con.id;
            newopp.closedate = Date.today().addDays(7);
            newopp.PriceBook2Id = '01s250000005Du6';
            
            

            opplist.add(newopp);

}
}


        try {
        insert opplist;
       OpportunityLineItem[] lines = new OpportunityLineItem[0];
PricebookEntry[] entry = [SELECT Id, Name, UnitPrice FROM PricebookEntry WHERE Pricebook2Id = '01s250000005Du6' AND name In ('Market Appraisal')];
for(Opportunity record: opplist) {
    for (PricebookEntry thisentry : entry)
        lines.add(new OpportunityLineItem(PricebookEntryId=thisentry.Id, OpportunityId=record.Id, UnitPrice=thisentry.UnitPrice, Quantity=1));
}
        insert lines;     
} catch (system.dmlexception e) {
system.debug (e);
}

    
    }
Hi All,
How to write test class for below class.
public class searchres {
public string country{get;set;}
public string PartneredNonPartneredUniversities{get;set;}
public string name{get;set;}
public string Qualification{get;set;}
public string quali{get;set;}
public string CourseCategory{get;set;}
public string Course{get;set;}
public string ProgramSepcialisation{get;set;}
public string Program{get;set;}

public list<SOV_Database__c> bank{get;set;}
Public SOV_Database__c ban{get;set;}
public id sh;
   public void login()
   {
       
       bank = [select id,country__c,qualification__c,Partnered_Non_Partnered_Universities__c,Course_Category__c,Program_Sepcialisation__c from SOV_Database__c where country__c=:country and Partnered_Non_Partnered_Universities__c=:PartneredNonPartneredUniversities ];
   }
   public List<SelectOption> getqualification()
   {
     List<SelectOption> options = new List<SelectOption>();
           
      Schema.DescribeFieldResult fieldResult =SOV_Database__c.qualification__c.getDescribe();
      List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
           
      for( Schema.PicklistEntry f : ple)
      {
         options.add(new SelectOption(f.getLabel(), f.getValue()));
      }       
      return options;
   }
   public List<SelectOption> getCourseCategory()
   {
     List<SelectOption> options = new List<SelectOption>();
           
      Schema.DescribeFieldResult fieldResult =SOV_Database__c.Course_Category__c.getDescribe();
      List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
           
      for( Schema.PicklistEntry f : ple)
      {
         options.add(new SelectOption(f.getLabel(), f.getValue()));
      }       
      return options;
   }
   public List<SelectOption> getProgramSepcialisation()
   {
     List<SelectOption> options = new List<SelectOption>();
           
      Schema.DescribeFieldResult fieldResult =SOV_Database__c.Program_Sepcialisation__c .getDescribe();
      List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
           
      for( Schema.PicklistEntry f : ple)
      {
         options.add(new SelectOption(f.getLabel(), f.getValue()));
      }       
      return options;
   }
}

Thanks
Pawan.
Hi, 
The following apex visualforce page and the controller retrieves the response which is getting captured in the debug log but does not get displayed on the vf page.

Apex Controller
============
public class BankDetailsController {
    
    public Id accId {get;set;}
    public Account acc {get;set;}
    public String accname {get; set;}
    public String Response {get; set;}
    public AsyncSoapSforceComSchemasClassGetbankdet.getBankDetailsResponse_elementFuture resp;
    public Object startAsyncCall() 
    {
         Account acc =  [select Name from Account where Id =: ApexPages.currentPage().getParameters().get('id')];
        Continuation con = new Continuation(60);
        con.ContinuationMethod = 'processResponse';
        
        //string accname = 'GoGlobalStrategies';
        partnerSoapSforceCom.Soap myPartnerSoap = new partnerSoapSforceCom.Soap(); 
        partnerSoapSforceCom.LoginResult partnerLoginResult = myPartnerSoap.login('somnath.paul4@cognizant.com', '**********');
        soapSforceComSchemasClassGetbankdet.SessionHeader_element webserviceSessionHeader=new soapSforceComSchemasClassGetbankdet.SessionHeader_element();
        webserviceSessionHeader.sessionId = partnerLoginResult.sessionId;
       // soapSforceComSchemasClassGetbankdet.GetBankDetailsofAccount getBankdet=new soapSforceComSchemasClassGetbankdet.GetBankDetailsofAccount();
        //getBankdet.SessionHeader=webserviceSessionHeader;*/
         AsyncSoapSforceComSchemasClassGetbankdet.AsyncGetBankDetailsofAccount asyngetbnkdet = new AsyncSoapSforceComSchemasClassGetbankdet.AsyncGetBankDetailsofAccount();
        
        asyngetbnkdet.SessionHeader = webserviceSessionHeader;
        system.debug('session header'+ asyngetbnkdet.SessionHeader);
        resp = asyngetbnkdet.beginGetBankDetails(con, acc.Name);
        system.debug('resp from action'+ resp);
        return con;
    }
    public Object processResponse()
    {
        Response = resp.getValue();
        system.debug('Response from get Value'+ Response);
        return null;
    }
        
}

VF Page
========
<apex:page controller="BankDetailsController">
     <apex:form >
   <apex:pageBlock >
         <apex:pageBlockSection >
               Congratulations {!$User.FirstName}
             Following are the Bank Details:
                   <apex:commandButton value="Get Bank Details" action="{!startAsyncCall}" reRender="Response"/>
       </apex:pageBlockSection>
  </apex:pageBlock>
  </apex:form>
    <apex:outputText value ="{!Response}"/>
</apex:page>


Can any body please reply what went wrong in the VF page. 
SObjectType objToken = Contact.sobjectType;
Map<String, SObjectField> withPrefix = objToken.getDescribe().fields.getMap();
//check rule is fully populated

Map<String, SObjectField> fields = new Map<String, SObjectField>();
//Create a new map without prefix
for( String key : withPrefix.keySet() ){
    fields.put(key, withPrefix.get(key));
}

System.debug('WITH PREFIX: ' + withPrefix.get('lastname'));
System.debug('WITH PREFIX 2: ' + withPrefix.get('LastName'));
System.debug('WITH PREFIX 2: ' + withPrefix.get('LastNAmE')); //ETC?!

System.debug('WITHOUT PREFIX: ' +fields.get('lastname'));
System.debug('WITHOUT PREFIX 2: ' +fields.get('LastName'));
 

My output to debug is:
WITH PREFIX: LastName
WITH PREFIX 2: LastName
WITH PREFIX 3: LastName
WITHOUT PREFIX: LastName
WITHOUT PREFIX 2: null

How come can it be that the map<String, SobjectField> withPrefix isn't case sensetive????? I cannot understand it

Can anyone answer this?

 

Hi
What is the difference between the <apex:inputlabel> and <apex:outputlabel>



Thansk&regards
Ranga
if(tasksToUpdate.size() > 0 && calledFrom == 'batch')
            database.update(tasksToUpdate);

tasksToupdate is the list and remaining part i did not understood help me 
Hi,

Here my senario, User 1, User 2.

Contract records are auto created under Opportunity when the stage is closed(I used process builder). The newly created Contract records are filled by the user (User 1), Whenever the user (User 1) update the contract records an Approval email is send to User 2, I have created a approval process that notify another user in my org(User 2) for Approve the Contarct record.

We need to prevent the "User 1" from Active(Standard Button) the Contract records(Non Approved Contract Records) until it's approved by the User 2.

Can this possible to do so? if yes, how. validation rule or a trigger, etc..

Thanks & Regards,
Karthikeyan Chandran
+91-9944676540
I am trying to take whoever the primary user is in an opportunity's contact roles and populate a Lookup(user) field with this person but need a little help.  This is what I have but i am missing some understanding of contactrole and user's id relationship.  How would I accomplish this?
 
trigger UpdateOpportunityContact on Opportunity (after update, after insert) {
    List<OpportunityContactRole> contactRoles = new List<OpportunityContactRole>();
    
    for( Opportunity acc : [ Select Id, (SELECT OpportunityId,IsPrimary,ContactId  FROM OpportunityContactRoles) FROM Opportunity ])
    {
        contactRoles.addALL(acc.OpportunityContactRoles);
    }
    for(Opportunity opp : trigger.new)
    {
    for(OpportunityContactRole role : contactRoles)
    {
        if(role.IsPrimary)
        {
            opp.Primary_Contact__c = new User(ContactId = role.ContactId);
            upsert opp.Primary_Contact__c;
        }
    }
    }

}

 
  • November 05, 2015
  • Like
  • 0

I have a validation rule on Contact which don't let me make a Contact without Email or Phone number, but I have some cases when the user can create an Contact without email and Phone. I have a visualforce page to create a new contact and when the user click Save and he don't put the email or phone I want to show a popup window and ask him if he want for sure to create a contact without email or phone. Can anyone explain me how to do this? (In Save method if email and phone are not introduced I put a text in the  Email field to pass the validation rule)
Heya, 

I am trying to create a Custom Button on the incident object that creates a Task and links it to the incident object record it came from. This was fine, see below:

{!REQUIRESCRIPT("/soap/ajax/22.0/connection.js")} 
var newtask= new sforce.SObject("BMCServiceDesk__Task__c"); 
newtask.BMCServiceDesk__taskDescription__c = "my new task"; 
newtask.BMCServiceDesk__FKIncident__c = "{!BMCServiceDesk__Incident__c.Id}"; 
var result = sforce.connection.create([newtask]); 
window.location.reload();

The issue i have is that it uses the default task record type, I would like it to bring up the select record type page. Is this possible?
 
I'm working on a Trigger on Account where a field named 'test__c' should get updated when a record is created or edited. I wrote a trigger for that. Below it is.  But when I create a record or edit it, I get an error "first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TestUpdate: maximum trigger depth exceeded Account trigger event AfterUpdate for [0019000001ZgGny"

Can someone help me with this.

Below is the code:

trigger TestUpdate on Account ( after insert, after update) {


List<Account> ast = new List<Account>();

for (Account a : [select id, name, test__c from Account where id IN: trigger.new])

{

if (a.test__c == null)        
        a.test__C = 'TestUpdate';
        
ast.add(a);
}

update ast;
}
Hi All,

The below trigger is working fine on insert and update operations but on delete it gives me the below error. can you please help me

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger Contactcallout caused an unexpected exception, contact your administrator: Contactcallout: execution of BeforeDelete caused by: System.FinalException: Record is read-only: Trigger.Contactcallout: line 11, column 1". 


Click here to return to the previous page.
trigger Contactcallout on Contact (after insert, after update, before delete) {
Id RecordType1= [SELECT Id FROM RecordType WHERE SOBJECTTYPE=:'Contact' AND DeveloperName=:'Commercial'].Id;
Map<Id, String> m = new Map<Id, String>();
list<Contact> validContacts = new list<Contact>();
set<ID> accIds = new set<ID>();
if(Trigger.isDelete)
    {
        for (contact c : Trigger.old) 
        {
            if(c.RecordTypeId == RecordType1 && c.Reg__c == TRUE)    
            c.Status__c='Inactive';
            {
                validContacts.add(c);
                accIds.add(c.accountid);
            }   
        }
    }
    else
    {
for (contact c : Trigger.new) {
    if(c.RecordTypeId == RecordType1 && c.Reg__c == TRUE){
    if(Trigger.isUpdate){
        contact old = Trigger.oldMap.get(c.Id);
        if (c.Email != old.Email||c.FirstName!=old.FirstName||c.LastName!=old.LastName||c.phone!=old.phone||c.Title__c!=old.Title__c||c.status__c!=old.status__c||c.AccountID!=old.AccountID||c.Registered_on_ITV_Media__c == TRUE)
         {
             validContacts.add(c);
                accIds.add(c.accountid);
         }
         }else{
         validContacts.add(c);
                accIds.add(c.accountid);
                }
                }
         }   
}
map<ID, Account> accMap;
if(!accIds.IsEmpty()) // guard condition for SOQL
    accMap = new map<ID, Account>([select name from account where id in :accIds]);

for (contact c : validContacts) {
    Account acc = accMap.get(c.AccountID);
    string accName = acc == null ? null : acc.Name;
    WebServiceCallout.sendNotification(c.Id,c.Email,c.FirstName,c.LastName,c.phone,c.Title__c,accName,c.status__c);
              }
}