• jsacpt24
  • NEWBIE
  • 30 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 15
    Replies
I am running into an issue with my data building class that we are using for test methods. I have a method that is supposed to 'createSaleRelatedContact'. It inserts the account then creates a user account. Once it has created those it will then create the contact record. After it creates those contact records it is supposed to create the sale related contact records and use the contact records from the previous list. and insert those new records. We have a validation rule set that it cannot create these records with Null contact values. When we set the debugs it is pulling null values into this list for SRC. Not sure why it is pulling a null id if we are inserting this list prior to? Am I doing something wrong here? 
 
public with sharing class CC_UnitTestUtil {
	
	static Database.DMLOptions dml = new Database.DMLOptions();
	
	public static void createCustomSetting(String Area) {
		// P Sutherland Area Added for Trigger 
        CC_Area_to_Process__c cca = new CC_Area_to_Process__c(Name=Area,TimeZoneSidKey__c='America/Phoenix');
        upsert cca;
	}
    
    public static list<Sale_Related_Contact__c> createSaleRelatedContact(Id saleId,  list<String> types){
        boolean dmActive = Utils.duplicateMgmtActive('Contact');        
        dml.DuplicateRuleHeader.allowSave = true;
        Account a = new Account(Name = 'TestAcct');
        if (dmActive)
            database.insert(a, dml);
        else
            insert a;
        SuperUserAccount__c sua = new SuperUserAccount__c(AccountID__c = a.Id, Name='Contact1');
        try{insert sua;}catch(Exception e){}
        system.debug('@-@ SuperUserAccount__c '+ sua.id);
        list<Contact> conts = new list<Contact>();
        for(Integer i=0;i<types.size();i++){
            Contact c = new Contact(LastName=types[i], FirstName=types[i], Email='test@test.com', AccountId= a.id, Related_Company__c= a.Id);
            if ( types[i] == 'Design Studio' || types[i] == 'Additional Meritage Employee')    
            	c.User_ID__c = UserInfo.getUserId();
            conts.add(c);
            system.debug('@-@ User id '+ c.User_ID__c);
        }
        if (dmActive)
            database.insert(conts, dml);
        else
            insert conts;
        system.debug('@-@ contact List after insert ' + conts);
		system.debug('@-@ contact id after insert ' + conts[0].id);
        
        list<Sale_Related_Contact__c>  src = new list<Sale_Related_Contact__c> ();
        
        for(Integer i=0;i<types.size();i++){
            Sale_Related_Contact__c sr = new Sale_Related_Contact__c();
            sr.Sale__c = saleId;
            sr.Type__c = types[i];
            sr.Company_Name__c = a.id;
            sr.Contact__c = conts[i].Id;
            src.add(sr);
            system.debug('@-@ ids for SRC ' + sr.Contact__c);
        }
        
        system.debug('@-@ size = ' + src.size());
        if(src.size()>0){
            insert src;
        }
        return src;
    }
    public static List<Sale_Related_Contact__c> createSaleRelatedContactMonterey(Id saleId,  List<String> types){
        boolean dmActive = Utils.duplicateMgmtActive('Contact');        
        dml.DuplicateRuleHeader.allowSave = true;        
        Account a = new Account(Name = 'TestAcct');
        if (dmActive)
            database.insert(a, dml);
        else
            insert a;
        SuperUserAccount__c sua = new SuperUserAccount__c(AccountID__c = a.Id, Name='Contact1M');
        insert sua;
        list<Contact> conts = new list<Contact>();
        for(Integer i=0;i<types.size();i++){
            Contact c = new Contact(LastName=types[0], FirstName='John', Email='test2346234@test.com', AccountId= a.id, Related_Company__c= a.Id);    
            conts.add(c);
        }
        if (dmActive)
            database.insert(conts, dml);
        else
            insert conts;
        list<Sale_Related_Contact__c>  src = new list<Sale_Related_Contact__c> ();
        
        for(Integer i=0;i<types.size();i++){
            Sale_Related_Contact__c sr = new Sale_Related_Contact__c();
            sr.Sale__c = saleId;
            sr.Type__c = types[i];
            sr.Company_Name__c = a.id;
            sr.Contact__c = conts[i].Id;
            src.add(sr);
        }
        if(src.size()>0){
            insert src;
        }
        return src;
    }
    // create sale
    public static list<Sale__c> createSale(List<Lot__c> lots, List<Plan__c> plans, Id primarySalesAssociate,  List<Opportunity__c> opps) {
        
        list<Sale__c> sales = new list<Sale__c>();
       
        for ( Integer i=0; i < opps.size(); i++ ) {
            Sale__c s = new Sale__c();
            s.Opportunity__c = opps[i].Id;
            s.Plan__c = plans[i].Id;
            s.Lot__c = lots[i].id;
            s.Swing__c ='Right';
            s.Customer_Contract_First_Name__c = opps[i].Customer_Name__r.FirstName;
            s.Customer_Contract_Last_Name__c = opps[i].Customer_Name__r.LastName;
            s.Customer_Home_Phone_Number__c = opps[i].Customer_Name__r.Phone;
            s.Customer_Email_Address__c = opps[i].Customer_Name__r.PersonEmail;
            s.Customer_Name_Lookup__c = opps[i].Customer_Name__c;
           // s.Approval_Status__c = 'Submitted';
            s.Approval_Type__c = 'Sale';
            s.Primary_Sales_Associate__c = primarySalesAssociate;
            sales.add(s);
        }
        insert sales;
        return sales;
    }
    // create lot
    public static list<Lot__c> createLot(String comId, Integer howMany) {
        list<Lot__c> lots = new list<Lot__c>();
        for ( Integer i = 0; i < howMany; i++ ) {
             Lot__c li = new Lot__c();
             li.Community__c = comID;
             li.Lot_Number__c = string.valueof(i);
             li.Lot_Address__c = '300 Chicago';
             li.City__c = 'Chicago';
             li.State__c = 'IL';
             li.Postal_Zip_Code__c = '60657';
             li.Status__c = 'Available';
             li.Base_House_Price__c = i;
             li.Lot_Premium__c = i; 
             lots.add(li);
        }
        insert lots;
        return lots;
    }
    // create oppotunities
    public static list<Opportunity__c> createOpportunity(String comId, List<Account> accts) {
        
        list<Opportunity__c> opps = new list<Opportunity__c>();

        Opportunity__c opp = new Opportunity__c();
        for ( Integer i=0; i < accts.size(); i++ ) {
            opp = new Opportunity__c();
            opp.Community__c = comid;
            opp.Customer_Name__c = accts[i].Id;
            opp.Opportunity_Status__c = 'Active';
            opp.Customer_Status__c = 'A-Prospect';
            opp.Realtor_Representing__c = 'No'; 
            opp.How_did_you_learn_about_Meritage_Homes__c = 'Realtor';
            opp.Web_Lead__c = true;
            opps.add(opp);
        }
        insert opps;
        return opps;
    }
    public static Id personAccountRecTypeId; 
    // create accounts
    public static list<Account> createAccount(Integer howMany)  {
        list<Account> accts = new list<Account>();
        for ( Integer i=0; i < howMany; i++ ) {
            Account a = new Account();
            a.FirstName = 'Tester';
            a.LastName = 'TestCust'+ String.valueOf(i);
            a.PersonEmail = String.valueOf(i)+'7s@mh.com';
            accts.add(a);
        }
        insert accts;
        return accts;
    }
    // create accounts monterey
    public static list<Account> createAccountMonterey(Integer howMany)  {
        list<Account> accts = new list<Account>();
        for ( Integer i=0; i < howMany; i++ ) {
            Account a = new Account();
            a.FirstName = 'Tester';
            a.LastName = 'Monterey'+ String.valueOf(i);
            a.PersonEmail = String.valueOf(i)+'7s@mh.com';
            accts.add(a);
        }
        insert accts;
        return accts;
    }
    // create plan
    public static list<Plan__c> createPlan(String comId, Integer howMany, String status) {
        list<Plan__c> complans = new list<Plan__c>();
        for ( Integer i = 0; i < howMany; i++ ) {
             Plan__c pi = new Plan__c();
             pi.Community__c = comId;
             pi.Amount_Base_Price__c = i;
             pi.Square_Feet__c = i;
             pi.Plan_Number__c = '900' + string.valueof(i);
             pi.Elevation__c = string.valueof(i);
             pi.Status__c = status;
             complans.add(pi);
        }
        insert complans;
        return complans;
    } 


    // create community 
    public static Community__c createCommunity(String dId) {

        Community_Sheet__c cs = createCommunitySheet(dID);
        
        Community__c comm = new Community__c();
        comm.Name = 'Test Comm';
        comm.Status__c = 'Active';
        comm.Division__c = dID;
        comm.Maximum_Incentive__c = 0;
        comm.Area__c = '900';
        comm.Community_Number__c = 'Tes';
        comm.Phase__c = '000';
        comm.Community_Demographic_Information__c = cs.id;
        insert comm;
        return comm;
    }

    // create monterey community 
    public static Community__c createCommunityMonterey(String dId) {

        Community_Sheet__c cs = createCommunitySheet(dID);
        
        Community__c comm = new Community__c();
        comm.Brand__c = 'Monterey Homes';
        comm.Name = 'Test Monterey Comm';
        comm.Status__c = 'Active';
        comm.Division__c = dID;
        comm.Maximum_Incentive__c = 0;
        comm.Area__c = '900';
        comm.Community_Number__c = 'TestM';
        comm.Phase__c = '000';
        comm.Community_Demographic_Information__c = cs.id;
        insert comm;
        return comm;
    }
    
    // create community sheet
    public static Community_Sheet__c createCommunitySheet(String dId){
        Community_Sheet__c cs = new Community_Sheet__c();
        cs.Division__c = dId;
        cs.Status__c = 'Active';
        cs.Marketing_Name__c = 'Tes Com S';
        insert cs;
        return cs;
    }    
    // create division
     public static Division__c createDivision() {
        Division__c div = new Division__c(Name='test div',JDE_Division_Key__c = 'Tes',status__c='Active');
        insert div;
        return div;
    }

    // create division monterey
     public static Division__c createDivisionMonterey() {
        Division__c div = new Division__c(Name='test div 1',JDE_Division_Key__c = 'Tee',status__c='Active');
        insert div;
        return div;
    }
    
    public static Id profileId;
    // create buyer users
	public static List<User> createUsers(Integer howMany,String profileName){
		 String type; 
		 if(profileId == null){
		    profileId = CC_Constants.BuyersProfileId;
		 	type = 'com';
		 } 

		 list<User> listOfUsers = new list<User>();
         
         for (Integer i = 0; i < howMany; i++){
	         User u = new User(alias = 'u' + type +i , email='testtest@test.com',
	            emailencodingkey='UTF-8', lastname='Test' + type +i, languagelocalekey='en_US',
	            localesidkey='en_US', profileid = profileId, 
	            timezonesidkey='America/Los_Angeles', username='test@testtest.com.' + type + i);

	         listOfUsers.add(u);
	     }
	     insert listOfUsers;
	 return listOfUsers;
    }
    
    public static List<User> createDesignerUsers(Integer howMany, String profileName) {
    	
    	Profile p = [SELECT Id, Name FROM Profile WHERE Name = :profileName LIMIT 1];
    	
    	list<User> listOfUsers = new list<User>();
         
        for (Integer i = 0; i < howMany; i++){
	         User u = new User(alias = 'u'  +i , email='testtest@test.com',
	            emailencodingkey='UTF-8', lastname='Test' +i, languagelocalekey='en_US',
	            localesidkey='en_US', profileid = p.Id, dsfs__DSProSFUsername__c = 'testing',
	            timezonesidkey='America/Los_Angeles', username='test@testtest.com.' + i);     

	         listOfUsers.add(u);
	    }
	    insert listOfUsers;
	 	return listOfUsers;
    }
}
 
public with sharing class Utils {
    
    private static map<Schema.SObjectType,map<String,ID>> rtypesCache;

    static { rtypesCache = new map<Schema.SObjectType,map<String,ID>>(); }

    public static map<String, ID> getRecordTypes( Schema.SObjectType token) 
    {
        map<String, ID> mapRecTypes = new map<String, ID>();
        mapRecTypes = getRecordTypes(token, true);
        return mapRecTypes;
    }
    public static map<String, ID> getRecordTypes( Schema.SObjectType token, Boolean dname) {
        // Do we already have a result? 
        map<String, ID> mapRecordTypes = rtypesCache.get(token);
        if (mapRecordTypes != null) 
           return mapRecordTypes;
        // Not Cached so build it out   
        mapRecordTypes = new map<String, ID>();
        Schema.DescribeSObjectResult obj = token.getDescribe();
        String soql = 
        'SELECT Id, Name, DeveloperName '
        + 'FROM RecordType '
        + 'WHERE SObjectType = \'' + String.escapeSingleQuotes(obj.getName()) + '\' '
        + 'AND IsActive = TRUE';
        list<SObject> results;
        try {
            results = Database.query(soql);
        } catch (Exception ex) {
            results = new list<SObject>();
        }
        map<ID,Schema.RecordTypeInfo> recordTypeInfos = obj.getRecordTypeInfosByID();
        for (SObject rt : results) {  
            if (recordTypeInfos.get(rt.Id).isAvailable()) 
            {
                if (dname)
                    mapRecordTypes.put(String.valueOf(rt.get('DeveloperName')),rt.Id);
                else
                    mapRecordTypes.put(String.valueOf(rt.get('Name')),rt.Id);
            }
        }
        rtypesCache.put(token,mapRecordTypes);
        return mapRecordTypes;
    }
    
    public class CloneChildrenResult {
        public sObject[] oldObjs;
        public sObject[] newObjs;
    }
    
    // returns two lists: the list of original values and list of clones
    public static CloneChildrenResult cloneChildrenAndAdopt(String objectName, String parentField, String parentId, String newParentId) {
        CloneChildrenResult result = cloneChildren(objectName, parentField, parentId);
        for ( sObject obj: result.newObjs ) {
            obj.put(parentField, newParentId);
        }   
        insert result.newObjs;
        return result;
    }
    
    // returns two lists: the list of original values and list of clones
    public static CloneChildrenResult cloneChildren(String objectName, String parentField, String parentId) {
        String soql = getCreatableFieldsSOQL(objectName, parentField +' =  \''+ parentId +'\'');
        sObject[] oldObjs = Database.query(soql);
        sObject[] newObjs = new list<sObject>();
        for ( sObject obj: oldObjs ) {
            sObject newObj = obj.clone(false);
            newObjs.add(newObj);
        }
        CloneChildrenResult retval = new CloneChildrenResult();
        retval.oldObjs = oldObjs;
        retval.newObjs = newObjs;
        return retval;
    }
    
    // Returns a dynamic SOQL statement for the whole object, includes only creatable fields since we will be inserting a cloned result of this query
    public static string getCreatableFieldsSOQL(String objectName, String whereClause) {
        String selects = '';
        if (whereClause == null || whereClause == '') { return null; }
        // Get a map of field name and field token
        map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();
        list<string> selectFields = new list<string>();
        if (fMap != null){
            for ( Schema.SObjectField ft : fMap.values() ){ // loop through all field tokens (ft)
                Schema.DescribeFieldResult fd = ft.getDescribe();
                if ( fd.isCreateable() && fd.getName() != 'Location__c'){ // field is creatable
                    selectFields.add(fd.getName());
                }
            }
        }
        if ( !selectFields.isEmpty() ) {
        	selects = String.join(selectFields,',');
            //for ( string s:selectFields ) {
            //    selects += s + ',';
            //}
            //if ( selects.endsWith(',') ){selects = selects.substring(0,selects.lastIndexOf(','));}
        }
        String retval = 'SELECT ' + selects + ' FROM ' + objectName + ' WHERE ' + whereClause;
        //System.Debug(LoggingLevel.DEBUG, '>>> getCreatableFieldsSOQL SOQL: ' + retval);
        return retval;
    }
    // Emil: overload
    public static string getAllFieldsSOQL(String objectName, String whereClause) {
        return getAllFieldsSOQL(objectName, whereClause, null);
    }
    
    // Emil: overload
    public static string getAllFieldsSOQL(String objectName, String whereClause, String orderBy) {
        return getAllFieldsSOQL(objectName, whereClause, orderBy, null);
    }
    // Mohan
    // Emil: added orderBy and ExtraFields
    public static string getAllFieldsSOQL(String objectName, String whereClause, String orderBy, String extraFields) {
        String selects = '';
        if (whereClause == null || whereClause == '') { return null; }
        // Get a map of field name and field token
        map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();
        list<string> selectFields = new list<string>();
        if ( fMap != null ){
            for ( Schema.SObjectField ft : fMap.values() ){ // loop through all field tokens (ft)
                Schema.DescribeFieldResult fd = ft.getDescribe(); // describe each field (fd)
                if ( fd.getName() != 'Location__c' )
                    selectFields.add(fd.getName());
            }
        }
        if ( !selectFields.isEmpty() ) {
        	selects = String.join(selectFields,',');
            //for ( string s:selectFields ) {
            //    selects += s + ',';
            //}
            //if ( selects.endsWith(',') ){selects = selects.substring(0,selects.lastIndexOf(','));}
            if ( extraFields != null && extraFields != '' )
                selects += ', ' + extraFields;
        }
        String retval = 'SELECT ' + selects + ' FROM ' + objectName + ' WHERE ' + whereClause;
        if ( orderBy != null && orderBy != '' ) retval += ' ORDER BY ' + orderBy;
        //System.Debug(LoggingLevel.DEBUG, '>>> getAllFieldsSOQLv2 SOQL: ' + retval);
        return retval;
    }
 
    public static void deleteChildren(String objectName, String parentField, String parentId) {
        objectName = String.escapeSingleQuotes(objectName);
        parentField = String.escapeSingleQuotes(parentField);
        SObject[] delThese = Database.query('SELECT Id FROM ' + objectName + ' WHERE ' + parentField + ' = :parentId');
        Database.delete(delThese);
    }
    // P. Sutherland Relocate this code for use everywhere
    public static list<selectOption> getPickValues(Sobject object_name, String field_name, String first_val) {
        list<selectOption> options = new list<selectOption>(); //new list for holding all of the picklist options
        if ( first_val != null) {//if there is a first value being provided
            options.add(new selectOption(first_val, first_val)); //add the first option
        }
        Schema.sObjectType sobject_type = object_name.getSObjectType(); //grab the sobject that was passed
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); //describe the sobject
        map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject
        list<Schema.PicklistEntry> pick_list_values = field_map.get(field_name).getDescribe().getPickListValues(); //grab the list of picklist values for the passed field on the sobject
        for ( Schema.PicklistEntry a : pick_list_values ) { //for all values in the picklist list
            options.add(new selectOption(a.getLabel(), a.getValue())); //add the value and label to our final list
        }
        return options; //return the List
    }
    // Public Function to Strip Characters out of text
    public static String stripSpecialCharsHTML(String txt){
        String retstr = '';
        if ( txt != null ) {
           //first replace all <BR> tag
           system.debug('Text A: '+txt);
           txt = txt.replaceAll('(?i)<br>','\n').replaceAll('(?i)<br/>','\n').replaceAll('(?i)<br />','\n').replaceAll('\'','&#39');
           //regular expression to match all HTML/XML tags ( keeps injected JS and CSS out )
           string HTML_TAG_PATTERN = '<.*?>';
           pattern strPattern = pattern.compile(HTML_TAG_PATTERN);
           matcher strMatcher = strPattern.matcher(txt);
           txt = strMatcher.replaceAll('');
           txt = txt.replaceAll('<','(').replaceAll('>',')').replaceAll('”','"').replaceAll('–','-');
           //remove the White Space
           //string WHITESPACE_PATTERN = '\\s';
           //pattern strPattern2 = pattern.compile(WHITESPACE_PATTERN);
           //matcher strMatcher2 = strPattern2.matcher(txt);
           //txt = strMatcher2.replaceAll(' ');
           system.debug('Text B: '+txt);
           txt = txt.replaceAll('\n','<br>').replaceAll('\r\n','<br>').replaceAll('\r','<br>').replaceAll('\t','<br>');
           system.debug('Text C: '+txt);
           //txt = txt.replaceAll('\n',' ');           
       }
       else
           return '';
       retstr = txt;
       return retstr;
    }
    // Public Function to Strip Characters out of text
    public static String replaceIllegalCharsHTML(String txt){
        String retstr = '';
        if ( txt != null ) {
           //first replace all ' tags and the <br>
           txt = txt.replaceAll('&#39','\'').replaceAll('<br>','\n');
       }
       else
           return '';
       retstr = txt;
       return retstr;
    }
    // Phone Number Validation
    public static Boolean validateUSPhone(String phoneNumber) {  
        if( phoneNumber != null ) {
            phoneNumber = phoneNumber.replaceAll('[^\\d]', ''); 
            if ( phoneNumber.length() == 10 ) 
                 return true;       //return true - if success  
            return false;       //else return false  
        }  
        else return false ;      //if Phone field is empty return false  
    }
    // returns a map of all the Object prefixes and Names
    public static map<String,String> getgdObjectTypeMap() {
        map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe(); 
        map<String,String> keyPrefixMap = new map<String,String>{};
        for ( String sObj : gd.keySet()){
             Schema.DescribeSObjectResult r = gd.get(sObj).getDescribe();
             String tempName = r.getName();
             String tempPrefix = r.getKeyPrefix();
             keyPrefixMap.put(tempPrefix,tempName);
        }
        return keyPrefixMap;    
    }
    // scrub an address to remove leading verbage
    public static String scrubAddress(String address) {
        String addstr = '';
        list<String> ls = address.splitByCharacterTypeCamelCase();
        for ( integer i=0; i < ls.size(); i++ ) {
            if ( ls[i].substring(1) > '0' && ls[i].substring(1) <= '9' ) {
                while ( i < ls.size() ) {
                    addstr += ls[i];
                    i++;
                }
            }    
        }
        return addstr;
    }
    // get Callout Keys Custom Setting record
    public static CalloutKeys__c getCalloutKeys(String key) {
        system.debug('@@@ Key: '+ key);
        CalloutKeys__c c = CalloutKeys__c.getInstance(key);
        system.debug('@@@ Call Out Keys Utils: '+c);
        return(c);
    }   
    
    // determine if sandbox or production
    public static Boolean runningInASandbox() {
      return [select id,issandbox from organization].issandbox;
  }    

    public static Boolean duplicateMgmtActive(String type) {
        String qstr = Utils.getAllFieldsSOQL('DuplicateRule','isactive = true and sobjecttype = :type');
        list <duplicateRule> drlst = database.query(qstr);
        if (drlst.size() == 0)
            return false;
        else
            return true;
    } // end of duplicateMgmtActive    
}

 
I wrote a dedupe trigger that is supposed to check to see if the lead already exists in the system by email and contact. If the contact already exist then I want it to add the original lead to a lookup field. If it is not a duplicate then it would mark is_primary__c. I don't see it updating when I go and create a new lead manually. Is there something in my code that is causing it to not work? 
 
trigger findLeadDupes on Lead (before insert) {
  for (Lead myLead : Trigger.new) {
    if (myLead.Email != null) {
      List<Lead> dupes = [SELECT Id FROM Lead
                               WHERE Email = :myLead.Email AND Company = :myLead.Company];
      if (dupes.size() > 0) {
        myLead.Primary_Lead__c = dupes[0].Id;
      } else {
        myLead.Primary_Lead__c = null;
        myLead.Is_Primary__c = True;
      }                             
    }
  }
}

 
I am not sure what the best way to do this is but I am trying to update a field to find out when a person account has entered a campaign for the first time. We are using campaigns that are coming over from Zapier. If the Person Account is created then we wanted the campaign name to be stamped on Campaign Origin. I was thinking about doing this via process builder but I don't seem to be able to. Any thoughts as to what would work the best? 
I am trying to run a test for my code that is working for UI testing. I am getting an error of "System.DmlException: Insert failed. First exception on row 0 with id 5000m000005R0B9AAK; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]" for a stack trace of "Class.attachController.submit: line 27, column 1
Class.attachController_Test.test1: line 30, column 1"

When I looked at this I am not seeing anything that would cause for it to error out for the id. Am I possibly missing something? 

VF: 
<apex:page Standardcontroller="Case" extensions="attachController" showheader="false" >
    <html lang="en">
        <head>
            <link rel="icon" type="image/png" href="{!$Resource.siteLogo}" />
            <link href="https://use.fontawesome.com/releases/v5.4.2/css/all.css" rel="stylesheet" media="screen"/>
            
            <!-- Bootstrap -->
            <link href="https://cdn.rawgit.com/creativetimofficial/now-ui-kit/2e8e665f/assets/css/bootstrap.min.css" rel="stylesheet" media="screen"/>
            <link href="https://cdn.rawgit.com/creativetimofficial/now-ui-kit/2e8e665f/assets/css/now-ui-kit.min.css?v1.2.0" media="screen"/>
            <title>Submit a Case</title>
            <style>
                
                p, li, .description{
                font-weight: 400;
                line-height: 1.8rem;
                }
                
                .paddingTop{padding-top: 2rem;}
                }
                
                .background-black{background: #2196f3;}
                
                .background-black:hover, 
                .background-black:focus{background: #2386d3 !important;}      
                
                section .section-inner h2{color: #fff;}
                
                .round {
                border-radius: 100px;
                margin: 0;
                color: #9a9a9a
                }
                
                .longBox{height: 100px;}
                
                
                @media screen and (max-width: 500px){
                .brand .h1-seo{
                font-size: 2.2rem;
                }
                
                }
                
            </style>
        </head>
        <body>
            <div class="container">
                <apex:form styleclass="form-signin"><br/><br/><br/>
                    <br/><h2 class="form-signin-heading">Create a Ticket</h2><br/><br/>
                    <h5 class="form-signin-heading">Email</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.Email__c}" required="true"/>
                    <br/><h5 class="form-signin-heading">Subject</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.Subject}" required="true"/>
                    <br/><h5 class="form-signin-heading">What are you experiencing?</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.What_are_you_experiencing__c}" required="true"/>
                    <br/><h5 class="form-signin-heading">Where is the location of your issue?</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.Location_of_issue__c}" required="true"/>
                    <br/><h5 class="form-signin-heading">Campaign or Source?</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.Source_Type__c}" required="false"/><br/>
                    <br/><h5 class="form-signin-heading">Campaign/Source ID</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.Campaign_Source_ID__c}" required="false"/><br/>
                    <br/><h5 class="form-signin-heading">Description</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control longBox" value="{!case.Description}" required="true"/><br/>
                    <apex:commandButton action="{!submit}" value="Submit" styleClass="btn btn-primary btn-block btn-lg background-black btn-round round"/><br/>
                    <!-- <button class="btn btn-primary btn-block btn-lg background-black btn-round round " action="{!submit}">Submit</button><br/><br/><br/> -->
                    <apex:pageBlock >
                        <apex:pageBlockSection columns="1" >
                            <div id="upload" class="upload">  
                                <h6>
                                    If you have more than 1 file to upload please zip file to include all files. 
                                </h6>
                                <apex:inputFile title="Choose File" value="{!filebody}" filename="{!filename}" styleClass="btn btn-primary btn-block btn-lg background-black btn-round round"/>                            
                            </div>
                        </apex:pageBlockSection>
                    </apex:pageBlock>
                </apex:form>
            </div>
            <!-- /container -->
            <!-- Bootstrap core JavaScript
================================================== -->
            <!-- Placed at the end of the document so the pages load faster -->
        </body>
    </html>
</apex:page>
Apex: 
public class attachController
{
    public case objcase{get;set;}
    public Attachment myAttachment{get;set;}
    public string fileName{get;set;}
    public Blob fileBody{get;set;}
    
    public attachController(Apexpages.standardcontroller controller)
    {
        objcase = (Case)controller.getRecord();
        myAttachment = new Attachment();
    }
    public PageReference submit(){
        if (fileName != null){
            objcase.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Product Case').getRecordTypeId();
            insert objcase;
            System.debug('@@@@@fileBody'+fileBody);    
            myAttachment = new Attachment();
            Integer i=0;
            myAttachment .clear();
            myAttachment.Body = fileBody;
            myAttachment.Name = fileName ;
            myAttachment.ParentId = objcase.id;            
            insert myAttachment;
        } else {
            objcase.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Product Case').getRecordTypeId();
            insert objcase;
               
        }             
        pagereference pr = Page.thankYouForSubmittingYourProductCase;                          
        pr.setRedirect(true);
        return pr;
    }
}
Test: 
@isTest
public class attachController_Test {
    static testMethod void test1()
    {
        Case cs = new Case(
            Email__c = 'Test@test.com', 
            Subject = 'Phone',
            What_are_you_experiencing__c = 'I have a feature request', 
            Location_of_issue__c = 'Campaigns',
            Source_Type__c = 'Source', 
            Campaign_Source_ID__c = '123456',
            Description = 'test from Mr. Testerson'
        );
        insert cs;
        
        Attachment attach=new Attachment();       
        attach.Name='Unit Test Attachment';
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
        attach.body=bodyBlob;
        attach.parentId=cs.id;
        insert attach;
        
        List<Attachment> attachments=[select id, name from Attachment where parent.id=:cs.id];
        System.assertEquals(1, attachments.size());
        
        ApexPages.StandardController stdCtr = new ApexPages.StandardController(cs);
        attachController ctr = new attachController(stdCtr);
        ctr.objcase = cs;
        ctr.myAttachment = attach;
        ctr.submit();   
    }
}



 
I am trying to create a visualforce button that then inserts an opportunity and then sends an email to anyone if the running user is listed as the marketing_development_rep__c. Not sure if I am doing something wrong but it isn't creating the opportunity when I go and hit save.

VF: 
<apex:page controller="mdrHandOffOppInsert" sidebar="false" showHeader="false">
    <apex:form id="frm">
        <apex:pageBlock >
            <strong>Please provide any reference notes for this deal.</strong>
            <apex:pageBlockSection >
               <apex:inputField value="{!Opportunity.Hand_Off_Notes__c}" required="true"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
                <apex:actionFunction name="quickSaveJavascript" action="{!quicksave}" oncomplete="window.top.close();"/>
               <apex:commandButton value="Submit" onclick="quickSaveJavascript();"/>
               <!--<apex:commandButton action="{!cancel}" value="Cancel"/>-->
           </apex:pageBlockButtons>
       </apex:pageBlock>
    </apex:form>
</apex:page>

Apex:
 
public class mdrHandOffOppInsert {
    public Account acc{get; set;}
    public opportunity oppstring{get; set;}
    public mdrHandOffOppInsert(){oppstring= new opportunity();}
    public void Saveto(){
        opportunity opp= new opportunity();
        opp.Accountid= oppstring.Accountid;
		opp.StageName= 'F- Awareness';
        opp.CloseDate=date.today()+90;
        opp.Type='New Business';
        opp.Name= oppstring.name + ' SaaS Deal';
        opp.Marketing_Opp__c = true;
        opp.RecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('SaaS - Marketer').getRecordTypeId();		             
        insert opp;
		}
    
}

public static sendEmailToAccDir {
    
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
                List <User> sadList= SELECT Account_Director__r.email
               	  				 		FROM team__c
               	  						WHERE Marketing_Development_Rep__r.id = UserInfo.getUserId()]; 
                mail.setTargetObjectId(Con[0].id); 
                mail.setSenderDisplayName('Salesforce Support'); 
                mail.setUseSignature(false); 
                mail.setBccSender(false); 
                mail.setSaveAsActivity(false); 
                EmailTemplate et=[Select id from EmailTemplate where Name=:'MDR_Sales_Handoff_Initial_Alert']; 
                mail.setTemplateId(et.id); 
                Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

​​​​​​​
Trigger:
trigger AccountTrigger on Account (before update)
  {
  
  if(checkRecursive.runOnce())
    {
    list<Account> account_Updatelist= new list<Account>();
    for(Account acc : Trigger.new)
      {
       
         if(acc.Total_Opportunities_Won__c>=1 && acc.Active_Opportunities__c == 0 && Trigger.oldMap.get(acc.id)!=null && Trigger.oldMap.get(acc.id).Active_Opportunities__c>=1)
            acc.Account_Clearing_Date__c= system.today();
            
         else if(acc.Total_Opportunities_Won__c>=1 && acc.Active_Opportunities__c >= 1)
             acc.Customer_Type__c = 'Current Client';
             
          else if(acc.Total_Opportunities_Won__c==0 && acc.Active_Opportunities__c==0)
             acc.Customer_Type__c = 'Prospect';
             
          
            
      }
      
          
      }
          
   }

Test Class: 
@isTest
private class testAccountTrigger {

static testMethod void customerTypeTest(){
    
    /*Create Account*/
    Account acc1=new Account();
    acc1.Name='Test Account1';
    acc1.Account_Status__c='Active';
    acc1.OMC_Alliance__c=true;
    insert acc1;
    
    /*Create Opportunity*/
    Opportunity opp1=new Opportunity();
    opp1.Name='Test Opportunity1';
    opp1.AccountId=acc1.Id;
    opp1.closeDate=date.today();
    opp1.stageName='Proposal';
    opp1.Type='Net New Account - First Deal';
    opp1.Project_Type_2__c='Data & Analytics';    
    opp1.Call_Center_Country__c='U.S.';
    opp1.Televerde_Ownership__c='Televerde U.S.';
    insert opp1;
    
    /*Create CDP*/
    Campaign_Design_Profile__c cdp1= new Campaign_Design_Profile__c();
    cdp1.name='Test CDP1';
    cdp1.Campaign_Type__c='Lead Generation';
    cdp1.Related_Opportunity__c=opp1.Id;
    cdp1.CDP_Status__c='new';
    cdp1.Account_Name_Ref__c=acc1.Id;
    cdp1.Volume__c=1324;
    cdp1.Estimate_Type__c='FTEs';
    cdp1.of_Hours__c=7500;
    cdp1.Requested_Start_Date__c=date.today();
    cdp1.Requested_Completion_Date__c=date.today(); 
    insert cdp1;
        
  opp1.StageName='closed won';
    update opp1;
    
    cdp1.CDP_Status__c='Completed';
    update cdp1;}
    
static testMethod void customerTypeTest1(){
    
    /*Create Account*/
    Account acc2=new Account();
    acc2.Name='Test Account2';
    acc2.Account_Status__c='Active';
    acc2.OMC_Alliance__c=true;
    insert acc2;
    
    /*Create Opportunity*/
    Opportunity opp2=new Opportunity();
    opp2.Name='Test Opportunity2';
    opp2.AccountId=acc2.Id;
    opp2.closeDate=date.today();
    opp2.stageName='Proposal';
    opp2.Type='Net New Account - First Deal';
    opp2.Project_Type_2__c='Data & Analytics';    
    opp2.Call_Center_Country__c='U.S.';
    opp2.Televerde_Ownership__c='Televerde U.S.';
    insert opp2;
    
    /*Create CDP*/
    Campaign_Design_Profile__c cdp2= new Campaign_Design_Profile__c();
    cdp2.name='Test CDP2';
    cdp2.Campaign_Type__c='Lead Generation';
    cdp2.Related_Opportunity__c=opp2.Id;
    cdp2.CDP_Status__c='new';
    cdp2.Account_Name_Ref__c=acc2.Id;
    cdp2.Volume__c=1324;
    cdp2.Estimate_Type__c='FTEs';
    cdp2.of_Hours__c=7500;
    cdp2.Requested_Start_Date__c=date.today();
    cdp2.Requested_Completion_Date__c=date.today(); 
    insert cdp2;
    
    }
}



The items not being covered are: 
else if(acc.Total_Opportunities_Won__c==0 && acc.Active_Opportunities__c==0) acc.Customer_Type__c = 'Prospect';

as well as 
acc.Account_Clearing_Date__c= system.today();

Am I supposed to have a secondary static test in this? When I tried what I thought I needed to do it gave me the same code coverage. 
I am trying to have a site that has a visualforce page allowing someone to upload an attachment with the new record that they are creating. I have the attachment passing at 95% code coverage but it doesn't seem to actually be uploading the attachment with the new record.

VF: 
<apex:pageBlockButtons >
    <apex:commandButton action="{!save}" value="Submit"/>
       <apex:commandButton action="{!cancel}" value="Cancel"/>
    </apex:pageBlockButtons>
    <apex:pageBlockSection title="Upload the Attachment" collapsible="false" dir="LTR" columns="1">
        <div id="upload" class="upload">                                   
            <apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>                            
        </div>
</apex:pageBlockSection>

Apex Class: 
public class dataSheetAttachment
{
    public Data_Feasibility_Request__c objdfr{get;set;}
    public Attachment myAttachment{get;set;}
    public string fileName{get;set;}
    public Blob fileBody{get;set;}

    public dataSheetAttachment(Apexpages.standardcontroller controller)
    {
        objdfr = (Data_Feasibility_Request__c)controller.getRecord();
        myAttachment = new Attachment();
    }
    public pagereference save()
    {
        if(myAttachment.Name == null)
        {
            insert objdfr;
        }
        if(myAttachment.Name != null)
        {
            insert objdfr;
            System.debug('@@@@@fileBody'+fileBody);    
            myAttachment = new Attachment();
            Integer i=0;
            myAttachment .clear();
            myAttachment.Body = fileBody;
            myAttachment.Name = fileName ;
            myAttachment.ParentId = objdfr.id;            
            insert myAttachment;   
        }             
       pagereference pr = Page.Thank_You;                          
       pr.setRedirect(true);
       return pr;
    }
}
Test Class: 
 
@isTest
private class Test_dataSheetAttachment {

public static testMethod void validatedataSheetAttachment() {        
    Data_Feasibility_Request__c myDFR = new Data_Feasibility_Request__c();
    dataSheetAttachment pageController = new dataSheetAttachment(new ApexPages.StandardController(myDFR));
  
    pageController.myAttachment.Name = 'foo';
    pageController.fileBody=Blob.valueOf('Body Test');
    pageController.fileName = 'Test';
    pageController.save();
  
    }

}



Wondering if someone might be able to help me figure out what I might be doing incorrect? 
Hello. Wondering if someone might be able to help me figure this out.
I am trying to update our picklist Account.Customer_Type__c to either “Former Client”, “Current Client” or “Prospect”. This is updated through opportunities (which we have a related list set up as we can have many opps tied to one account). These opportunities then have Campaign_Design_Profile__c associated with them. We are wanting to have the account update as long as all the CDP’s are marked to “Complete” and all opps stage are “Closed Won”.
 
Former Client on Account –
AND(
ISPICKVAL(Opportunity.StageName = “Closed Won”),
ISPICKVAL(Campaign_Design_Profile__c.CDP_Status__c, “Completed”),
All opps are classified as Former 120+ days.
 
**If any opps are closed won -120 days then it would move back to Current Client**
Issue that I am running into is a way to pull all of the data from the related list to one opportunity. For example, I feel that if I can pull all of the data into the Opportunity from the CDP’s then we can update the boolean we have on the opportunity. Then with that same logic we can do that with the opportunities for the account. As in if the CDP’s all show as complete then we would have the opportunity Boolean show as true for former opportunity.
I have a site that is being used internally for our team to submit cases to our admin team. I am trying to write a test class for the apex part of it but my code coverage seems to still be at 0%. Was wondering if someone might be able to help me with this as this is my first test class. 

VF: 
<apex:page standardController="Case" extensions="case_attachment">
<apex:form id="frm">
    <apex:pageBlock title="New Salesforce Case">
        <apex:pageBlockSection columns="1"  title="Salesforce Case -- Red lines represent required fields." collapsible="false">
        </apex:pageBlockSection>
        <strong>Please click the lookup icon (small button to right of field) to search name selection from Salesforce lookup dialog.</strong>
        <apex:pageBlockSection columns="1">
           <apex:inputField value="{!Case.Requestor_Name__c}" required="true"/>
           <br></br>
           </apex:pageBlockSection>
        <strong>Select Problem and High Priority ONLY if the issue is preventing you from continuing work in Salesforce.</strong>
        <apex:pageBlockSection columns="1">
           <apex:inputField value="{!Case.Type}" required="true"/>
           <apex:inputField value="{!Case.Priority}" required="true"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection columns="1" title="Case Details" collapsible="false">
           <apex:inputField value="{!Case.Department__c}" required="true"/>
           <apex:inputField value="{!Case.Salesforce_Object__c}" required="true"/>
           <apex:inputField value="{!Case.Description}" required="true" style="width:50%; height: 60px" />
        </apex:pageBlockSection>
        <apex:pageBlockButtons >
           <apex:commandButton action="{!save}" value="Submit"/>
           <apex:commandButton action="{!cancel}" value="Cancel"/>
       </apex:pageBlockButtons>
    <apex:pageBlockSection title="Upload the Attachment" collapsible="false" dir="LTR" columns="1">
    <div id="upload" class="upload">                                   
        <apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>                            
    </div>
    </apex:pageBlockSection>
   </apex:pageBlock>
</apex:form>
</apex:page>

The controller that I am using for the attachment is being used to save the record, add the attachment and then the page is redirected to a thank you page. 

Apex: 
public class case_attachment
{
public case objcase{get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
 
    public case_attachment(Apexpages.standardcontroller controller)
    {
        objcase = (Case)controller.getRecord();
        myAttachment = new Attachment();
    }
    public pagereference save()
    {
      if(myAttachment.Name == null)
        {
        insert objcase;
        }
      if(myAttachment.Name != null)
      {
        insert objcase;
        System.debug('@@@@@fileBody'+fileBody);    
        myAttachment = new Attachment();
              Integer i=0;
              myAttachment .clear();
              myAttachment.Body = fileBody;
              myAttachment.Name = fileName ;
              myAttachment.ParentId = objcase.id;            
              insert myAttachment;   
        }             
        pagereference pr = Page.Thank_You;                          
        pr.setRedirect(true);
        return pr;
    }
}

I was under the impression that I had to make sure that the test class ran through the required fields of the external site but it doesn't seem to show any test coverage. 

Test Class: 
@isTest
private class Test_case_attachment {
	
	@isTest static void createCase() {
		Case c = new Case();
		c.Requestor_Name__c = '0035C000001njRp';
		c.Type = 'Problem';
		c.Priority = '1';
		c.Department__c = 'Marketing';
		c.Salesforce_Object__c = 'Accounts';
		c.Description = 'this is a test submission';

		insert c;
	}
	
}

Does anyone know what I am doing wrong? 

 
I am trying to write a trigger that updates Account, Contact and Opportunity with the lead after that said lead is converted. Does anyone have the most recommended practice for this? 
I am trying to create a custom button that works for multiple different objects to all come back to my Data_Feasibility_Report__c custom object. I was trying to create the button to pull from the Lead standard object but I keep gettting an error that I am not sure how to fix. Any help would be appreciated. Here is the code that I am trying to write. I am trying to pull the Name from the Lead and the record type as well as a couple custom fields. When I go test the button I get "Invalid or unexpected token".
 
{!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/33.0/apex.js")}
 
var DFR = new sforce.SObject("Data_Feasibility_Request__c"); 
DFR.Related_To__c = 'Lead';
DFR.Related_Lead__c = '{!Lead.Name}';
DFR.RecordID=0125C00000005jd;

var result = sforce.connection.create([DFR]);
 
if(result[0].getBoolean("success")){
   alert('New record updated successfully');
}
else{
  alert('Error : '+result);
}

I tried this another way but I am getting an error the second way I tried as well. Any help on either of these would be appreciated. 
 
{!REQUIRESCRIPT('/soap/ajax/37.0/connection.js')} 

getDate = function(dateObj){ 
var day = dateObj.getDay() < 9 ? '0'+dateObj.getDay() : dateObj.getDay(); 
var month = dateObj.getMonth() < 9 ? '0'+dateObj.getMonth() : dateObj.getMonth(); 

return dateObj.getFullYear()+'-'+month+'-'+day; 
} 

var oppty = new sforce.SObject('Data_Feasibility_Report__c'); 

oppty.Related_Lead__c = '{!Lead.Name}; 
oppty.Related_To__c = 'Lead'; 
RecordType=0125C00000005jd; 

result = sforce.connection.create([oppty]); 

if(result[0].success == 'true'){ 
alert('An New Opportunity with Name - ' + oppty.Name + ' was Created Successfully.'); 
}

 
I am trying to create a case external page that allows for me to use the standard controller with an extension so that they are able to add an attachment if they are wanting to. I had it where it wouldn't upload the attachment and now it will only upload the attachment and leaves all of the data alone. Anyone know of a way for it to do both?

VF Page:
<apex:page standardController="Case" extensions="caseattachment">
    <apex:form id="frm">
        <apex:pageBlock title="New Salesforce Case">
            <apex:pageBlockSection columns="1"  title="Salesforce Case -- Red lines represent required fields." collapsible="false">
            </apex:pageBlockSection>
            <strong>Please click the lookup icon (small button to right of field) to search name selection from Salesforce lookup dialog.</strong>
            <apex:pageBlockSection columns="1">
               <apex:inputField value="{!Case.Requestor_Name__c}" required="true"/>
               <br></br>
               </apex:pageBlockSection>
            <strong>Select Problem and High Priority ONLY if the issue is preventing you from continuing work in Salesforce.</strong>
            <apex:pageBlockSection columns="1">
               <apex:inputField value="{!Case.Type}" required="true"/>
               <apex:inputField value="{!Case.Priority}" required="true"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection columns="1" title="Case Details" collapsible="false">
               <apex:inputField value="{!Case.Department__c}" required="true"/>
               <apex:inputField value="{!Case.Salesforce_Object__c}" required="true"/>
               <apex:inputField value="{!Case.Description}" required="true" style="width:50%; height: 60px" />
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
               <apex:commandButton action="{!save}" value="Submit"/>
               <apex:commandButton action="{!cancel}" value="Cancel"/>
           </apex:pageBlockButtons>
        <apex:pageBlockSection title="Upload the Attachment" collapsible="false" dir="LTR" columns="1">
        <div id="upload" class="upload">                                   
            <apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>                            
        </div>
        </apex:pageBlockSection>
       </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class: 
public class caseattachment
{
public case objcase{get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;} 
public Blob fileBody{get;set;}

    public caseattachment(Apexpages.standardcontroller controller)
    {
        objcase = new case();
        myAttachment =new Attachment();
    }
    public pagereference save()
    {
        insert objcase;
        System.debug('@@@@@fileBody'+fileBody);     
        myAttachment  = new Attachment();
              Integer i=0;
              myAttachment .clear();
              myAttachment.Body = fileBody; 
              myAttachment.Name = 'Logo_'+objcase.id+'.jpeg' ; 
              myAttachment.ParentId = objcase.id;             
              insert myAttachment;                 
        pagereference pr = new pagereference('/'+objcase.id);                           
        return pr;
    }
}

Anyone know what I am doing wrong? 
 
I am trying to solve an issue that I am not sure about. I am wanting to have multi picklist on the page layout. If they select any of these picklist then whatever they select then checks the checkbox that is not on the page layout. Is there any way to do this or something else that someone recommends? 
I have a custom object that I am trying to enforce that if checkbox = true they must attach a file. Any thoughts on how this would be accomplished? Or more if this is able to be accomplished? 
Hello all, 

I am trying to create a validation which will stop users from either skipping forward (changing value from A to C) or going backward (changing value from C to B). For some reason I keep getting an error on this. Any advice on these? 
I wrote a dedupe trigger that is supposed to check to see if the lead already exists in the system by email and contact. If the contact already exist then I want it to add the original lead to a lookup field. If it is not a duplicate then it would mark is_primary__c. I don't see it updating when I go and create a new lead manually. Is there something in my code that is causing it to not work? 
 
trigger findLeadDupes on Lead (before insert) {
  for (Lead myLead : Trigger.new) {
    if (myLead.Email != null) {
      List<Lead> dupes = [SELECT Id FROM Lead
                               WHERE Email = :myLead.Email AND Company = :myLead.Company];
      if (dupes.size() > 0) {
        myLead.Primary_Lead__c = dupes[0].Id;
      } else {
        myLead.Primary_Lead__c = null;
        myLead.Is_Primary__c = True;
      }                             
    }
  }
}

 
I am trying to run a test for my code that is working for UI testing. I am getting an error of "System.DmlException: Insert failed. First exception on row 0 with id 5000m000005R0B9AAK; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]" for a stack trace of "Class.attachController.submit: line 27, column 1
Class.attachController_Test.test1: line 30, column 1"

When I looked at this I am not seeing anything that would cause for it to error out for the id. Am I possibly missing something? 

VF: 
<apex:page Standardcontroller="Case" extensions="attachController" showheader="false" >
    <html lang="en">
        <head>
            <link rel="icon" type="image/png" href="{!$Resource.siteLogo}" />
            <link href="https://use.fontawesome.com/releases/v5.4.2/css/all.css" rel="stylesheet" media="screen"/>
            
            <!-- Bootstrap -->
            <link href="https://cdn.rawgit.com/creativetimofficial/now-ui-kit/2e8e665f/assets/css/bootstrap.min.css" rel="stylesheet" media="screen"/>
            <link href="https://cdn.rawgit.com/creativetimofficial/now-ui-kit/2e8e665f/assets/css/now-ui-kit.min.css?v1.2.0" media="screen"/>
            <title>Submit a Case</title>
            <style>
                
                p, li, .description{
                font-weight: 400;
                line-height: 1.8rem;
                }
                
                .paddingTop{padding-top: 2rem;}
                }
                
                .background-black{background: #2196f3;}
                
                .background-black:hover, 
                .background-black:focus{background: #2386d3 !important;}      
                
                section .section-inner h2{color: #fff;}
                
                .round {
                border-radius: 100px;
                margin: 0;
                color: #9a9a9a
                }
                
                .longBox{height: 100px;}
                
                
                @media screen and (max-width: 500px){
                .brand .h1-seo{
                font-size: 2.2rem;
                }
                
                }
                
            </style>
        </head>
        <body>
            <div class="container">
                <apex:form styleclass="form-signin"><br/><br/><br/>
                    <br/><h2 class="form-signin-heading">Create a Ticket</h2><br/><br/>
                    <h5 class="form-signin-heading">Email</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.Email__c}" required="true"/>
                    <br/><h5 class="form-signin-heading">Subject</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.Subject}" required="true"/>
                    <br/><h5 class="form-signin-heading">What are you experiencing?</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.What_are_you_experiencing__c}" required="true"/>
                    <br/><h5 class="form-signin-heading">Where is the location of your issue?</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.Location_of_issue__c}" required="true"/>
                    <br/><h5 class="form-signin-heading">Campaign or Source?</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.Source_Type__c}" required="false"/><br/>
                    <br/><h5 class="form-signin-heading">Campaign/Source ID</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control" value="{!case.Campaign_Source_ID__c}" required="false"/><br/>
                    <br/><h5 class="form-signin-heading">Description</h5><br/>
                    <apex:inputfield styleClass="inputGroupSelect01 custom-select form-control longBox" value="{!case.Description}" required="true"/><br/>
                    <apex:commandButton action="{!submit}" value="Submit" styleClass="btn btn-primary btn-block btn-lg background-black btn-round round"/><br/>
                    <!-- <button class="btn btn-primary btn-block btn-lg background-black btn-round round " action="{!submit}">Submit</button><br/><br/><br/> -->
                    <apex:pageBlock >
                        <apex:pageBlockSection columns="1" >
                            <div id="upload" class="upload">  
                                <h6>
                                    If you have more than 1 file to upload please zip file to include all files. 
                                </h6>
                                <apex:inputFile title="Choose File" value="{!filebody}" filename="{!filename}" styleClass="btn btn-primary btn-block btn-lg background-black btn-round round"/>                            
                            </div>
                        </apex:pageBlockSection>
                    </apex:pageBlock>
                </apex:form>
            </div>
            <!-- /container -->
            <!-- Bootstrap core JavaScript
================================================== -->
            <!-- Placed at the end of the document so the pages load faster -->
        </body>
    </html>
</apex:page>
Apex: 
public class attachController
{
    public case objcase{get;set;}
    public Attachment myAttachment{get;set;}
    public string fileName{get;set;}
    public Blob fileBody{get;set;}
    
    public attachController(Apexpages.standardcontroller controller)
    {
        objcase = (Case)controller.getRecord();
        myAttachment = new Attachment();
    }
    public PageReference submit(){
        if (fileName != null){
            objcase.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Product Case').getRecordTypeId();
            insert objcase;
            System.debug('@@@@@fileBody'+fileBody);    
            myAttachment = new Attachment();
            Integer i=0;
            myAttachment .clear();
            myAttachment.Body = fileBody;
            myAttachment.Name = fileName ;
            myAttachment.ParentId = objcase.id;            
            insert myAttachment;
        } else {
            objcase.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Product Case').getRecordTypeId();
            insert objcase;
               
        }             
        pagereference pr = Page.thankYouForSubmittingYourProductCase;                          
        pr.setRedirect(true);
        return pr;
    }
}
Test: 
@isTest
public class attachController_Test {
    static testMethod void test1()
    {
        Case cs = new Case(
            Email__c = 'Test@test.com', 
            Subject = 'Phone',
            What_are_you_experiencing__c = 'I have a feature request', 
            Location_of_issue__c = 'Campaigns',
            Source_Type__c = 'Source', 
            Campaign_Source_ID__c = '123456',
            Description = 'test from Mr. Testerson'
        );
        insert cs;
        
        Attachment attach=new Attachment();       
        attach.Name='Unit Test Attachment';
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
        attach.body=bodyBlob;
        attach.parentId=cs.id;
        insert attach;
        
        List<Attachment> attachments=[select id, name from Attachment where parent.id=:cs.id];
        System.assertEquals(1, attachments.size());
        
        ApexPages.StandardController stdCtr = new ApexPages.StandardController(cs);
        attachController ctr = new attachController(stdCtr);
        ctr.objcase = cs;
        ctr.myAttachment = attach;
        ctr.submit();   
    }
}



 
I am trying to create a visualforce button that then inserts an opportunity and then sends an email to anyone if the running user is listed as the marketing_development_rep__c. Not sure if I am doing something wrong but it isn't creating the opportunity when I go and hit save.

VF: 
<apex:page controller="mdrHandOffOppInsert" sidebar="false" showHeader="false">
    <apex:form id="frm">
        <apex:pageBlock >
            <strong>Please provide any reference notes for this deal.</strong>
            <apex:pageBlockSection >
               <apex:inputField value="{!Opportunity.Hand_Off_Notes__c}" required="true"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
                <apex:actionFunction name="quickSaveJavascript" action="{!quicksave}" oncomplete="window.top.close();"/>
               <apex:commandButton value="Submit" onclick="quickSaveJavascript();"/>
               <!--<apex:commandButton action="{!cancel}" value="Cancel"/>-->
           </apex:pageBlockButtons>
       </apex:pageBlock>
    </apex:form>
</apex:page>

Apex:
 
public class mdrHandOffOppInsert {
    public Account acc{get; set;}
    public opportunity oppstring{get; set;}
    public mdrHandOffOppInsert(){oppstring= new opportunity();}
    public void Saveto(){
        opportunity opp= new opportunity();
        opp.Accountid= oppstring.Accountid;
		opp.StageName= 'F- Awareness';
        opp.CloseDate=date.today()+90;
        opp.Type='New Business';
        opp.Name= oppstring.name + ' SaaS Deal';
        opp.Marketing_Opp__c = true;
        opp.RecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('SaaS - Marketer').getRecordTypeId();		             
        insert opp;
		}
    
}

public static sendEmailToAccDir {
    
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
                List <User> sadList= SELECT Account_Director__r.email
               	  				 		FROM team__c
               	  						WHERE Marketing_Development_Rep__r.id = UserInfo.getUserId()]; 
                mail.setTargetObjectId(Con[0].id); 
                mail.setSenderDisplayName('Salesforce Support'); 
                mail.setUseSignature(false); 
                mail.setBccSender(false); 
                mail.setSaveAsActivity(false); 
                EmailTemplate et=[Select id from EmailTemplate where Name=:'MDR_Sales_Handoff_Initial_Alert']; 
                mail.setTemplateId(et.id); 
                Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

​​​​​​​
I am trying to have a site that has a visualforce page allowing someone to upload an attachment with the new record that they are creating. I have the attachment passing at 95% code coverage but it doesn't seem to actually be uploading the attachment with the new record.

VF: 
<apex:pageBlockButtons >
    <apex:commandButton action="{!save}" value="Submit"/>
       <apex:commandButton action="{!cancel}" value="Cancel"/>
    </apex:pageBlockButtons>
    <apex:pageBlockSection title="Upload the Attachment" collapsible="false" dir="LTR" columns="1">
        <div id="upload" class="upload">                                   
            <apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>                            
        </div>
</apex:pageBlockSection>

Apex Class: 
public class dataSheetAttachment
{
    public Data_Feasibility_Request__c objdfr{get;set;}
    public Attachment myAttachment{get;set;}
    public string fileName{get;set;}
    public Blob fileBody{get;set;}

    public dataSheetAttachment(Apexpages.standardcontroller controller)
    {
        objdfr = (Data_Feasibility_Request__c)controller.getRecord();
        myAttachment = new Attachment();
    }
    public pagereference save()
    {
        if(myAttachment.Name == null)
        {
            insert objdfr;
        }
        if(myAttachment.Name != null)
        {
            insert objdfr;
            System.debug('@@@@@fileBody'+fileBody);    
            myAttachment = new Attachment();
            Integer i=0;
            myAttachment .clear();
            myAttachment.Body = fileBody;
            myAttachment.Name = fileName ;
            myAttachment.ParentId = objdfr.id;            
            insert myAttachment;   
        }             
       pagereference pr = Page.Thank_You;                          
       pr.setRedirect(true);
       return pr;
    }
}
Test Class: 
 
@isTest
private class Test_dataSheetAttachment {

public static testMethod void validatedataSheetAttachment() {        
    Data_Feasibility_Request__c myDFR = new Data_Feasibility_Request__c();
    dataSheetAttachment pageController = new dataSheetAttachment(new ApexPages.StandardController(myDFR));
  
    pageController.myAttachment.Name = 'foo';
    pageController.fileBody=Blob.valueOf('Body Test');
    pageController.fileName = 'Test';
    pageController.save();
  
    }

}



Wondering if someone might be able to help me figure out what I might be doing incorrect? 
I am trying to write a trigger that updates Account, Contact and Opportunity with the lead after that said lead is converted. Does anyone have the most recommended practice for this? 
I am trying to create a custom button that works for multiple different objects to all come back to my Data_Feasibility_Report__c custom object. I was trying to create the button to pull from the Lead standard object but I keep gettting an error that I am not sure how to fix. Any help would be appreciated. Here is the code that I am trying to write. I am trying to pull the Name from the Lead and the record type as well as a couple custom fields. When I go test the button I get "Invalid or unexpected token".
 
{!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/33.0/apex.js")}
 
var DFR = new sforce.SObject("Data_Feasibility_Request__c"); 
DFR.Related_To__c = 'Lead';
DFR.Related_Lead__c = '{!Lead.Name}';
DFR.RecordID=0125C00000005jd;

var result = sforce.connection.create([DFR]);
 
if(result[0].getBoolean("success")){
   alert('New record updated successfully');
}
else{
  alert('Error : '+result);
}

I tried this another way but I am getting an error the second way I tried as well. Any help on either of these would be appreciated. 
 
{!REQUIRESCRIPT('/soap/ajax/37.0/connection.js')} 

getDate = function(dateObj){ 
var day = dateObj.getDay() < 9 ? '0'+dateObj.getDay() : dateObj.getDay(); 
var month = dateObj.getMonth() < 9 ? '0'+dateObj.getMonth() : dateObj.getMonth(); 

return dateObj.getFullYear()+'-'+month+'-'+day; 
} 

var oppty = new sforce.SObject('Data_Feasibility_Report__c'); 

oppty.Related_Lead__c = '{!Lead.Name}; 
oppty.Related_To__c = 'Lead'; 
RecordType=0125C00000005jd; 

result = sforce.connection.create([oppty]); 

if(result[0].success == 'true'){ 
alert('An New Opportunity with Name - ' + oppty.Name + ' was Created Successfully.'); 
}

 
I am trying to create a case external page that allows for me to use the standard controller with an extension so that they are able to add an attachment if they are wanting to. I had it where it wouldn't upload the attachment and now it will only upload the attachment and leaves all of the data alone. Anyone know of a way for it to do both?

VF Page:
<apex:page standardController="Case" extensions="caseattachment">
    <apex:form id="frm">
        <apex:pageBlock title="New Salesforce Case">
            <apex:pageBlockSection columns="1"  title="Salesforce Case -- Red lines represent required fields." collapsible="false">
            </apex:pageBlockSection>
            <strong>Please click the lookup icon (small button to right of field) to search name selection from Salesforce lookup dialog.</strong>
            <apex:pageBlockSection columns="1">
               <apex:inputField value="{!Case.Requestor_Name__c}" required="true"/>
               <br></br>
               </apex:pageBlockSection>
            <strong>Select Problem and High Priority ONLY if the issue is preventing you from continuing work in Salesforce.</strong>
            <apex:pageBlockSection columns="1">
               <apex:inputField value="{!Case.Type}" required="true"/>
               <apex:inputField value="{!Case.Priority}" required="true"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection columns="1" title="Case Details" collapsible="false">
               <apex:inputField value="{!Case.Department__c}" required="true"/>
               <apex:inputField value="{!Case.Salesforce_Object__c}" required="true"/>
               <apex:inputField value="{!Case.Description}" required="true" style="width:50%; height: 60px" />
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
               <apex:commandButton action="{!save}" value="Submit"/>
               <apex:commandButton action="{!cancel}" value="Cancel"/>
           </apex:pageBlockButtons>
        <apex:pageBlockSection title="Upload the Attachment" collapsible="false" dir="LTR" columns="1">
        <div id="upload" class="upload">                                   
            <apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>                            
        </div>
        </apex:pageBlockSection>
       </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class: 
public class caseattachment
{
public case objcase{get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;} 
public Blob fileBody{get;set;}

    public caseattachment(Apexpages.standardcontroller controller)
    {
        objcase = new case();
        myAttachment =new Attachment();
    }
    public pagereference save()
    {
        insert objcase;
        System.debug('@@@@@fileBody'+fileBody);     
        myAttachment  = new Attachment();
              Integer i=0;
              myAttachment .clear();
              myAttachment.Body = fileBody; 
              myAttachment.Name = 'Logo_'+objcase.id+'.jpeg' ; 
              myAttachment.ParentId = objcase.id;             
              insert myAttachment;                 
        pagereference pr = new pagereference('/'+objcase.id);                           
        return pr;
    }
}

Anyone know what I am doing wrong? 
 

hi ,

 

im working on to write test class, in that im facing problem to how to wrire test code for the attachment class. please provide solution for that.

 

 

thakyou.