• jungleee
  • SMARTIE
  • 610 Points
  • Member since 2012

  • Chatter
    Feed
  • 21
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 14
    Questions
  • 102
    Replies

Hi, I want to return the record count of a dynamic SOQL query, (checkVal is passed in so don't worry about that):

 

Public List<sObject> lstObj;

Public Integer totRecsToProcess;


mystr  = '[select count() from payout__ImportStaging__c where payout__BD_Id__c = \'' + String.escapeSingleQuotes(checkVal) ;

 lstObj = Database.query(mystr);

 

I want to set totRecsToProcess equal to the count() value returned, can someone please tell me the correct syntax for that?

 

Thanks.

 

 

 

 

hi all,

 

i've been triyng to pull data from a remote service and have managed to get connected and can see in the logs that my child items are being read - my only issue is that the new records that I want creating aren't being created.

 

here is my code can anyone see what this isn't created montioring forms - the apex is triggered when we create a new form, basically it will then go off and check the remote service for any new forms on the server.

 

cheers

dan

 

public class MonitoringFormsUpdater {
  //Future annotation to mark the method as async.
  @Future(callout=true)
  public static void updateMF() {
    //construct an HTTP request
    Http http = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://magpi.com/api/surveys?username=myusername&accesstoken=myaccesstoken');
    req.setMethod('POST'); 
    //send the request
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
    // list object ready for insert 
    List<Monitoring_Form__c> newforms = new List<Monitoring_Form__c> ();
    string s = res.getBody();
    Dom.Document docx = new Dom.Document();
        docx.load(s);
        dom.XmlNode xroot = docx.getrootelement();
        dom.XmlNode [] xrec = xroot.getchildelements(); //Get all Record Elements
        for(Dom.XMLNode child : xrec) //Loop Through Records
            {
            Monitoring_Form__c mf = new Monitoring_Form__c();
        for(dom.XmlNode magpi : child.getchildren() ) {
           if (magpi.getname() == 'SurveyId') {
                   mf.form_id__c = magpi.gettext();
             }
           if (magpi.getname() == 'SurveyName') {
                   mf.name = magpi.gettext();
             }  
         }
        newforms.add(mf);
        }
  }
}

 the remote service returns this xml file.

 

<Surveys>
<Survey>
<SurveyId>7471</SurveyId>
<SurveyName>Bole_ASD_JHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7450</SurveyId>
<SurveyName>Bole_ASD_Pri</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7493</SurveyId>
<SurveyName>Bole_ASD_SHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7474</SurveyId>
<SurveyName>Bongo_ASD_JHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7494</SurveyId>
<SurveyName>Bongo_ASD_SHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
</Surveys>

Hi

I'm new to Apex and teaching myself. I've got a simple trigger that works in a sandbox, but to deploy it to production I need code coverage with a unit test.  Here's where the problem is.

 

This is where I got so far. (Trigger takes Billiing Zip off Account object - looks up a related object - finds County - returns to County__c field on Account object)

 

This is the working trigger

trigger conZipcodeAcc on Account (before insert, before update) {
    for(Account a : Trigger.new){
        List<ZipCounty_Chart_del__c> zcc = [select t.id,t.county__c,t.Postal_Code__c from ZipCounty_Chart_del__c t where t.Postal_Code__c =: a.BillingPostalCode ];
        if(!zcc.isEmpty()){
            for(ZipCounty_Chart_del__c t : zcc){
                a.County__c = String.valueOf(t.County__c);
            }
        }
    }
}

 

Here is where I've got with my unit test, but I get a compile error (Error: Compile Error: expecting right curly bracket, found 'EOF' at line 0 column -1).

 

@isTest
private class TestConzipcodeAcc{
static testMethod void TestConzipcodeAcc (){
//Set up the account record
List<Account> accounts = new List<Account>{};

For (Integer x=0; x<200;x++)
{
//This iterates and creates 200 Accounts with a postal code of 19001 (something known). 
Account a = new Account (Test= 'School' + x, BillingPostalCode = '19001');
accounts.add(a);
}


test.startTest();
   insert accounts;
test.stopTest();

 

 

For (Account a : accounts) {
System.AssertEquals (County__c = 'Montgomery');
}
}

 

  • September 11, 2013
  • Like
  • 0

Dear Folks,

 

I have been struggling with trying to write a trigger to update a balance on a bill when a payment is made on it. The progress I have made is below:

 

trigger UpdateBalanceOnPayment on Payment__c (after insert) {
    for (Payment__c payment : Trigger.new) {
        Bill__c bill = [SELECT Id, Balance__c FROM Bill__c
            WHERE Id = :payment.Bill__c.Id];
    }
}

For some reason the Force.com IDE says invalid foreign key relationship and does not synchronize with the server.

Each payment will have a master detail relationship with the associated bill when it is saved and I want to reduce the balance on the bill by the amount made by the payment after the payment is saved.

 

However I have not even got to that stage yet because it looks like I have made a mistake in the query. I would appreciate any pointers you can lend on this problem.

 

Many Thanks

nandac

  • April 19, 2013
  • Like
  • 0

Hi,

 

I have implemented a case in which a user can select a list of Feature object to add to a Car object. Right now ,the apex code generates a dynamic list of feature objects that the user can select and add to a custom list. My problem is that I would like this list to be tied to the Car object permanently after the user makes it (right now if the user refreshes the page, everything is reset and the list is emptied). How do I go about making this apex variable persistant to the custom object? Essentially it would be a List variable that gets saved into the database with the Car Object, kind of how the custom fields are.

 

Thanks!

  • April 16, 2013
  • Like
  • 0

I'm working with this at the moment:

List<RecordType> id = [select ID from RecordType where Name = 'Quote'];
    if (id.isEmpty()){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'No ID found.'));
    return null;    
    }
    rectypeid = String.valueOf(id[0].ID);

cncl = new Cancelations__c();
    cncl.Id = rectypeid;
    cncl.Date__c = cDate;
    cncl.Contract_Holder__c = name;
    cncl.Customer_Pay__c = custPrice;
    cncl.Cancelation_Fee__c = cFee;
    cncl.Cx_Method__c = method;
    cncl.Deduction__c = deduction;

 I'm trying to get it to return the proper ID value, but it keeps returning the 18 digit version instead of the 15 digit one so when I try and pass it back to salesforce it says it's an invalid ID for the object and I can't figure out either ther best way to truncate it or pass it back so it will accept it.  I've tried typcasting it as an ID, various string methods to remove the extra characters, but without success, and it's wearing a little thin so any advice on perhaps a better way to do it, or a correction if I'm doing it completly wrong would be great.

I don't know what I am doing wrong.  I am try to create a Contact, then link it with an Account.  Here is the gist of it.

 

 

Account a = new Account();
a.Name = 'account1';
insert a;

Contact c = new Contact();
c.Account__c = a;         // is this the right way to link them together?
insert c;

 

Contact cc = [ select name, Account.Name from Contact ];
System.debug(cc.Account);    // Account is null here.  Why?

 

Much appreciated if someone figures this out.  I am stumped.  

if(T.Completion_Date__c != NULL){
                   T.No_Of_Days_Open__c = T.Completion_Date__c - DATEVALUE(CreatedDate);
                }
Error :

 Error: Compile Error: Variable does not exist: CreatedDate at line 38 column 76
 if(T.Completion_Date__c != NULL){
                   T.No_Of_Days_Open__c = T.Completion_Date__c - DATEVALUE(T.CreatedDate);
                }
Error :

 Error: Compile Error: Method does not exist or incorrect signature: DATEVALUE(Datetime) at line 38 column 66

 

 

The Code :

 

trigger UpdateTypePicklist on Task(before update) {
            
            String Curr = Userinfo.getDefaultCurrency();
            
            for(Task T: Trigger.new){
              
            //Create an old and new map so that we can compare values  
              Task oldT = Trigger.oldMap.get(T.ID);    
              Task newT = Trigger.newMap.get(T.ID);
              
             //Retrieve the old and new Status Value   
              String OldStat = oldT.Status;
              String NewStat = newT.Status;
if((T.Type__c != NULL)&& (T.RecordTypeId == '012S0000000DIPs'))
                 {                  
                  T.Type = T.Type__c;
                 }
                
                if(OldStat!= NewStat){
                      
               T.Status_Update_Date_Time__c = DateTime.now();
               
                 if(T.Status == 'Completed'){
                   T.Completion_Date__c = Date.Today();
               
               }
               
               if(T.Completion_Date__c != NULL){
                   T.No_Of_Days_Open__c = T.Completion_Date__c - DATEVALUE(T.CreatedDate);
                }
               
               }
               
               
               If((T.CurrencyIsoCode!= Curr)&&((T.Type__c!='Estimate')&&(T.Type__c!='Quote'))){
                   T.adderror('Activity Currency Should not be updated');
                 
               }
                
   }
}


Hello!

I'm new to writing apex triggers but I finally got one to work in my sandbox.  My problem now is that I can't put it inot production without a test class, and I'm clueless on how to write it.  Here is what I'm trying to do:

 

When a Lead is created links via a lookup to a custom object called Site; When the field "First Payment Date" on the Site is updated the trigger updats a field named "First Payment Date" on the Lead.

 

How the heck do I write a test class for this??  Any help would be greatly appreciated!!

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
trigger updateFirstPaymentDate on Site__c(after update, after insert) {
    Integer i = 0;
    Set<ID> leadIds = new Set<ID>();
    Map<ID, Date> id2Date = new Map<ID, Date>();
    for (Site__c o : Trigger.new)
    {
        if ((Trigger.isInsert && o.First_Payment_Date__c != null) ||
            Trigger.old[i].First_Payment_Date__c != o.First_Payment_Date__c)
        {
            leadIds.add(o.lead__c);
            id2Date.put(o.lead__c, o.First_Payment_Date__c);
        }     
        i++;    
    }
    
    List<Lead> leads = [select id  from Lead where id in :leadIds];
    
    for (Lead c : leads)
    {
        c.First_Payment_Date__c = id2Date.get(c.Id);
    }
    
    update leads;
}

  • October 23, 2012
  • Like
  • 0

Hi,

 

My requirement is to give a dropdown to the user and based on the selected value, a table has to be displayed.

 

If the dropdown value is changed, then the result set also should get changed.

 

The problem is whenever the drop down value is selected for the firsttime, the corresponding result set is shown. But whenever the dropdown value is changed for the second time, corresponding result set is not getting refreshed.

 

 

VFPAGE:

 

<apex:page StandardController="User" Extensions="UserData" tabstyle="User" sidebar="false">
  <apex:form >
  <apex:pageBlock title="Select Users" id="USERSLIST" mode="edit">
    <h1>Update Sales Co-ordinator for the users in Particular Region</h1>
  <br></br>
  <br></br>
      
   <apex:outputLabel value="Select Region of the user: " for="viewlist" />
<apex:inputField id="startMode" value="{!User.Region__c}">
<apex:actionsupport event="onchange" action="{!doSearch}" rerender="theTable" />
</apex:inputfield>
  
           <br></br>
   <apex:pageBlockTable value="{!results}" var="t" id="theTable">
        <apex:column >
          <apex:inputCheckbox value="{!User.ManagerId}" id="checkedone">
          </apex:inputCheckbox>
        </apex:column>
        <apex:column value="{!t.Name}"/>
        <apex:column value="{!t.Email}"/>
        <apex:column value="{!t.Region__c}"/>
        <apex:column value="{!t.Manager__c}"/>     
  </apex:pageBlockTable>
 

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

 

CONTROLLER:

 

public class UserData {
List<Userwrapper> userList {get;set;}
PUBLIC String usr{get;set;}
List<User> results=new List<User>();
public User user;
public ApexPages.StandardController stdCtrl;
public UserData(ApexPages.StandardController controller)
   {
     stdCtrl=controller;

   }  
    
        
  public Pagereference doSearch()
     {
      //results = [select Name,Region__c,Email,LanguageLocaleKey,Manager__c from User Where Region__c =:User.Region__c];
      User u=(User)stdCtrl.getrecord();
      results = [select Name,Region__c,Email,LanguageLocaleKey,Manager__c from User Where Region__c =:u.Region__c];

      system.debug('USERSLISTFOR REGION$$$$'+results);
      return null;
     }
   
     
   public List<User> getResults()
    {
        return results;
    }
 
 }

 

Please check and suggest if there are any ideas.

 

Thanks,

Ranjita.

 

Here we go....

 <apex:outputpanel rendered="{!errorxml}">
         <apex:pageBlockSection title="Payment Result">
             <apex:pageblocksectionItem >
                  <Label class="table">Transaction Status</Label>
                  <apex:outputtext value="{!cnpxmlstring.ErrorData}"/>
              </apex:pageblocksectionItem>
              <apex:pageblocksectionItem >
                  <label>Order Number</label>
                  <apex:outputText value="{!cnpxmlstring.TransactionNumber}"></apex:outputText>
              </apex:pageblocksectionItem>

       </apex:pageblocksection>

</apex:outputpanel>

 

 <apex:commandButton value="Process payment" id="processpayment"  action="{!PaymentAPIMethod}"  reRender="seexml,errorxml"/>

 

But cant able to find the payment result values.....Any help pls

 

Thanks,
   

Currently have the following trigger which works perfectly for one record inside our production organization:

 

trigger createCommissionClosedWon on Opportunity ( before insert, before update) {
    Opportunity[] opps = Trigger.New;
    for (Opportunity o:opps){
    If (o.StageName == 'Closed Won')
       CreateCommissionRecords.createCommissionRecords(opps);
}}

 I'm trying to bulkify this trigger so that it performs well under bulk updates..... The following code creates an error when I try and save:

 

trigger createCommissionClosedWon on Opportunity (before insert, before update) {

    for (Opportunity opps: Trigger.New){
    	If (opps.Stage == 'Closed Won'){
   		CreateCommissionRecords.createCommissionRecords(opps);
}}}

 What am I doing Wrong??? This is the error message that I'm receiveing: Save error: Method does not exist or incorrect signature: CreateCommissionRecords.createCommissionRecords(SOBJECT:Opportunity)  

 

it sounds like a variable / definitional problem.... Thanks so much for helping me.....

 

 

 

I am trying to update the value of a date / time field called as Last_Stage_Change__c by system.now(). When ever there is a change in value of a field called Sales_Order_Status__c then the field Last_Stage_Change__c should be updated. Both the fields belong to the the same object called Sales_Order__c. Here, Sales_Order_Status__c is a picklist field.

This is the code:

trigger UpdateField_LastStageChange on Sales_Order__c (after insert, after update) {
        List <Sales_Order__c> statusInsert = new List<Sales_Order__c>();
        List <Sales_Order__c> statusUpdate = new List<Sales_Order__c>();
        if(trigger.isInsert){
            for(Sales_Order__c so1:trigger.new){
                if( so1.Sales_Order_Status__c!=Null){
                    so1.Last_Stage_Change__c = system.now();
                    statusInsert.add(so1);
             } }
            update statusInsert;
            System.debug('last Stage Change Date/Time during Insert:'+statusInsert);
        } else if(trigger.isUpdate){
            for(Sales_Order__c so2:trigger.new){
                if(so2.Sales_Order_Status__c!=Null && so2.Sales_Order_Status__c!=trigger.oldMap.get(so2.id).Sales_order_Status__c){
                    so2.Last_Stage_Change__c = system.now();
                    statusUpdate.add(so2);
          } } update statusUpdate;
            System.debug('last Stage Change Date/Time during update:'+statusUpdate);
        } }

  I got an error message:

This is the error message: Error:Apex trigger UpdateField_LastStageChange caused an unexpected exception, contact your administrator: UpdateField_LastStageChange: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.UpdateField_LastStageChange. How to solve this problem?

 Is it possible to replace the above trigger just by setting the default value of the field Last_Stage_Change__c to NOW()?

 Everytime the field is queried it will run the NOW() method and give the desired result.

 

hi guys,

This trigger has 100% test coverage before after adding one condition it decreased .

help me in increasing the test coverage.

 
trigger Updtcon on comments__c (before insert) {
Set<Id> sobjectSetOfIds = new Set<Id>();
Set<Id> sobjectSetOfctctIds = new Set<Id>();
Set<Id> sobjectSetOffinIds = new Set<Id>();

Comments__c cms;
opportunity opp;
UserRole ur = [ select Id, Name FROM UserRole where Id =:Userinfo.getUserroleid()];


for(Comments__c cs:trigger.New){
cms=cs;
if(cms.Opportunity__c!=null && cms.Contact__c==null && cms.finance__c==null){
sobjectSetOfIds.add(cms.Opportunity__c);
}
if(cms.Opportunity__c==null && cms.Contact__c!=null && cms.finance__c==null){
sobjectSetOfctctIds.add(cms.Contact__c);
}
if(cms.Opportunity__c==null && cms.Contact__c==null && cms.finance__c!=null){
sobjectSetOffinIds.add(cms.Finance__c);
}
}
/* updating contact and finance from opportunity object comments related list*/
if(!sobjectSetOfIds.ISEmpty())
{
Map<Id,Opportunity>smap= new Map<Id, Opportunity>([Select id,Name,Borrower__c,(Select id,name from Finances__r) from Opportunity where Borrower__r.RecordType.name=:'Applicant' AND Id in : sobjectSetOfIds ]);

for(Comments__c s: trigger.new){
if(smap.containsKey(s.Opportunity__c)){ 
s.Contact__c=smap.get(s.Opportunity__c).Borrower__c;
if(smap.get(s.Opportunity__c).finances__r.size()>0){
s.Finance__c=smap.get(s.Opportunity__c).finances__r[0].id;
}
s.Comment_Created_from__c ='Opportunity ::'+ ' '+smap.get(s.Opportunity__c).Name;
s.written_by__c='Opportunity';//UserInfo.getName();
s.Written_date__c=system.Today();
s.Role__c=ur.name;
}
}
}

/* updating opportunity and finance from contact object comments related list*/
if(!sobjectSetOfctctIds.ISEmpty()){
List<Opportunity> opportunities = [select Id,Borrower__c, Name,Borrower__r.Name,(Select id,name,contact__c from Finances__r )from Opportunity where Borrower__r.RecordType.name=:'Applicant' AND Borrower__c in:sobjectSetOfctctIds ];
map<string,string> mpcopid=new map<string,string>();
map<string,string> mpcopname=new map<string,string>();
map<string,string> mpfinid=new map<string,string>();
for(Opportunity oppn:opportunities){
mpcopid.put(oppn.Borrower__c,oppn.Id);
mpcopname.put(oppn.Borrower__c,oppn.Borrower__r.Name);
if(oppn.finances__r.size()>0){mpfinid.put(oppn.Borrower__c,oppn.Finances__r[0].Id);}


}
for(Comments__c s: trigger.new){
if(mpcopid.containsKey(s.Contact__c))
{
s.Opportunity__c=mpcopid.get(s.Contact__c);
if(mpfinid.ContainsKey(s.Contact__c)){s.Finance__c=mpfinid.get(s.Contact__c);}
s.Comment_Created_from__c ='Contact :: '+mpcopname.get(s.Contact__c);
s.written_by__c='Contact';//UserInfo.getName();
s.Written_date__c=system.Today();
s.Role__c=ur.name;
}
}
}



/* updating opportunity and contact from finance */
if(!sobjectSetOffinIds.ISEmpty()){
Map<id,Finance__c> fc =new Map<id, Finance__c>([select id,Name,Opportunity__r.id,Opportunity__r.Borrower__r.id from Finance__c where id in:sobjectSetOffinIds]);
for(Comments__c cs:trigger.New){
if(fc.containsKey(cs.Finance__c)){
cs.Opportunity__c=fc.get(cs.Finance__c).opportunity__r.id;
cs.Contact__c=fc.get(cs.Finance__c).Opportunity__r.Borrower__r.id;
cs.Comment_Created_from__c='Finance::'+''+fc.get(cs.Finance__c).Name;
cs.written_by__c='Finance';//UserInfo.getName();
cs.Written_date__c=system.Today();
cs.Role__c=ur.Name;

}
}
}
}

After adding the condition in red line then the code is not getting covered which is in brown,

test Method:-

-----------------------------------------------

@isTest
private class Updtcon {
static testMethod void Updtcon () {



Contact C= new contact(LastName='Anil');
insert c;

Opportunity o=new opportunity(name='Anil',StageName='prospecting',CloseDate=system.today(),Borrower__c=c.id);
insert o;

Finance__c f=new finance__c(Name='payment',opportunity__c=o.id,Contact__c=o.Borrower__r.id);
insert f;

Comments__c cm=new comments__c(Name='Raghu',Contact__c=c.id);
insert cm;

comments__c cms=new comments__c(Name='Anil',opportunity__c=o.id);
insert cms;

Comments__c cs=new comments__c(Name='Anil',Finance__c=f.id);
insert cs;

}
}

 

Thanks

Anil.B

Hi guys, 

 

I am having trouble with a test class for a simple trigger. My test class has no coverage and I am very new when it comes to test classes.

 

My trigger is pretty basic: When a user creates a Trip Report (custom object :Trip_Report__c), a related record is automatically created that adds the Trip Report owner to the list of meeting attendees (custom object: covance_attendees__c). 

 

 

 

trigger createCovanceAttendeeonnewTR on Trip_Report__c (after insert) {

List <Covance_Attendees__c> attToInsert = new List <Covance_Attendees__c> ();

for(Trip_Report__c t: Trigger.new) {

if (t.name<>'1') {

Covance_Attendees__c a = new Covance_Attendees__c (); 

a.Attendee_Name__c = t.OwnerId;
a.How_Attended__c = 'In Person';
a.Trip_Report__c = t.id;

attToInsert.add(a);
        
        
        }//end if
        
    }//end for o
    
    //once loop is done, you need to insert new records in SF
    // dml operations might cause an error, so you need to catch it with try/catch block.
    try {
        insert attToInsert; 
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
    
}

 

 

 

My Test Class has 0% coverage. I'm not sure what I am doing wrong as I don't know Apex very well.

 

If anyone knows how to fix this code- could you actually "write" the code instead of just telling me how to fix it? If I could see a proper test class in a context I understand, I think it will be a huge help. THANK YOU!!!


 

public class test_createCovanceAttendeeonnewTR
{
public static testMethod void testcreateCovanceAttendeeonnewTR()
{
//Insert Trip_Report__c
try
{
Trip_Report__c t = new Trip_Report__c(Name='TestMethodMouse1',Call_Objective__c='Follow Up',Visit_Date__c =System.Today());
insert t;

Test.StartTest();
Insert t;
Test.StopTest();



t=[SELECT Name,Trip_Description__c FROM Trip_Report__c WHERE Id = :t.Id];
system.assert (t.Name <> '1');
}
catch (System.DmlException e)
{
System.assert(true);
}
}
}


I have a before insert trigger on the Case object.  Under certain conditions, I need to change the owner of the case to a Queue called 'Platinum'.  I need to set x.Owner = <Platinum Queue>.  I assume i have to run a sql statement to get the ID of the 'Platinum' queue and then set x.owner equal to that?       thanks

hello,

 

I have a look up field assets_owned in my contacts object. I want to populate this look up only with those assets whose status is not assigned in the assets object. Can someone please help me.

 

Thanks!

Hi

 

I am new to salesforce platform.I need help with triggers.

I have created a look up field in contacts named Assets_owned. whenever a particular asset is selected in assets_owned i want to change the asset status to assigned from the picklist in the assets tab.

 

Thanks!

 

public class College
{
 // college name.
 Public Static final String CollegeName ='Tirumala Engg College';
 // college address.
 public Static final String  CollegeAdress='kesaraGutta,Bogaram,Hyderabad.';
 //college Year of Establishment.
 public Static final Integer DOE=1990;
 // creating Student class
 public class StudentClass
  {
  // creating properties for the required Student feilds(student number,student name,student address etc).
   public Integer sNo{get;set;}
   public String sName{get;set;}
   public String sAddress{get;set;}
   public Integer doj{get;set;}
   public String course{get;set;}
  }
  public class InstructorClass
  {
  // creating properties for Instructor feilds.
   public Integer iNo{get;set;}
   public String iName{get;set;}
   public String iQualification{get;set;}
   public Integer iDeptno{get;set;}
   }
   public class DeptClass
  {
  //creating properties for Department feilds.
   public Integer deptNo{get;set;}
   public String deptName{get;set;}
   public String deptLoc{get;set;}
   }
   //creating a list of students
   public List<StudentClass> students =new List<StudentClass>();
   ////creating a list of Instructors
   public List<InstructorClass> instructors =new List<InstructorClass>();
   //creating a list of Departments
   public List<DeptClass> departments =new List<DeptClass>();
   
  /* public String College()
   {
    return 'Welcome to '+ College.CollegeName;
    }*/
    
    public static StudentClass searchStudent(Integer stNo,List<StudentClass> Stds)
    {
       for(College.StudentClass student:stds)
         {
          if(Stds.sNo==stNo)
           {
           return student;
           }
           }
           }
    }
    
    hi can tell what's the error , am unable to understand error. any suggestion
   

Hi 

I am just not able to create a Enterprise or performance edition (Trial Editions). Whenever I click on the Try me links on the enterprise ot performance column a professional edition org gets created. I have a client demo tomorrow and I'm just not finding  a way to create these editions. Could anyone please help on this?

-Sam
Hi,

I have been a developer all along and was least bothered about the Licenses or the edition on which I was working on as it always was Unlimited editions. But now I need to send a proposal to a new customer with all the details for enterprise edition and the customer wanted to use the community as well. It would be very helpful if any of you could answer my queries :

1) What is the cost of Partner community license? Its not available on the website, its says contact salesforce.
2) Do we need to pay any additional amount for enabling salesforce1 for community users? I think this is free not fully sure.
3) What are the cost of the sandboxes (different types) if we are required to procure new ones?
4) To create a new account do we need to create a trial account and then buy licenses using the checkout options?
5) In the full comparision of the editions I saw that a feature 'Mobile customization and administration' comes in for additional charge in the enterprise edition? What is this feature if salesforce1 is free?

Thanks
Junglee

Hi ,

 

In our project we have many tables where we are required to display checkboxes and the associated records. So we have used  an equal number of wrapper classes for each object. I was planning to generalize it, by soing something like this(below code), but was unsuccessful. I am not sure how to cast an generic sObject back to a specific object in a VF page

 

//apex Class:

public class genericObjectCreation{
    
    public class wrapperClass{
        //using a generic sObject.
        public sObject acc {get;set;}
        public boolean x {get;set;}
        public wrapperClass(sObject a){
            this.acc = a;
            this.x=false;
        }
   }
   
   public list<wrapperClass> wrapperList{get;set;}
   
   public genericObjectCreation(){
       wrapperList = new list<wrapperClass>();
       for(account a : [select name from account]){
            wrapperList.add(new wrapperClass(a));
       }
   }
}

//VF Page:
<apex:page controller="genericObjectCreation">
    <apex:form>
        <apex:pageblock>
            <apex:pageBlockTable value="{!wrapperList}" var="wp">
                <apex:column headerValue="boolean">
                    <apex:inputCheckbox value="{!wp.x}"/>
                </apex:column>    
                <apex:column value="{!wp.acc.name}"/>            
            </apex:pageBlockTable>
        </apex:pageblock>
    </apex:form>
</apex:page>

When I open the VF page I get an error stating:
ERROR: Unknown property 'SObject.name'
Error is in expression '{!wp.acc.name}' in component <apex:page> in page genericexample

 The error makes sense coz I am not casting the generic sObject back to account, the VF page is unable to get the value of .name. Any ideas how to go about it?

 

Regards

Sam

 

Hi

 

I have created a few html and javascript files in my local machine. I am using  forceTK client oAuth to login to salesforce . What I want to achive is, when the login is successful I want the page to redirect to a html page on my local machine. I have given the location of this html in the CallBackURL(c:/myfolder/example.html) in remote Access and also I have mentioned the same in the javascript redirectUri variable. But its not redirecting to that page.

 

COuld you please help me achive this?

 

-Sam

Hi ,

I am inserting records into the opportunityShare object programtically thru a trigger, while inserting the record I am setting the userOrGroupID field in the oppotunityShare to a public group.  When I change the owner of the opportunity, all these sharing records get deleted. While if I change any other field on the opportunity, the records in the opportunityShare object are intact.

 

Could anyone please let me know as to why this behaviour is happening?? And how can we avoid this?

 

Regards

Sam

Hi All,

 

I am aware of the fact that we cannot traverse on the ownerId field in the formula field. But I came across a similar problem in triggers. In the below class I am passing a map from the trigger to a class as below

 

//passing newMap to the below method.

public static void someMethod(map<id, opportunity> newOppMap){
	list<opportunity> oppty  = newOppMap.values();
	//iterating thru the list of opportunity.
	for(opportunity opp: oppty){
		if(opp.owner.isportalEnabled){//I am unable to fetch the CORRECT value of isportalEnabled. it always returns False for all the owners.
		.....some code....
		}
	}
}

 Any idea why this is happening??

 

Workaround: to create a map of user based on the owner and pass the the id to the map to fetch the correct value.

 

Regards

Sam

Hi,

I have a simple html page in my system. I am trying to access my org details using the ajax toolkit. But I am unable to do so. Any idea how can I access salesforce data in a simple html page in my system using javascript/ jquery??

 

<html>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="connection.js"></script>
<script type="text/javascript" src="apex.js"></script>

<script type="text/javascript">
	var j$ = jQuery.noConflict();
	sforce.connection.init('sessionId', 'https://ap1.salesforce.com/services/Soap/u/26.0');
	j$(document).ready(function(){
		var result = sforce.connection.query("Select Name, Id from User");
		var records = result.getArray("records");
		for (var i=0; i< records.length; i++) {
			var record = records[i];
			console.log(record.Name + " -- " + record.Id);
		}
	});
</script>
</html>

 Regards
Sameer

Hi ,

 

In the reports tab, the sidebar component is not enabled. In the user interface setting I have checked both the options

Enable Collapsible Sidebar
Show Custom Sidebar Components on All Pages

But still I am unable to view the sidebar in the reports tab. Can anyone let me know how do we add the sidebar in the reports tab??

Hi Guys,

 

I have created a simple vf page and placed and small jQuery script in the vf page (below code). I have added this vf page as an inline VF page in the Case detail page. In the jQuery I am trying to pick up the case number by passing the id of the div in which the case number is present and alerting the result. But I am getting a blank pop-up.

But when I try the same, by placing the jQuery in the sidebar, its working just fine.

 

<apex:page standardController="Case">
<script src="/resource/jQueryLatest" type="text/javascript"></script> <script type="text/javascript"> j$(document).ready(function(){ var caseNumber = j$("#cas2_ileinner").text(); alert(caseNumber); }); </script>
</apex:Page>

 Problem: not able to access the DOM elements of the standard detail page from a jQuery script which is placed in the inline vf page on the same page.

 

please help!

 

Regards

Sam

 

 

Hi,

 

I have created a input box and a link. When I click on the link, an alert will show the value of the input box. But this is not happening as of now, Please suggest the code changes. Thanks!

 

<apex:page id="pa">
 <apex:includeScript value="{!$Resource.jQuery}"/>
 <script type="text/javascript">
         var j$ = jQuery.noConflict();
         
         j$(document).ready(function(){
             j$("a").click(function(){
            var xyz = j$("#pa:f1:userInput").val();
            //var xyz = document.getElementById('{!$Component.pa.f1.userInput}').value;
             alert(xyz);
             });
        });         
  </script>

  <a herf="#" id="clickHere">click here</a>
  <apex:form id="f1">
      enter something <apex:inputText id="userInput"/>  
  </apex:form>
</apex:page>

 Thanks

Sam

 

 

Hi All,

 

I just installed the SurveyForce app in one of my sandbox, which was very recently upgraded to winter'13. I click on the Surveys tab, enter a name for the new survey and am redirected to a page which has 4 tabs namely Share, edit, thanks page.. and results... I am unable to select any of the tabs.. But this works perfectly fine in my developer org which is still in Summer'12.

The 4 tabs are being displayed using the <apex:tabPanel> tag of the visualforce. So i decided to inspect this tag. I used the example used in the visualForce developer guide (Below), But when I click on the tabs, I am unable to navigate...

 

ANy help here??

 

<apex:page standardController="Account" showHeader="true"
tabStyle="account" >
<style>
.activeTab {background-color: #236FBD; color:white;
background-image:none}
.inactiveTab { background-color: lightgrey; color:black;
background-image:none}
</style>
<apex:tabPanel switchType="client" selectedTab="tabdetails"
id="AccountTabPanel" tabClass='activeTab'
inactiveTabClass='inactiveTab'>
<apex:tab label="Details" name="AccDetails" id="tabdetails">
<apex:detail relatedList="false" title="true"/>
</apex:tab>
<apex:tab label="Contacts" name="Contacts" id="tabContact">
<apex:relatedList subject="{!account}" list="contacts" />
</apex:tab>
32
Getting a Quick Start with Visualforce Overriding an Existing Page with a Visualforce Page
<apex:tab label="Opportunities" name="Opportunities"
id="tabOpp">
<apex:relatedList subject="{!account}"
list="opportunities" />
</apex:tab>
<apex:tab label="Open Activities" name="OpenActivities"
id="tabOpenAct">
<apex:relatedList subject="{!account}"
list="OpenActivities" />
</apex:tab>
<apex:tab label="Notes and Attachments"
name="NotesAndAttachments" id="tabNoteAtt">
<apex:relatedList subject="{!account}"
list="NotesAndAttachments" />
</apex:tab>
</apex:tabPanel>
</apex:page>

 

Thanks

Sam

 

 

 

Hi ,

 

Could someone please point out the difference between 'save to database' and 'Commit to database'? This will be really helpful.

 

Thanks

Sam

Hi All,

 

Could some please throw some light on the difference between the id and QueueID used when we query for a Queue using SOQL like Select id, SobjectType, QueueId, Queue.Name from QueueSobject.?

 

Thanks

Sameer

Hiya people,

 

I am using a VF page in the self service portal(SSP) in the 'View cases'  tab. The VF page loads normally in salesforce(when used like apex/customVFPage), but when I use the same page as a in-Line VF page on the SSP, I(logged in to SSP as a Demo user) get the follwoing error :

"You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary."

 

Any idea where I can give the permissions to the SSP users(contacts)? Any help on this greatly appreciated. Thanks!!

 

Regards

Sameer

 

Hello apex experts,

 

I have a field on the account object that updates when the account is edited.  When the record is edited individually, the correct value gets written to the field.  When I use the data loader . . . One value applies to all records.  Here is my trigger, please advise.

 

trigger Populate_Transfer_Manager on Account (before insert, before Update) {   
   
    list<id> aid = new list<id>();
    for(account a: trigger.new){           
        aid.add(a.ownerid);
    }
    
list<user> managers = new list<user>();
    managers = [select managerid from user where id in: aid];
   

set<id> manid = new set<id>();                             
    for(user u: managers){
        manid.add(u.managerid);
    }
   

for(account a: trigger.new){        
    for(id i: manid){           
            a.transfer_manager__c = i;       
        }
    }
}

I'm having trouble with this because the documentation says that the limit is number of sendEmail methods called, but my trigger is bulkified and the method is only called once.

 

Does this error mean that you can only send 10 emails per apex execution?  That sounds nutso.  Here's the code (note: accountIds set was already populated)

 

// Email related vars

Messaging.SingleEmailMessage m;

string messageBody;

Messaging.SingleEmailMessage[] emails = new List<Messaging.SingleEmailMessage>();

 

Account[] accounts = [select id, name, ownerid, owner.email, type from Account where id in :accountIds];

for(Account a : accounts)

{

 if(a.type.startsWith('X') || a.type.startsWith('Pending')) { 

  messageBody = 'The account: "' + a.name + '" with type ' + a.type + ' has closed an opportunity';

  m = new Messaging.SingleEmailMessage();

  m.setHtmlBody(messageBody);

  m.setPlainTextBody(messageBody);

  m.setSubject('Pending or X account ' + a.name + ' has closed an opportunity');

  m.setToAddresses(new list<string>{a.owner.email});

  emails.add(m);

 }

 

 if(a.type == 'Distributor' || a.type == 'Distributor & Customer') {

  a.type = 'Distributor & Customer';

 } else if(a.type == 'Prospect' || a.type == 'Customer' || a.type == 'X Customer') {

  a.type = 'Customer';

 } elseif(a.type == 'CP: Consultant') {

  a.type = 'CP: Consultant & Customer';

 } else {

  a.type = 'Partner & Customer';

 }

}

 

update accounts;

 

Messaging.sendEmail(emails);

 

Does anybody know the real answer?

I am getting this error on a VF page :

 

This page is redirected from another controller class : The details are coming on the URL but on the page it is displaying error as :Page DetailController does not exist 

 

External Controller Class : Method :

 

public PageReference SaveChanges()

{
String OppId = ApexPages.currentPage().getParameters().get('Id');
Splits__c LitOrd = new Splits__c();
DSObj = new List<Splits__c>();
LitOrd.Opportunity__c= Opp.id ;
DSObj.add(LitOrd);
insert DSObj;
insert OppTeam;
PageReference pageRef = new PageReference('/apex/DetailController?Id='+opp.Id);
return pageRef;

}

 

--------------------------------------

 

VF page :

<apex:page controller="DetailController" tabstyle="Opportunity">
<apex:form >
<apex:pageBlock title="Region Details">
<apex:pageBlockTable value="{!wrappers}" var="wrapper" id="wtable">
<apex:column headerValue="Ident">
<apex:outputText value="{!wrapper.ident}"/>
</apex:column>
<apex:column headerValue="Region">
<apex:inputField value="{!wrapper.MSalesO.Region__c}"/>
</apex:column>
</apex:pageBlockTable>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlock>
</apex:form>
</apex:page>

--------------------------------------

 

Controller Class :

public class DetailController
{

public List<SOWrapper> wrappers {get; set;}

public static Integer addCount {get; set;}
private Integer nextIdent=0;

public DetailController()
{
wrappers=new List<SOWrapper>();
for (Integer idx=0; idx<5; idx++)
{
wrappers.add(new SOWrapper(nextIdent++));
}
}
public void addRows()
{
for (Integer idx=0; idx<addCount; idx++)
{
wrappers.add(new SOWrapper(nextIdent++));
}
}

public PageReference save()
{
List<Order__c> MSO=new List<Order__c>();
for (SOWrapper wrap : wrappers)
{
MSO.add(wrap.MSalesO);
}

insert MSO;

return new PageReference('/' + Schema.getGlobalDescribe().get('Order__c').getDescribe().getKeyPrefix() + '/o');
}

public PageReference SaveDS()

{
return null;
}
public class SOWrapper
{
public Order__c MSalesO {get; private set;}
public Integer ident {get; private set;}

public SOWrapper(Integer inIdent)
{
ident=inIdent;
MSalesO=new Order__c(Opportunity__c='006f0000003afa5' + ident);
}
}

}

I have two custom objects, Equipment and Equipment History. I would like to insert a new record into Equipment History when a record is inserted into Equipment. So far, I getting this error:

 

Apex trigger insertrecords caused an unexpected exception, contact your administrator: insertrecords: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.insertrecords: line 8, column 1

 

Here is my trigger:

trigger insertrecords on Equipment__c (after insert)
{
 Equipment__c[] eq = [SELECT Name from Equipment__c where id =: trigger.new];
 List<Equipment_History__c> copyeq;
 for(Equipment__c neweq : eq)
 
 {
  copyeq.add(new Equipment_History__c (Name=neweq.Name));
 }
 
 insert copyeq;
}

I'd like to build a trigger that pulls that updates a text field on a record with the report ID of a particular report.  I'm not sure how to go about obtaining the report ID.

Hi, I want to return the record count of a dynamic SOQL query, (checkVal is passed in so don't worry about that):

 

Public List<sObject> lstObj;

Public Integer totRecsToProcess;


mystr  = '[select count() from payout__ImportStaging__c where payout__BD_Id__c = \'' + String.escapeSingleQuotes(checkVal) ;

 lstObj = Database.query(mystr);

 

I want to set totRecsToProcess equal to the count() value returned, can someone please tell me the correct syntax for that?

 

Thanks.

 

 

 

 

Hi,

Why this err occr actually i want to pass the parameter where do i write with in metho r other class...

public class kathir_clsLand {

    public Account acct{get; set;}
    public static String accid;
    public static String qryString;
    public static List<Level1s__c> lstLevel1Tree;
    public static List<Level1s__c> lstLevel1;
    public static List<Level2s__c> lstLevel2; 
    public static List<Level3s__c> lstLevel3;
    public static List<Level4s__c> lstLevel4; 
    public String searchinput {get;set;}
    public List<Level1__c> lstsearch {get;set;} 
    public List<Level2__c> lstsearch2 {get;set;} 
    public List<Level3__c> lstsearch3 {get;set;} 
    public List<Level4__c> lstsearch4 {get;set;} 
    public List<Level5__c> lstsearch5 {get;set;} 
    public List<Level6__c> lstsearch6 {get;set;} 
    public String lurl{get;set;}
    public String state{get; set;}
 public String SearchText {get; set;}
 public Level1__c le1;
 
    public ApexPages.StandardController stdController; 
   public kathir_clsLand(ApexPages.StandardController con)
    {
        stdController = con;
        accid = ApexPages.currentPage().getParameters().get('id');
        lurl=ApexPages.currentPage().getParameters().get('levid');
        this.acct = (Account)con.getRecord();
       // this.le1= (Level1__c)con.getRecord();
        system.debug('*********'+acct);
        Integer j; 
        Integer k;
        // lstLevel1Tree = [Select id, name,(select account__r.name from Level1s__r where account__c =:accid ) from Level1s__c where id in (Select cLevel1__c from Level1__c where Account__c=:accid) ]; 
          if(ApexPages.currentPage().getParameters().get('S') == null)
          {
           lstLevel1 = [Select Id, Name,Description__c,(select account__r.name from Level1s__r where account__c =:accid ),(select id, name from Level2s__r limit 1) from level1s__c  order by Name ];
          // lstLevel4 = [Select Id,name,Level3__c,(select id, account__r.name from Level4s__r where account__c =: + accid ) from Level4s__c ];  
          }else
          {
           lstLevel1 = [Select id, name,(select account__r.name from Level1s__r where account__c =:accid ) from Level1s__c where id in (Select cLevel1__c from Level1__c where Account__c=:accid) ];
         //  lstLevel4 = [Select Id,name,Level3__c,(select id, account__r.name from Level4s__r where account__c =: + accid ), (select id from cusLevel5s__r limit 1) from Level4s__c  where id in (Select cLevel4__c from Level4__c where Account__c=:accid) ];  
         } 
         
            if(ApexPages.currentPage().getParameters().get('S') == null)
            {
                Level='All';   
            }
            else
            {
            Level='Selected Only';
            } 
            
            
    }        
    /* search*/
    
    public void searchmethod()
    {
        String url = ApexPages.currentPage().getParameters().get('levid');
        String urls = ApexPages.currentPage().getParameters().get('id');
        if(url != '' && url != null)
        {
            system.debug('$$$$$$$$$$$$$$$$$$$$$$state '+searchinput );
           if(searchinput != null)
           {
           
            lstsearch = [Select Level1__c,Name,cLevel1__r.Name, AccountName__c, Account__c ,cLevel1__c from Level1__c where cLevel1__c=:url   and  AccountName__c LIKE :(searchinput+'%') limit 500];
            lstsearch2 = [Select Level2__c,Name,cLevel2__r.Name, AccountName__c, Account__c ,cLevel2__c from Level2__c where cLevel2__c=:url   and  AccountName__c LIKE :(searchinput+'%') limit 500];
            lstsearch3 = [Select Level3__c,Name,cLevel3__r.Name, AccountName__c, Account__c ,cLevel3__c from Level3__c where cLevel3__c=:url  and  AccountName__c LIKE :(searchinput+'%') limit 500];
            lstsearch4 = [Select Level4__c,Name,cLevel4__r.Name, AccountName__c, Account__c ,cLevel4__c from Level4__c where cLevel4__c=:url   and  AccountName__c LIKE :(searchinput+'%') limit 500];
            lstsearch5 = [Select Level5__c,Name,cLevel5__r.Name, AccountName__c, Account__c ,cLevel5__c from Level5__c where cLevel5__c=:url  and  AccountName__c LIKE :(searchinput+'%') limit 500];
            lstsearch6 = [Select Level6__c,Name,cLevel6__r.Name, AccountName__c, Account__c ,cLevel6__c from Level6__c where cLevel6__c=:url  and  AccountName__c LIKE :(searchinput+'%') limit 500];

            system.debug('****search****'+lstsearch);
           // return lstLevel11 ;
           }
          
        }
    }
    
    /*radio*/
    public List<SelectOption> getItems()
{
   List<SelectOption> options = new List<SelectOption>(); 
   options.add(new SelectOption('All','All')); 
   options.add(new SelectOption('Selected Only','Selected Only'));     
   return options; 
}        
        
public string Level;           
public String getLevel() 
{
return Level;
}
public void setLevel(String Level) 
{ 
this.Level= Level; 
}
/*cuslevel start  */

    public class Level1sClass 
    {
        public String accURL;
        public string acid1{ get; set; }
        public Level1s__c lev1{ get; set; }
        public Level1s__c lev1Tree{ get; set; }
       // public Level1__c lev1AccTree{ get; set; }
        public Level1__c lev1IDTree{ get; set; }
        public List<Level2sClass> lev2 {get; set;}
        public List<Level2sClass> lev2Tree {get; set;}
        public integer chkcountL1 {get; set;} 
        public Boolean selected {get; set;}
        public Level1sClass(Level1s__c gp)
        {
            accURL= ApexPages.currentPage().getParameters().get('id');
            lev1 = gp;
            lev1Tree = gp;
            acid1 = accURL;
        /*    List<Level1__c> treelst1 = [Select Level1__c,Name,CusLevel1Name__c, AccountName__c, Account__c ,cLevel1__c from Level1__c where Account__c=:accURL];
            for(Level1__c le1: treelst1)
            {
             lev1IDTree =  le1;
             
            } */
           
            lev2 = getList2Details(gp); 
          //  lev2Tree = getTreeLevel2list(gp);
           
            if(accURL!= '' && accURL!= null)
            {
                  chkcountL1 = gp.Level1s__r.size();
                    if(chkcountL1  > 0 )
                        {
                            selected = true;
                           
                        }
                        else
                        {
                            selected = false;
                              
                        }
                      
             }  
 
        }
     }       
    public class Level2sClass
    {
        public String accURL;
        public level2s__c lev2 {get; set;}
        public level2s__c lev2Tree {get; set;}
        public Level2__c lev2IDTree{ get; set; }
        public List<Level3sClass> lev3 {get; set;}
        public List<Level3sClass> lev3Tree {get; set;}
        public Boolean selected {get; set;}
        public integer chkcountL2 {get; set;} 
        public Level2sClass(Level2s__c l2)
        {
           accURL= ApexPages.currentPage().getParameters().get('id');
           lev2 = l2;
           lev2Tree = l2;
         /*  List<Level2__c> treelst2 = [Select Level2__c,Name,CusLevel2Name__c, AccountName__c, Account__c ,cLevel2__c from Level2__c where Account__c=:accURL];
            for(Level2__c le1: treelst2)
            {
             lev2IDTree =  le1;
             
            } */
           lev3 = getList3Details(l2);
          // lev3Tree = getTreeLevel3list(l2);
          
           chkcountL2  = l2.Level2s__r.size();
            if(chkcountL2  > 0 )
            {
                selected = true;
               
            }
            else
            {
                selected = false;
                  
            }           
        }
    } 
    public class Level3sClass
    {
        public Level3s__c lev3 {get; set;}
        public Level3__c lev3IDTree{ get; set; }
        public List<Level4sClass> lev4 {get; set;}
        public Boolean selected {get; set;} 
        public integer chkcountL3{get; set;} 
        public Level3sClass(Level3s__c l3)
        {
            lev3 = l3;
          /*     List<Level3__c> treelst3 = [Select Level3__c,Name,CusLevel3Name__c, AccountName__c, Account__c ,cLevel3__c from Level3__c where Account__c=:accid];
            for(Level3__c le1: treelst3 )
            {
             lev3IDTree =  le1;
             
            }  */
            
            lev4 = getList4Details(l3);
            chkcountL3  = l3.Level3s__r.size();
            if(chkcountL3  > 0 )
            {
                selected = true;
               
            }
            else
            {
                selected = false;
                  
            }         
        }
    }
    public class Level4sClass
    {
        public Level4s__c lev4 {get; set;}
        public Boolean selected {get; set;}
        public integer chkcountL4{get; set;}
        public Level4sClass(Level4s__c l4)
        {
            lev4 = l4;
           // lstLevel4 = [Select Id,name,Level3__c,(select id, account__r.name from Level4s__r where account__c =: + accid ) from Level4s__c where Level3__c =:lev4.id limit 1 ]; 
            chkcountL4 = l4.Level4s__r.size();
            if(chkcountL4  > 0 )
            {
                selected = true;
               
            }
            else
            {
                selected = false;
                  
            }      
        }
    }
     List<Level1sClass> Level1List{get; set;}
    public List<Level1sClass> getList1Details()
    {
       if(Level1List == null)
       {       
            Level1List = new List<Level1sClass>();
          
            for(level1s__c k: lstLevel1 )
            { 
                Level1List.add(new Level1sClass(k)); 
            } 
       }     
          
        return  Level1List ;
    }
   
    public static  List<Level2sClass> Level2List; 
    public static List<Level2sClass> getList2Details(Level1s__c lvl) 
    {
          Level2List= new List<Level2sClass>(); 
          if(ApexPages.currentPage().getParameters().get('S') == null)
          {
              lstLevel2 = [Select id,name,Level1_Name__c,Level1__c, (select  id,account__r.name from Level2s__r where account__c =:accid  ) from Level2s__c where Level1__c =:lvl.id order by id]; 
             
          }else
          {
              lstLevel2 = [Select id,name,Level1_Name__c,Level1__c, (select  id,account__r.name from Level2s__r where account__c =:accid  ),(select id from Level3s__r limit 1) from Level2s__c where Level1__c =:lvl.id and id in (Select cLevel2__c from Level2__c where Account__c=:accid) order by id]; 
               
          }
              for(level2s__c s: lstLevel2)
              {
                Level2List.add(new Level2sClass(s));
              }
          
             
         return Level2List;  
    } 
    
    public static  List<Level3sClass> Level3List; 
    public static List<Level3sClass> getList3Details(Level2s__c lvl) 
    {
        Level3List= new List<Level3sClass>();  
        if(ApexPages.currentPage().getParameters().get('S') == null)
          {
               lstLevel3 = [Select Id,name,Description__c,Level2__c,(select id,account__r.name  from Level3s__r where account__c =: accid ),(select id from cusLevel4s__r limit 1)   from Level3s__c where Level2__c =:lvl.id ]; 
          }else
          {
             lstLevel3 = [Select Id,name,Description__c,Level2__c,(select id,account__r.name  from Level3s__r where account__c =: accid ),(select id from cusLevel4s__r limit 1)   from Level3s__c where Level2__c =:lvl.id and id in (Select cLevel3__c from Level3__c where Account__c =: accid) ];  
          }     
                
                 for(level3s__c s: lstLevel3)
                 {
                     Level3List.add(new Level3sClass(s));
                 }  
         
        return Level3List;          
    }
    public static  List<Level4sClass> Level4List; 
    public static List<Level4sClass> getList4Details(Level3s__c lv4) 
    {
        
        Level4List= new List<Level4sClass>(); 
          
             
    
        return Level4List;          
    }
 
/*cuslevel end */

/* $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ Save $$$$$$$$$$$$$$$$$$$$$$$$$$$$$ */


public PageReference Save()
{
   List<level1s__c> selectLevel1 = new List<level1s__c>();
     
       
    //this.stdController.save();
    

    /////////// LEVEL1 ///////////////////
    List<level1s__c> selectedLevel1 = new List<level1s__c>(); 
    
    for(Level1sClass cCon: getList1Details() )
    {
         system.debug('cCon'+cCon.selected);
        if(cCon.selected == true)
        {
            system.debug('firstCCCCCCCCCC:'+cCon.lev1);
            selectedLevel1.add(cCon.lev1);
        }
    }           
     
    Level1__c[] levl1= [Select Id from Level1__c where Account__c=: ApexPages.currentPage().getParameters().get('id')]; 
    delete levl1; 
    if(selectedLevel1 != null)
    {     
        for(level1s__c con : selectedLevel1)
        {
            system.debug('CCCCCCCCCC:'+con+'\n');
            string acctid =ApexPages.currentPage().getParameters().get('id');
            List<Level1__c> lvl1obj= new  Level1__c[0];
            lvl1obj.add(new Level1__c(Name='Level1',Account__c=acctid,cLevel1__c=con.id));
            insert lvl1obj;
    
        }
    }    
    //////////// LEVEL2 ////////////////////
    List<level2s__c> selectedLevel2 = new List<level2s__c>(); 
    
 
    for(Level2sClass cCon:getList2Details())
    {
    
         system.debug('cCon'+cCon.selected);
        if(cCon.selected == true)
        {
            system.debug('firstCCCCCCCCCC:'+cCon.lev2);
            selectedLevel2.add(cCon.lev2);
        }
    }           
     
    Level2__c[] levl2= [Select Id from Level2__c where Account__c=: ApexPages.currentPage().getParameters().get('id')]; 
    delete levl2; 
    if(selectedLevel2 != null)
    {     
        for(level2s__c con : selectedLevel2)
        {
            system.debug('CCCCCCCCCC:'+con+'\n');
            string acctid =ApexPages.currentPage().getParameters().get('id');
            List<Level2__c> lvl2obj= new  Level2__c[0];
            lvl2obj.add(new Level2__c(Name='Level2',Account__c=acctid,cLevel2__c=con.id));
            insert lvl2obj;
           
         }
    }
  
    return null;
    
}

 

 

trigger Trigger1 on Task (after insert,after update)
{
List<String> mlist = new List<String>();
List<String> mailAddrs = new List<String>();
String fURL = URL.getSalesforceBaseUrl().toExternalForm() ;


for(Task t : Trigger.new)

{
Account act = [select Name from Account where Id =: t.AccountId];
if(t.Status == 'Completed')
{
if( t.Activity_Type__c == 'Resolved')
{

Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = 'SET A'];

for (GroupMember gm : g.groupMembers)
{
mlist.add(gm.userOrGroupId);
}

User[] usr = [SELECT email FROM user WHERE id IN :mlist];
for(User u : usr)
{
mailAddrs.add(u.email);

}
}
else if ( t.Activity_Type__c == 'Completed')

{
Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = 'SET B'];
for (GroupMember gm : g.groupMembers)

{
mlist.add(gm.userOrGroupId);
}

User[] usr = [SELECT email FROM user WHERE id IN :mlist];
for(User u : usr)
{
mailAddrs.add(u.email);
}
}

else if ( t.Activity_Type__c == 'In Progress')

{
Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = 'SET C'];
for (GroupMember gm : g.groupMembers)

{
mlist.add(gm.userOrGroupId);

}
User[] usr = [SELECT email FROM user WHERE id IN :mlist];
for(User u : usr)
{
mailAddrs.add(u.email);
}
}

else if ( t.Activity_Type__c == 'On Hold')

{
Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = 'SET D'];
for (GroupMember gm : g.groupMembers)

{
mlist.add(gm.userOrGroupId);

}
User[] usr = [SELECT email FROM user WHERE id IN :mlist];
for(User u : usr)
{
mailAddrs.add(u.email);
}
}

else
{
Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = 'SET E'];

for (GroupMember gm : g.groupMembers) {
mlist.add(gm.userOrGroupId); }

User[] usr = [SELECT email FROM user WHERE id IN :mlist];
for(User u : usr) { mailAddrs.add(u.email); }

}

if(mailAddrs != null || mailAddrs.size() > 0)
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

mail.setToAddresses(mailAddrs);

mail.setSubject(t.Activity_Type__c+' : '+act.Name+' Task Information');

mail.setPlainTextBody(' Contact Report has been completed '+'\n'+fURL+'/'+t.Id);

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

}
}

 

The above trigger is working fine. Can any one help to avoid Governor limits for this trigger. by using collections can do it. but am not able fix it please help me on this.

  • October 15, 2013
  • Like
  • 0

Im not using a sandbox but testing towards the actual database. This is the query I'm trying:

 

Select (Select Id, CurrencyIsoCode, Postcode_lookup__c From Post_code_company__r) From Postal_code_lookup__c 

 

The result Im looking for is not objects itselfs, but I want a list of the child records. Im not sure how to acomplish this since there seem to be no __r object to getch data from? How can you do this query?

Anyone have a technique for getting the timestamp of when a new Lead entry page is opened and still retain the ability to use the standard Page Layout capability?

 

I know that this is possible if a custom VF page is constructed, but we want to use the standard Page Layout editor with Record Types, etc. 

 

There was a suggestion that the NOW() function could be put into a custom Lead formula field to capture when the page was opened then used in a before insert trigger to calculate the time difference, but the NOW() function seems to continuously update whenever the field is accessed.

 

Any suggestions would be greatly appreciated.  Thanks.

How to query a file id from a custom objects Notes and Attachment and append this id to the salesforce's url?

 

can someone help me with the code

Datetime insdate;
insdate = 2013-10-07 00:00:00;
System.debug(insdate);

 

when i try to execute this as  annonymous, I get the error unexpected token: '2013-10-07'

 

My question is, How do we assign a datetime value to a variable?

Hi,

 

I am trying to call a future method from a before trigger.

 

Insert Operation is hapening fine.

 

Update, Delete are not getting executed.

 

Delete is failed with Error333: []

 

Update is failed with an error like 

Future method cannot be called from a future or batch method: MyFutureClass.myMethod(Id)

Please suggest.

 

trigger futurecheck on Account (after update) 

{
   system.debug('Name issssss ' + Trigger.NEW[0].name);
   Account acc = [SELECT name FROM Account WHERE name = 'Thru Future'];
   MyFutureClass.myMethod(acc.Id);
   
}


global class MyFutureClass
{

@future (callout=false)
Public static void myMethod(Id i)
{
System.debug('Method calleddddddd '+ i);

try {
acc.AccountSource='Phone Inquiry';
update acc;
}
catch (DmlException e) {


}

 

hi all,

 

i've been triyng to pull data from a remote service and have managed to get connected and can see in the logs that my child items are being read - my only issue is that the new records that I want creating aren't being created.

 

here is my code can anyone see what this isn't created montioring forms - the apex is triggered when we create a new form, basically it will then go off and check the remote service for any new forms on the server.

 

cheers

dan

 

public class MonitoringFormsUpdater {
  //Future annotation to mark the method as async.
  @Future(callout=true)
  public static void updateMF() {
    //construct an HTTP request
    Http http = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://magpi.com/api/surveys?username=myusername&accesstoken=myaccesstoken');
    req.setMethod('POST'); 
    //send the request
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
    // list object ready for insert 
    List<Monitoring_Form__c> newforms = new List<Monitoring_Form__c> ();
    string s = res.getBody();
    Dom.Document docx = new Dom.Document();
        docx.load(s);
        dom.XmlNode xroot = docx.getrootelement();
        dom.XmlNode [] xrec = xroot.getchildelements(); //Get all Record Elements
        for(Dom.XMLNode child : xrec) //Loop Through Records
            {
            Monitoring_Form__c mf = new Monitoring_Form__c();
        for(dom.XmlNode magpi : child.getchildren() ) {
           if (magpi.getname() == 'SurveyId') {
                   mf.form_id__c = magpi.gettext();
             }
           if (magpi.getname() == 'SurveyName') {
                   mf.name = magpi.gettext();
             }  
         }
        newforms.add(mf);
        }
  }
}

 the remote service returns this xml file.

 

<Surveys>
<Survey>
<SurveyId>7471</SurveyId>
<SurveyName>Bole_ASD_JHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7450</SurveyId>
<SurveyName>Bole_ASD_Pri</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7493</SurveyId>
<SurveyName>Bole_ASD_SHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7474</SurveyId>
<SurveyName>Bongo_ASD_JHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7494</SurveyId>
<SurveyName>Bongo_ASD_SHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
</Surveys>

So I'm trying to run some code through the developer console with execute anonymous. 

 

Anytime I try to run the code, it hangs for a second at Sending Request, then just shows Execution Failed and...that's it. No error message, nothing. Since I'm not getting an error message, I'm not really sure what's going wrong. It was working just fine a few days ago with the exact same code I'm trying to run now. Anyone ever see this issue before?

Hi, 

 

I am trying to check if an integer field has a string value , if yes display an error. 

 

if(totalunit != '' && totalunit != null && !Pattern.matches('\\d*', totalunit)){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'WARNING: Total Unit Quanitity Requested Only Accepts Number.'));
return null;
}

 

I am facing an error saying " Comparison arguments must be compatible types: Integer, String".

 

I would appreciate any help or pointers ...

 

Thank you 

 

Problem statement:

 

When APEX inserting OpportunityShare records, you get DML Exception: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY

 

Why does this happen?

 

The obvious reasons are:

 

  • OpportunityShare.OpportunityId is for an invalid Opportunity (or not an opportunity at all)
  • Running user doesn't have access to the Opportunity in OpportunityId



But if neither of these are the case...what else could it be?

 

ANSWER:

 

You can not insert OpportunityShare records for the current owner of the record.  You'll need to modify the Apex code to see if the current owner is the same as OpportunityShare.UserOrGroupId.  If it is, then don't insert.  You can still create OpportunityTeamMember records for that user but not OpportunityShare.  Who the current user is will depend if you are doing the OpportunityShare Dml statement in a before trigger, after trigger, VF controller, or API.

 

Although I haven't tested this, I presume the above applies to AccountShare and CaseShare objects as well.

Problem statement:

 

When APEX inserting OpportunityShare records, you get DML Exception: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY

 

Why does this happen?

 

The obvious reasons are:

 

  • OpportunityShare.OpportunityId is for an invalid Opportunity (or not an opportunity at all)
  • Running user doesn't have access to the Opportunity in OpportunityId



But if neither of these are the case...what else could it be?

 

ANSWER:

 

You can not insert OpportunityShare records for the current owner of the record.  You'll need to modify the Apex code to see if the current owner is the same as OpportunityShare.UserOrGroupId.  If it is, then don't insert.  You can still create OpportunityTeamMember records for that user but not OpportunityShare.  Who the current user is will depend if you are doing the OpportunityShare Dml statement in a before trigger, after trigger, VF controller, or API.

 

Although I haven't tested this, I presume the above applies to AccountShare and CaseShare objects as well.