• Tarun Suri
  • NEWBIE
  • 45 Points
  • Member since 2015
  • Salesforce Developer and Consultant

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 19
    Replies
Hi guys.

Looking for a piece of code to allow me to Validate that one or the other field has a value inside. These are custom fields in VF so i cant create a object validation rule as these are just input text fields.

e.g. Field 1 or Field 2 must be mandatory.

Using a standard controller and Ext Controller. 

Any help would be great.

Nick

 
How can I get the whole pagelayout and fields of an object and set it into a vf page in Edit Mode? I want to make it dynamic means if i create a new field and set it into my standard page layout it should automatically be shown in my Visualforce PageLike we have <apex:Detail> for detail page but I want it for Edit Mode.
Trying to get the response on rest explorer workbench. My salesforce Url is "https://tarunlight-dev-ed.my.salesforce.com/" and getting problem in having the Get Response with the URI "/services/apexrest/Cases/". Getting 404 error: Not Found. 
my requirement is when we convert a lead we usually get new account, new contact and ooportunity but i dont want to create contact. so am trying to achieve this through trigger on lead before update but its not working for me . can anyone help me to write a trigger on this requiremnet. here is what i have written which is not working. 
 
trigger NoContact on Lead (before update) {
    list<lead> newlead = trigger.new;
    list<contact> conlead=new list<contact>();
    for(lead lead1:newlead){
    if(trigger.new.size()>1){
        if(trigger.old[0].isconverted==false && trigger.new[0].isconverted==true){
            if (Trigger.new[0].ConvertedContactId != null) {
            contact con= new contact(Id=newlead[0].ConvertedContactId);
                conlead.add(con);
                system.debug('conlead :' +conlead);
        }
        	}
    }
        
    }
    delete conlead;
}

 
 i am trying to write a test class on a simple trigger below but getting error
 
1. trigger accountrevenue on Account (before insert) {
2. list<account> acc=trigger.new;
3. for(account accs:acc){
4. if(accs.industry=='Banking')
5. accs.annualRevenue=5000000;
6. }
7. }



======================================
 
1. @isTest public class AnnualTest {
2. @isTest
3. static void testme(){
4. Integer count=[select count() from Account];
5. Account a1=new Account(Name='aaa',Industry='Banking');
6. Account a2=new Account(name='bbb',Industry='Energy');
7. try{
8. insert a1;
9. insert a2;
10. } catch(Exception e) {
11. System.debug(e);
12. }
13. Integer size=[select count() from Account];
14. System.assertEquals(size,count+2);
15. Account acc=[select annualrevenue from Account where id=:a1.id];
16. System.assertEquals(acc.annualRevenue,5000000);
17. Account acc1=[select annualrevenue from Account where id=:a2.id];
18. System.assertNotEquals(acc1.annualRevenue,a1.AnnualRevenue);
19. }
20. }



============================================
TestRun result = Fail
TestRun Error = System.AssertException: Assertion Failed: Expected: 0, Actual: 2
TestRun Stack trace = Class.AnnualTest.testme: line 14, column 1
I have one custom object and I have custom field which is lookup to account in the same object.
When record inserted in this custom object, I want create a task under open activities in account object. (Task shoud get create under same name of the account which we select from lookup field in custom object)

I want to write trigger for the same.
Please share syntax, if any one has syntax.
I'm having an issue trying to show ID, NAME, and URL of attachment based on who uploaded it. Problem is the code is showing results even without an attachment.... Can someone please look at my code and help me understand why?
Again, I need the page to show Attachment NAME, ID, Client NAME, ID and URL to attachment.

APEX CLASS
 
public with sharing class DisplayAttachments{
public List<Account> Records {get; set;}
public DisplayAttachments(){
    String userId = userinfo.getUserId();
    Records = [select Id,Name,(Select Id,Name from Attachments) From Account Where CreatedById =:userId];
    }
}

VISUALFORCE PAGE
 
<apex:page controller="DisplayAttachments" >

    <apex:pageBlock title="{!$User.FirstName} {!$User.LastName}'s Attahments">       

    <apex:pageBlockTable value="{!Records}" var="Record">

     <apex:column >

     <apex:facet name="header">Client ID</apex:facet>

     <apex:outputText value="{!Record.Id}"/>

     </apex:column>

     <apex:column >

     <apex:facet name="header">Client Name</apex:facet>

     <apex:outputText value="{!Record.Name}"/>

     </apex:column>

     <apex:column >

     <apex:facet name="header">Attachment ID</apex:facet>

        

        <apex:pageBlockTable value="{!Record.Attachments}" var="a">

            <apex:column >

                <apex:outputField value="{!a.Id}"/>

            </apex:column>

        </apex:pageBlockTable>
         

     </apex:column>
     

     <apex:column >

     <apex:facet name="header">Attachment Name</apex:facet>

         <apex:pageBlockTable value="{!Record.Attachments}" var="a">

            <apex:column >

                 <apex:outputField value="{!a.Name}"/>

            </apex:column>

        </apex:pageBlockTable>

     </apex:column>-->

       </apex:pageBlockTable>

     </apex:pageBlock>
       
     </apex:page>

 
Hi All,

I getting the field values (Is_Locked__c & Locked_By__c )from old content version(previous),but these field values are returning NUll.

Use case: For first time on uploading the "new version" of document from chatter feed items, updating the field values Is_Locked__c to "True" and Locked_By__c to username.

And second time when uploading new version for feed item, i am getting the field values (Is_Locked__c& Locked_By__c) of previous content version and comparing. But i am getting Null values for these field values (Is_Locked__c & Locked_By__c).

I am using the below code and please help me to get updated field values instead null value,instead referring to correct document (Previous content version)?

Thanks in Advance.

Code:

Trigger ContentVersionStop_trigger on ContentVersion (before insert, before update) { 

       // Getting the current username
       String userName = UserInfo.getUserName();
       User activeUser = [Select name From User where Username = : userName limit 1];
       String currentusername = activeUser.name;
       system.debug('Current user:' + currentusername );
       system.debug('Trigger New:' + Trigger.new);


   ContentVersion oldCV = [Select Id,CreatedDate, PathOnClient, ContentUrl, Is_Locked__c, Locked_By__c, Title from ContentVersion Order By CreatedDate Desc Limit 1];   

  for (ContentVersion cv : Trigger.new) {

    if (oldCV.Is_Locked__c == NULL && oldCV.Locked_By__c==NULL)
      { 
       system.debug('Into Null Loop:' +oldCV.Is_Locked__c);
      cv.Is_Locked__c='True';
      cv.Locked_By__c=currentusername;
       System.debug('records1 are ' + cv);
      }
      else if(oldCV.Is_Locked__c == 'True' && oldCV.Locked_By__c==currentusername )
      {
      system.debug('Into locked Loop:' +oldCV.Is_Locked__c);
      cv.addError('Version is locked');
      } 
  }
}
Hi..
I am new in salesforce. And i want to create a dashboard through which i can show the status of the org. I have shown the apex classes, and custom object with custom field count now i want to show the Validation rules and workflow count.

I have studied that it is possible throug Metadata API but i don't know how can i use them in salesforce apex class
Please help me to write the code for following conditions:

1) Add Opportunities programmatically.
2) List items of opportunities.
3) List opportunities created by X user.

Thanks in advance
  • August 16, 2016
  • Like
  • 0
Hi Guys
I have created a Vf page like
<b>Start Date</b><apex:inputField value="{!j.From_Date__c}"  />&nbsp;&nbsp;&nbsp;
     <b>End Date</b><apex:inputField value="{!j.To_Date__c}" />
     <apex:commandButton value="Go" action="{!displaingTable}" style="background:green"/>
      <b><apex:commandLink id="printable"  onclick="JavaScript:window.print();" value="Print"/></b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
User-added image

but i am making mandatory the date field using required="true"
<b>Start Date</b><apex:inputField value="{!j.From_Date__c}"  required="true"/>&nbsp;&nbsp;&nbsp;
     <b>End Date</b><apex:inputField value="{!j.To_Date__c}" required="true"/>
     <apex:commandButton value="Go" action="{!displaingTable}" style="background:green"/>
      <b><apex:commandLink id="printable"  onclick="JavaScript:window.print();" value="Print"/></b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
User-added image

so how to arrange the field in same line when i am using required field...
 
I am trying to update the field of the child object when the type field in case is changed, but iam getting empty child list
system.debug('c.Casechilds__r'+c.Casechilds__r);, can some one help me on this

debug logs is as follows
11:06:12.0 (3510151)|SOQL_EXECUTE_BEGIN|[8]|Aggregations:1|SELECT id, (SELECT id, Field_to_update__c FROM Casechilds__r) FROM case WHERE id IN :tmpVar1 11:06:12.0 (9078923)|SOQL_EXECUTE_END|[8]|Rows:1 11:06:12.0 (9255628)|USER_DEBUG|[9]|DEBUG|caseList(Case:{Id=5002800000O4w0fAAB}) 11:06:12.0 (9310150)|USER_DEBUG|[10]|DEBUG|caseIds (5002800000O4w0fAAB) 11:06:12.0 (10027977)|USER_DEBUG|[12]|DEBUG|cCase:{Id=5002800000O4w0fAAB, IsDeleted=false, CaseNumber=00001027, ContactId=null, AccountId=null, AssetId=null, BusinessHoursId=01m28000000DrvlAAC, ParentId=null, SuppliedName=null, SuppliedEmail=null, SuppliedPhone=null, SuppliedCompany=null, Type=Electrical, Status=New, Reason=null, Origin=Phone, Subject=null, Priority=Medium, Description=null, IsClosed=false, ClosedDate=null, IsEscalated=false, OwnerId=00528000002LYzBAAW, IsClosedOnCreate=false, CreatedDate=2016-08-09 05:34:43, CreatedById=00528000002LYzBAAW, LastModifiedDate=2016-08-09 05:36:12, LastModifiedById=00528000002LYzBAAW, SystemModstamp=2016-08-09 05:36:12, LastViewedDate=null, LastReferencedDate=null, EngineeringReqNumber__c=null, SLAViolation__c=null, Product__c=null, PotentialLiability__c=null} 11:06:12.0 (10168326)|USER_DEBUG|[13]|DEBUG|c.Casechilds__r() 11:06:12.10 (10443794)|CUMULATIVE_LIMIT_USAGE 11:06:12.10 (10443794)|LIMIT_USAGE_FOR_NS|(default)|
trigger updateChild on Case (after insert, after update){
    list<id> caseIds = new list<id>();
    list<id> childCaseIds = new list<id>();
    for(case c:trigger.new){
        caseIds.add(c.id);
    }
    
   list<case> caseList= [select id,(select id,Field_to_update__c from Casechilds__r)from case where id IN : caseIds ];
   system.debug('caseList'+caseList);
   system.debug('caseIds '+caseIds );
   for(case c : trigger.new){
       system.debug('c'+c);
       system.debug('c.Casechilds__r'+c.Casechilds__r);
       for(Case_child__c casechild :c.Casechilds__r){
           system.debug('casechild '+casechild );
           casechild.Field_to_update__c  = c.type;
           system.debug('casechild.Field_to_update__c'+casechild.Field_to_update__c);
           childCaseIds.add(casechild.id);
           system.debug('childCaseIds'+childCaseIds);
       }
      }
   // update childCaseIds;

}

 
Hi guys.

Looking for a piece of code to allow me to Validate that one or the other field has a value inside. These are custom fields in VF so i cant create a object validation rule as these are just input text fields.

e.g. Field 1 or Field 2 must be mandatory.

Using a standard controller and Ext Controller. 

Any help would be great.

Nick

 
Hello,
i created favicon in salesforce,i created favicon 16*16.that is save i desktop.
what are the "NEXT STEPS" i set favicon in salesforce?
Hello,

  I am creating a web to lead form. In that form i am using picklist filed. I want to make this picklist field required on visualforce page. I am not able to do it using required ="true". What will be other solution.

<section class="form-row">
<label for="Interested In">Interested In:</label>
<section class="select-outer">
<select class="select" id="00N36000006Q84K" name="00N36000006Q84K" title="Interested In" required="true">
<option value="">Please select</option>
<option value="Mobile Apps">Mobile Apps</option>
<option value="Web Apps">Web Apps</option> <option value="Salesforce">Salesforce</option>
<option value="Technical Support">Technical Support</option>
<option value="Application Support">Application Support</option>
</select>
</section>
</section>
hey how should i write test class for this controller

global class AutoCompleteLookupController {
    
    @RemoteAction
    global static SObject[] findSObjects(string obj, string qry,Integer recordCount,String accountId, string addFields) {
        // more than one field can be passed in the addFields parameter
        // split it into an array for later use
        List<String> fieldList;
        if (String.isNotBlank(addFields)) fieldList = addFields.split(',');
       // check to see if the object passed is valid
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        Schema.SObjectType sot = gd.get(obj);
        if (sot == null) {
            // Object name not valid
            return null;
        }
        // create the filter text
        String filter = ' like \'%' + String.escapeSingleQuotes(qry) + '%\'';
        //begin building the dynamic soql query
        String soql = 'select id, Name';
        // if an additional field was passed in add it to the soql
        if (fieldList != null) {
            for (String s : fieldList) {
                soql += ', ' + s;
            }
        }
        // add the object and filter by name to the soql
       if(recordCount > 15){
          soql += ' from ' + obj + ' where Company__c =:accountId AND name' + filter;
       }else{
           soql += ' from ' + obj + ' where Company__c =:accountId';
       }
        // add the filter by additional fields to the soql
        if (fieldList != null && recordCount > 15) {
            for (String s : fieldList) {
                soql += ' or ' + s + filter;
            }
        }
        soql += ' order by Name limit 20';
        List<sObject> L = new List<sObject>();
        try {
            L = Database.query(soql);
        }
        catch (QueryException e) {
            return null;
        }
        return L;
   }
}



 
Hi,

I have one SOQL query like 
I want Reocrd Type Label name , Is it possible to get using dynamic apex...........................

Adv Thnx
VSK
  • April 26, 2016
  • Like
  • 0

Hi,

I am trying to deploy some code from a sandbox to production but I'm getting the error message that my companys code coverage is 74%.

When I check one of the apex classes in my change set - it has the code coverage of 44% but it doesn't have any test class associated with it.
Is it possible to increase this code coverage for the apex class without creating a test class (this deployment has been the only one to return the error)? Can I add something into the class so that I could increase the coverage to 55% - does commenting count or using system.debug?

Controller:-

public with sharing class MyLoginController{


private ApexPages.StandardController controller;
public Login__c login{get;set;}
public id loginId{get;set;}


//constructor
public MyLoginController(ApexPages.StandardController controller) {
 this.controller=controller;
 this.login= (Login__c)Controller.getRecord();
 System.debug('@@@@@'+login.Id);


}



//Login method when user clicks on login button
public ApexPages.PageReference LoginMethod() {
system.debug('&&&&&&&&'+login);

loginId = [SELECT Id FROM Login__c 

                      WHERE Name =: login.Name].Id;
string password = [SELECT password__c FROM Login__c 

                      WHERE Name =: login.Name].password__c;
                      
             system.debug('!!!!!!!!'+login.Name);
           
       
        
        system.debug('@@@'+password);
        
        if(login.password__c==password) {
        system.debug('%%%%%%');
        PageReference redirectPage = new PageReference ('/apex/Nomination_msg');
        //redirectPage.setRedirect(true);
        //redirectPage.getParameters().put('id',controller.getId());
        
        return redirectPage;
        }
        else{

        login.Name.addError('Incorrect username or password.Please Enter correct value.');
        return null;
        }


}



//save method when user clicks on save button on nomination msg page
public pagereference save(){
login__c l= [select name,password__c,First_Name__c,Last_Name__c,age__c,Email__c,Country_of_user__c from login__c where id =: loginId ];
l.First_Name__c=login.First_Name__c;
l.Last_Name__c=login.Last_Name__c;
l.age__c=login.age__c;
l.Email__c=login.Email__c;
l.Country_of_user__c=login.Country_of_user__c;
update l;
try{
       system.debug('Entered into the Method');
    PageReference redirectPage = new PageReference ('/apex/successful_msg');
        return redirectPage;
             return null;
                }
    Catch(Exception dmle){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error'));
    //ApexPages.addMessages(dmle);
    //ApexPages.addMessage(myMsg);
    return null;
    } 
    }           




//signup method when the user clicks on signup button on login page
public pagereference signup() {
Pagereference pg=new Pagereference('https://ap2.salesforce.com/066280000027Mwq');
try{
system.debug('@@@###$$$$%%%%');
  PageReference redirectPage = Page.SignupPage;
               redirectPage.setRedirect(true);
                 return redirectPage;
              }
                 
      Catch(Exception dmle){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error'));
    //ApexPages.addMessages(dmle);
    //ApexPages.addMessage(myMsg);
    }          
return null;
}




//submit method when the user clicks on submit button on signup page
public pagereference Submit(){
login__c lp=new login__c();
lp.Name=login.Name;
lp.password__c=login.password__c;
lp.RePassword__c =login.RePassword__c ;
try{
 PageReference redirectPage = new PageReference ('/apex/Nomination_msg_a');
       system.debug('Entered into the Method');
          if(login.Password__c == login.Repassword__c) {
               Insert lp;
                return redirectPage;
                }
                else {
                login.Repassword__c.adderror('Please enter correct password');
                redirectPage.setRedirect(false);
                return null;
                }
                }
    Catch(Exception dmle){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error'));
    //ApexPages.addMessages(dmle);
    //ApexPages.addMessage(myMsg);
    return null;
    } 
}





//savesignup method when user clicks on save option on Nomination_msg_a page
public pageReference savesignup(){
loginId = [SELECT Id FROM Login__c WHERE Name =: login.Name].Id;
login__c log=[select name,password__c,First_Name__c,Last_Name__c,Age__c,Email__c,Country_of_user__c, id from login__c where id =: loginid];
log.First_Name__c=login.First_Name__c;
log.Last_Name__c=login.Last_Name__c;
log.Age__c=login.Age__c;
log.Email__c=login.Email__c;
log.Country_of_user__c=login.Country_of_user__c;
update log;
system.debug('&&&&&&&'+log);
try{

       system.debug('Entered into the Method');
       
            PageReference redirectPage = new PageReference ('/apex/successful_msg');
                return redirectPage;
                }
                
    Catch(Exception dmle){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error'));
    //ApexPages.addMessages(dmle);
    //ApexPages.addMessage(myMsg);
    return null;
    } 



}

test class:-

@isTest
public class MyLoginControllerTest{

static List<login__c > Lstlogs = new List<login__c >();

public static testMethod void oppExtensionTest(){
Test.startTest();
login__c login=new login__c();
login.Name=login.id;
login.Password__c='sss';
login.First_Name__c ='Shruthi GM';
login.Last_Name__c ='GM';
login.age__c =12;
login.Email__c ='shruthi.gm@tcs.com';
login.Country_of_user__c ='India'; 
insert login;

login__c login1=new login__c();
login1.Name=login1.id;
login1.Password__c='test';
login1.First_Name__c ='Shruthi GM';
login1.Last_Name__c ='GM';
login1.age__c =12;
login1.Email__c ='shruthi.gm@tcs.com';
login1.Country_of_user__c ='India'; 
insert login1;


ApexPages.StandardController controller;
controller = new ApexPages.StandardController(login);
MyLoginController mec = new MyLoginController(controller);
ApexPages.currentPage().getParameters().put('id',login.id);
PageReference testPage = mec.save();
PageReference testPage1 = mec.signup();
PageReference testPage2 = mec.submit();
PageReference testPage3 = mec.savesignup();

ApexPages.StandardController controller1;
controller1 = new ApexPages.StandardController(login1);
MyLoginController mec1 = new MyLoginController(controller1);
ApexPages.PageReference testing1 = mec1.LoginMethod();
PageReference testPage4 = mec1.save();
PageReference testPage5 = mec1.signup();
PageReference testPage6 = mec1.submit();
PageReference testPage7 = mec1.savesignup();
Test.stopTest();
}

Please help.

 
Hello,

Please, could you help me to determine which is the issue in this code? I am trying to update a list of records related (through a lookup field) to the object which is being modified.
 
public class HandlerResources {
    public static void handleAfterInsert(List<Resource__c> ResourceList) { 
        List <Project__c> ProjectsToUpdate = new List<Project__c>();
            for (Resource__c currentResource : ResourceList) {
                if (currentResource.Project__c != '') {
                    for (Project__c Project : currentResource.Project__c.Id) {
                    Project.Hours__c = Project.Hours__c + currentResource.Hours__c;
                	ProjectsToUpdate.add(Project);
                    }
                }
            }
        Database.update(ProjectsToUpdate);
    }
}

Thank you very much!
Jesus
 i am trying to write a test class on a simple trigger below but getting error
 
1. trigger accountrevenue on Account (before insert) {
2. list<account> acc=trigger.new;
3. for(account accs:acc){
4. if(accs.industry=='Banking')
5. accs.annualRevenue=5000000;
6. }
7. }



======================================
 
1. @isTest public class AnnualTest {
2. @isTest
3. static void testme(){
4. Integer count=[select count() from Account];
5. Account a1=new Account(Name='aaa',Industry='Banking');
6. Account a2=new Account(name='bbb',Industry='Energy');
7. try{
8. insert a1;
9. insert a2;
10. } catch(Exception e) {
11. System.debug(e);
12. }
13. Integer size=[select count() from Account];
14. System.assertEquals(size,count+2);
15. Account acc=[select annualrevenue from Account where id=:a1.id];
16. System.assertEquals(acc.annualRevenue,5000000);
17. Account acc1=[select annualrevenue from Account where id=:a2.id];
18. System.assertNotEquals(acc1.annualRevenue,a1.AnnualRevenue);
19. }
20. }



============================================
TestRun result = Fail
TestRun Error = System.AssertException: Assertion Failed: Expected: 0, Actual: 2
TestRun Stack trace = Class.AnnualTest.testme: line 14, column 1

I am trying to write a formula which compares 2 criteria, for quarterly reporting purposes.  One is a picklist value and one is a text formula field.  The scenario is this:

 

If ISPICKVAL = "MGM" and EXHIBITION MONTH = "JAN" THEN "MAR", EXHIBITION MONTH

 

OR

 

If ISPICKVAL = "MGM" and EXHIBITION MONTH = "FEB" THEN "MAR", EXHIBITION MONTH

 

OR

 

If ISPICKVAL = "MGM" and EXHIBITION MONTH = "APR" THEN "JUN", EXHIBITION MONTH...etc

 

Please help if you can.  Thanks!