• Ali Meyer
  • NEWBIE
  • 25 Points
  • Member since 2012

  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 18
    Replies
My code is pretty much right off of Jeff Douglas's wonderful blog (http://blog.jeffdouglas.com/2010/07/13/building-a-dynamic-search-page-in-visualforce/) and while it compiles just fine, the search doesn't actually work. I think there's something wrong with my SQL query because the dynamic search isn't altering it (as you can see in the debug log)--I think it's something related to the doSearch but I just can't figure it out.

Anyone want to give it a shot?:

Class:
public with sharing class RClassTest {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public RClassTest() {
    soql = 'select firstname, lastname, Id, account.name, CMI_Leadership__c, account.BillingStreet, account.BillingCity, account.BillingState from contact where account.name != null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {

    String firstName = Apexpages.currentPage().getParameters().get('firstname');
    String lastName = Apexpages.currentPage().getParameters().get('lastname');
    String accountName = Apexpages.currentPage().getParameters().get('accountName');
    String CMILeadership = Apexpages.currentPage().getParameters().get('CMILeadership');
    String billingCity = Apexpages.currentPage().getParameters().get('billingCity');
    String billingState = Apexpages.currentPage().getParameters().get('billingState');

    soql = 'select firstname, lastname, account.name, account.BillingStreet, account.BillingState, account.BillingCity, CMI_Leadership__c from contact where account.name != null';
    if (!firstName.equals(''))
      soql += ' and firstname LIKE \''+String.escapeSingleQuotes(firstName)+'%\'';
    if (!lastName.equals(''))
      soql += ' and lastname LIKE \''+String.escapeSingleQuotes(lastName)+'%\'';
    if (!accountName.equals(''))
      soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+'%\'';
    if (!CMILeadership.equals(''))
      soql += ' and CMI_Leadership__c includes (\''+CMILeadership+'\')';
    if (!billingCity.equals(''))
      soql += ' and account.BillingCity LIKE \''+String.escapeSingleQuotes(billingCity)+'%\'';
    if (!billingState.equals(''))
      soql += ' and account.BillingState LIKE \''+String.escapeSingleQuotes(billingState)+'%\'';

    // run the query again
    runQuery();

    return null;
  }

  // use apex describe to build the picklist values
  public List<String> CMILeadership {
    get {
      if (CMILeadership == null) {

        CMILeadership = new List<String>();
        Schema.DescribeFieldResult field = Contact.CMI_Leadership__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          CMILeadership.add(f.getLabel());

      }
      return CMILeadership;        
    }
    set;
  }

}

Page:
<apex:page controller="RClassTest" sidebar="false">

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

  <apex:pageBlock title="Search the Referral Database" mode="edit">

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

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

      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("firstName").value,
          document.getElementById("lastName").value,
          document.getElementById("accountName").value,
          document.getElementbyId("billingCity").value,
          document.getElementbyId("billingState").value,
          document.getElementById("CMILeadership").options[document.getElementById("CMILeadership").selectedIndex].value
          );
      }
      </script>

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="firstName" value="" />
          <apex:param name="lastName" value="" />
          <apex:param name="accountName" value="" />
          <apex:param name="billingCity" value="" />
          <apex:param name="billingState" value="" />
          <apex:param name="CMILeadership" value="" />
      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
        <input type="text" id="firstName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Last Name<br/>
        <input type="text" id="lastName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="accountName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">City<br/>
        <input type="text" id="billingCity" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">State<br/>
        <input type="text" id="billingState" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">CMI Leadership<br/>
          <select id="CMILeadership" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!CMILeadership}" var="CMI">
              <option value="{!CMI}">{!CMI}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>

      </apex:pageBlock>

    </td>
    <td valign="top">

    <apex:pageBlock mode="edit" id="results">

        <apex:pageBlockTable value="{!contacts}" var="contact">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.id}">
                <apex:outputField value="{!contact.firstName}"/>
                </apex:outputlink>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.id}">
                <apex:outputField value="{!contact.lastName}"/>
                </apex:outputlink>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.account.id}">
                <apex:outputField value="{!contact.account.name}"/>
                </apex:outputlink>
            </apex:column>
          
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Address" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingStreet" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingStreet}"/>
            </apex:column>
          
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="City" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingCity" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingCity}"/>
            </apex:column>
          
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="State" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingState" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingState}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="CMILeadership" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="CMI_Leadership__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.CMI_Leadership__c}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>

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

  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />
              
  </apex:pageBlock>  

  </apex:pageBlock>

  </apex:form>

</apex:page>

Thank you so much!!
My code is pretty much right off of Jeff Douglas's wonderful blog (http://blog.jeffdouglas.com/2010/07/13/building-a-dynamic-search-page-in-visualforce/) and while it compiles just fine, the search doesn't actually work. I think there's something wrong with my SQL query because the dynamic search isn't altering it (as you can see in the debug log)--I think it's something related to the doSearch but I just can't figure it out.

Anyone want to give it a shot?:

Class:
public with sharing class RClassTest {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public RClassTest() {
    soql = 'select firstname, lastname, Id, account.name, CMI_Leadership__c, account.BillingStreet, account.BillingCity, account.BillingState from contact where account.name != null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {

    String firstName = Apexpages.currentPage().getParameters().get('firstname');
    String lastName = Apexpages.currentPage().getParameters().get('lastname');
    String accountName = Apexpages.currentPage().getParameters().get('accountName');
    String CMILeadership = Apexpages.currentPage().getParameters().get('CMILeadership');
    String billingCity = Apexpages.currentPage().getParameters().get('billingCity');
    String billingState = Apexpages.currentPage().getParameters().get('billingState');

    soql = 'select firstname, lastname, account.name, account.BillingStreet, account.BillingState, account.BillingCity, CMI_Leadership__c from contact where account.name != null';
    if (!firstName.equals(''))
      soql += ' and firstname LIKE \''+String.escapeSingleQuotes(firstName)+'%\'';
    if (!lastName.equals(''))
      soql += ' and lastname LIKE \''+String.escapeSingleQuotes(lastName)+'%\'';
    if (!accountName.equals(''))
      soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+'%\''; 
    if (!CMILeadership.equals(''))
      soql += ' and CMI_Leadership__c includes (\''+CMILeadership+'\')';
    if (!billingCity.equals(''))
      soql += ' and account.BillingCity LIKE \''+String.escapeSingleQuotes(billingCity)+'%\'';
    if (!billingState.equals(''))
      soql += ' and account.BillingState LIKE \''+String.escapeSingleQuotes(billingState)+'%\'';

    // run the query again
    runQuery();

    return null;
  }

  // use apex describe to build the picklist values
  public List<String> CMILeadership {
    get {
      if (CMILeadership == null) {

        CMILeadership = new List<String>();
        Schema.DescribeFieldResult field = Contact.CMI_Leadership__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          CMILeadership.add(f.getLabel());

      }
      return CMILeadership;         
    }
    set;
  }

}

Page:
<apex:page controller="RClassTest" sidebar="false">

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

  <apex:pageBlock title="Search the Referral Database" mode="edit">

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

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

      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("firstName").value,
          document.getElementById("lastName").value,
          document.getElementById("accountName").value,
          document.getElementbyId("billingCity").value,
          document.getElementbyId("billingState").value,
          document.getElementById("CMILeadership").options[document.getElementById("CMILeadership").selectedIndex].value
          );
      }
      </script>

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="firstName" value="" />
          <apex:param name="lastName" value="" />
          <apex:param name="accountName" value="" />
          <apex:param name="billingCity" value="" />
          <apex:param name="billingState" value="" />
          <apex:param name="CMILeadership" value="" />
      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
        <input type="text" id="firstName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Last Name<br/>
        <input type="text" id="lastName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="accountName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">City<br/>
        <input type="text" id="billingCity" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">State<br/>
        <input type="text" id="billingState" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">CMI Leadership<br/>
          <select id="CMILeadership" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!CMILeadership}" var="CMI">
              <option value="{!CMI}">{!CMI}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>

      </apex:pageBlock>

    </td>
    <td valign="top">

    <apex:pageBlock mode="edit" id="results">

        <apex:pageBlockTable value="{!contacts}" var="contact">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.id}">
                <apex:outputField value="{!contact.firstName}"/>
                </apex:outputlink>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.id}">
                <apex:outputField value="{!contact.lastName}"/>
                </apex:outputlink>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.account.id}">
                <apex:outputField value="{!contact.account.name}"/>
                </apex:outputlink>
            </apex:column>
           
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Address" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingStreet" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingStreet}"/>
            </apex:column>
           
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="City" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingCity" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingCity}"/>
            </apex:column>
           
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="State" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingState" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingState}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="CMILeadership" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="CMI_Leadership__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.CMI_Leadership__c}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>

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

  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />
               
  </apex:pageBlock>   

  </apex:pageBlock>

  </apex:form>

</apex:page>

Thank you so much!!

Hello,

 

I'm trying to write a trigger that will do three things: 

1. take info from a custom object 

2. create an account from that info

3. create a contact from that info

 

I lifted this code from here but I don't really know what I'm doing. I think the first problem is declaring the Account variable; my error message says "Name" does not exist.

 

Thank you for your help!

 

trigger CreateContact on Intake_Phone_Screen_Information__c (after update, after insert) {
    
    List<Intake_Phone_Screen_Information__c> IntakeList = new List<Intake_Phone_Screen_Information__c>();
    List<Account> AccList = new List<Account>();
        for(Intake_Phone_Screen_Information__c i:Trigger.new){
              Account a = new Account(Name = i.Caller_First_Name__c, RecordTypeId = '012A0000000dlDz'); 
              }
              insert a;
    //newAccount has IDs since been inserted, so parallel list to Trigger.new
              
    Integer cnt = 0;
        for(Intake_Phone_Screen_Information__c i:Trigger.new){
              if (i.Boolean_Appointment__c = TRUE){
              cnt++;
              continue;
              }
              newContact.add(FirstName = i.Caller_First_Name__c, LastName = i.Caller_Last_Name__c, Date_entered_as_new_patient__c = System.today(), Account = newAccount[cnt].Id);
              cnt++; 
              }
     if (!newContact.isEmpty()) insert newContact;
    
}

 

 

Hello,

 

I don't get any compile errors, but the thing that's supposed to happen just doesn't when I run this trigger. Basically, I have a contact lookup field on my Clinical_Intake_Object (Parent_Name_2), and when certain criteria on the Clinical lntake Object are met (clinician assigned, not canceled) I want to change the record type of the contact to "Household." Instead, this trigger just keeps the record type the same, and I don't know why.

 

Thank you!

 

trigger updateClinical2 on Clinical_Intake_Object__c (after update, after insert)
{
Map<Id, Contact> consMap = new Map<Id, Contact>();
Set<id> Ids = new Set <id>();
for (Clinical_Intake_Object__c tk: Trigger.new)
{
Ids.add(tk.Parent_Name_2__c);
}
Map<id, Contact> consMap2 = new Map<id, Contact>([SELECT Id FROM Contact WHERE Id in :Ids]);
for (Clinical_Intake_Object__c t: Trigger.new)
if (t.Parent_Name_2__c != null && t.Canceled__c!= true && t.Clinician_Assigned__c !=null && t.CMI_Appointment_Date__c !=null)
{
Contact c = consMap2.get(t.Parent_Name_2__c);
List<Contact> consList = [SELECT Name, Id FROM Contact WHERE Id in :Ids];

List<RecordType> rtypes = [SELECT Name, Id FROM RecordType WHERE sObjectType = 'Contact' and isActive = true];
Map<String, String> contactRecordTypes = new Map<String, String>{};
for(RecordType rt: rtypes)
    contactRecordTypes.put(rt.Name, rt.Id);

c.RecordTypeId = contactRecordTypes.get('Household Contact');  
upsert consMap.values();
consMap.put(c.Id,c);

}}

 

I'm trying to write what I think is a really simple trigger: I want to change the contact field "2013 Clinician" if certain criteria are met in a related task. Below is my code: it doesn't have any compile errors but it also just plain doesn't work. 

 

Thank you!

 

trigger updateConsTask on Task (after update, after insert)
{

Map<Id, Contact> consMap = new Map<Id, Contact>();
Set<id> Ids = new Set <id>();
    for (Task tk: Trigger.new)
    {
    Ids.add(tk.WhoId);
    }
Map<id, Contact> consMap2 = new Map<id, Contact>([SELECT Id FROM Contact WHERE Id in :Ids]);
    for (Task t: Trigger.new)
    if (t.WhoId != null && t.Status == 'Cultivate')
    {
    Contact c = consMap2.get(t.WhoId);
    c.X2013_Clinician__c = t.Clinician__c;
    
    consMap.put(c.id,c);
    }
    }

 

Hello,

 

I have a really basic issue: When a specific boolean field = true on a contact object, I want the ID of that contact to populate into a field on the associated Account object. I don't think this should be too hard but I am really new to Apex so I appreciate all the help I can get!

 

here's the code I have so far:

trigger Secondary on Contact (after update) {
List<Contact> cons = new List<Contact>();
    List<Contact> consToSecondary = new List<Contact>();
    
    for(Contact c:trigger.new){
        if(c.SecCon_Checkbox__c != null && c.cv__Head_of_Household__c != true){
            cons.add(c); 
        }
    }
    
    for(Contact c: cons){
    c.Account.cv__Secondary_Contact__c = c.Id;
    consToSecondary.add(c);
    }
    
    update consToSecondary;
}

 The code compiles alright but when I try to test it I get this error: 

 

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

 

Any help is appreciated, and thank you!

I wrote a trigger that works perfectly in sandbox and has 100% test coverage and deployed it to production; now that it's in the production instance, it doesn't work. I don't get any error messages, but the thing that it's supposed to do (create a contact if a specific field is filled in) just doesn't happen. In production, it also has 100% coverage. Any ideas what's going on?

 

Here's the code:

trigger SpouseTrigger on Contact (before insert) {
 2	      List<Contact> cons = new List<Contact>();
 3	      List<Contact> consToInsert = new List<Contact>();
 4	      
 5	      for(Contact c:trigger.new){
 6	          if(c.Sig_Other_First_Name__c != null && c.Sig_Other_Last_Name__c != null){
 7	              cons.add(c);
 8	          }
 9	      }
 10	      
 11	      for(Contact c: cons){
 12	          Contact newCon = new Contact();
 13	          newCon.FirstName = c.Sig_Other_First_Name__c;
 14	          newCon.LastName = c.Sig_Other_Last_Name__c;
 15	          newCon.AccountId = c.AccountId;
 16	          consToInsert.add(newCon);
 17	      }
 18	      
 19	      insert consToInsert;
 20	  }

 Thanks for your help!

Hello,

 

I'm really new to Apex and to code in general, so please try to not laugh at my pathetic test code. The code itself works (I tested manually) and it's a really basic trigger; the test code fails, though, and I can't figure out why. Can anyone help me figure out what's going on? Thank you!!

 

Trigger:

 

trigger SpouseTrigger on Contact (before insert) {
    List<Contact> cons = new List<Contact>();
    List<Contact> consToInsert = new List<Contact>();
    
    for(Contact c:trigger.new){
        if(c.Sig_Other_First_Name__c != null && c.Sig_Other_Last_Name__c != null){
            cons.add(c);
        }
    }
    
    for(Contact c: cons){
        Contact newCon = new Contact();
        newCon.FirstName = c.Sig_Other_First_Name__c;
        newCon.LastName = c.Sig_Other_Last_Name__c;
        newCon.AccountId = c.AccountId;
        consToInsert.add(newCon);
    }
    
    insert consToInsert;
}

 

Here's the test code, where something isn't working:

@istest
private class SpouseTriggerTest {

    static TestMethod void Test1_TestInsertContact() {
        Account acc = new Account(Name = 'My Account', RecordTypeid = '012A0000000dlDz');
        insert acc;
    
        Contact testC1 = new Contact(LastName='Test1 Contact', Sig_Other_First_Name__c='John', Sig_Other_Last_Name__c='Smith', AccountId = acc.Id);
        insert testC1;
        
        //pull the account info for that contact
        Contact SecContact1 = [SELECT FirstName, LastName, AccountId FROM Contact WHERE Id = :testC1.id];
        
        //verify that the insert updated by creating another contact as in the trigger
        System.assert(SecContact1.Id != null);
        System.assertEquals(SecContact1.FirstName, testC1.Sig_Other_First_Name__c);
        System.assertEquals(SecContact1.LastName, testC1.Sig_Other_Last_Name__c);
        System.assertEquals(SecContact1.AccountId, testC1.AccountId);
        
        Contact testC2 = new Contact(LastName='Test1 Contact', Sig_Other_First_Name__c=null, Sig_Other_Last_Name__c='Smith', AccountId = acc.Id);
        insert testC2;
        
        //pull the account info for that contact
        Contact SecContact2 = [SELECT FirstName, LastName, AccountId FROM Contact WHERE Id = :testC2.id];
        
        //verify that the insert updated by creating another contact as in the trigger
        System.assert(SecContact2.Id != null);
        System.assertNotEquals(SecContact2.FirstName, testC2.Sig_Other_First_Name__c);
        System.assertNotEquals(SecContact2.LastName, testC2.Sig_Other_Last_Name__c);
        System.assertNotEquals(SecContact2.AccountId, testC2.AccountId);
        
        Contact testC3 = new Contact(LastName='Test1 Contact', Sig_Other_First_Name__c='John', Sig_Other_Last_Name__c=null, AccountId = acc.Id);
        insert testC3;
        
        //pull the account info for that contact
        Contact SecContact3 = [SELECT FirstName, LastName, AccountId FROM Contact WHERE Id = :testC3.id];
        
        //verify that the insert updated by creating another contact as in the trigger
        System.assert(SecContact3.Id != null);
        System.assertNotEquals(SecContact3.FirstName, testC3.Sig_Other_First_Name__c);
        System.assertNotEquals(SecContact3.LastName, testC3.Sig_Other_Last_Name__c);
        System.assertNotEquals(SecContact3.AccountId, testC3.AccountId);
        
        Contact testC4 = new Contact(LastName='Test1 Contact', Sig_Other_First_Name__c=null, Sig_Other_Last_Name__c=null, AccountId = acc.Id);
        insert testC4;
        
        //pull the account info for that contact
        Contact SecContact4 = [SELECT FirstName, LastName, AccountId FROM Contact WHERE Id = :testC4.id];
        
        //verify that the insert updated by creating another contact as in the trigger
        System.assert(SecContact4.Id != null);
        System.assertNotEquals(SecContact4.FirstName, testC4.Sig_Other_First_Name__c);
        System.assertNotEquals(SecContact4.LastName, testC4.Sig_Other_Last_Name__c);
        System.assertNotEquals(SecContact4.AccountId, testC4.AccountId);
        
    }
}

 

Here's the error message I receive:

 

ClassSpouseTriggerTest
Method NameTest1_TestInsertContact
Pass/FailFail
Error MessageSystem.AssertException: Assertion Failed: Expected: null, Actual: John
Stack TraceClass.SpouseTriggerTest.Test1_TestInsertContact: line 16, column 1

 

I'm brand new to Apex and I'm working on my first trigger, pasted below. Through manual testing, I know that it works--however, i'm not quite sure how to create test code for it (my attempt is also pasted below). 

 

Any help would be appreciated, and thank you!

 

Trigger code:


trigger SpouseTrigger on Contact (before insert) {
    List<Contact> cons = new List<Contact>();
    List<Contact> consToInsert = new List<Contact>();
    
    for(Contact c:trigger.new){
        if(c.Sig_Other_First_Name__c != null && c.Sig_Other_Last_Name__c != null){
            cons.add(c);
        }
    }
    
    for(Contact c: cons){
        Contact newCon = new Contact();
        newCon.FirstName = c.Sig_Other_First_Name__c;
        newCon.LastName = c.Sig_Other_Last_Name__c;
        newCon.AccountId = c.AccountId;
        consToInsert.add(newCon);
    }
    
    insert consToInsert;
}

This trigger checks to see if two fields (Sig_Other_First_Name and Sig_Other_Last_Name) are filled in, and if they are, creates a new contact record. The contact record uses the First_Name as the First Name and the Last_Name as the last, and puts the contact within the same account as the original contact.

 

 My attempt at a test:

@istest
private class SpouseTriggerTest
{

static TestMethod void Test1_TestInsertContact()
{
Contact testC1 = new Contact(Text(80)='Test1 Contact', Sig_Other_First_Name__c='John', Sig_Other_Last_Name__c='Smith');
insert testC1;

//pull the account info for that contact
Contact SecContact = [SELECT cv__Contact__c FROM Account WHERE Id = :testc1.id];

//verify that the insert updated by creating another contact as in the trigger
System.assertEquals(testC1.account, SecContact.account);

}
}

I know this test is really awful but I don't even know where to start! So again, any help at all would be appreciated. Thank you!!

My code is pretty much right off of Jeff Douglas's wonderful blog (http://blog.jeffdouglas.com/2010/07/13/building-a-dynamic-search-page-in-visualforce/) and while it compiles just fine, the search doesn't actually work. I think there's something wrong with my SQL query because the dynamic search isn't altering it (as you can see in the debug log)--I think it's something related to the doSearch but I just can't figure it out.

Anyone want to give it a shot?:

Class:
public with sharing class RClassTest {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public RClassTest() {
    soql = 'select firstname, lastname, Id, account.name, CMI_Leadership__c, account.BillingStreet, account.BillingCity, account.BillingState from contact where account.name != null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {

    String firstName = Apexpages.currentPage().getParameters().get('firstname');
    String lastName = Apexpages.currentPage().getParameters().get('lastname');
    String accountName = Apexpages.currentPage().getParameters().get('accountName');
    String CMILeadership = Apexpages.currentPage().getParameters().get('CMILeadership');
    String billingCity = Apexpages.currentPage().getParameters().get('billingCity');
    String billingState = Apexpages.currentPage().getParameters().get('billingState');

    soql = 'select firstname, lastname, account.name, account.BillingStreet, account.BillingState, account.BillingCity, CMI_Leadership__c from contact where account.name != null';
    if (!firstName.equals(''))
      soql += ' and firstname LIKE \''+String.escapeSingleQuotes(firstName)+'%\'';
    if (!lastName.equals(''))
      soql += ' and lastname LIKE \''+String.escapeSingleQuotes(lastName)+'%\'';
    if (!accountName.equals(''))
      soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+'%\'';
    if (!CMILeadership.equals(''))
      soql += ' and CMI_Leadership__c includes (\''+CMILeadership+'\')';
    if (!billingCity.equals(''))
      soql += ' and account.BillingCity LIKE \''+String.escapeSingleQuotes(billingCity)+'%\'';
    if (!billingState.equals(''))
      soql += ' and account.BillingState LIKE \''+String.escapeSingleQuotes(billingState)+'%\'';

    // run the query again
    runQuery();

    return null;
  }

  // use apex describe to build the picklist values
  public List<String> CMILeadership {
    get {
      if (CMILeadership == null) {

        CMILeadership = new List<String>();
        Schema.DescribeFieldResult field = Contact.CMI_Leadership__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          CMILeadership.add(f.getLabel());

      }
      return CMILeadership;        
    }
    set;
  }

}

Page:
<apex:page controller="RClassTest" sidebar="false">

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

  <apex:pageBlock title="Search the Referral Database" mode="edit">

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

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

      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("firstName").value,
          document.getElementById("lastName").value,
          document.getElementById("accountName").value,
          document.getElementbyId("billingCity").value,
          document.getElementbyId("billingState").value,
          document.getElementById("CMILeadership").options[document.getElementById("CMILeadership").selectedIndex].value
          );
      }
      </script>

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="firstName" value="" />
          <apex:param name="lastName" value="" />
          <apex:param name="accountName" value="" />
          <apex:param name="billingCity" value="" />
          <apex:param name="billingState" value="" />
          <apex:param name="CMILeadership" value="" />
      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
        <input type="text" id="firstName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Last Name<br/>
        <input type="text" id="lastName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="accountName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">City<br/>
        <input type="text" id="billingCity" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">State<br/>
        <input type="text" id="billingState" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">CMI Leadership<br/>
          <select id="CMILeadership" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!CMILeadership}" var="CMI">
              <option value="{!CMI}">{!CMI}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>

      </apex:pageBlock>

    </td>
    <td valign="top">

    <apex:pageBlock mode="edit" id="results">

        <apex:pageBlockTable value="{!contacts}" var="contact">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.id}">
                <apex:outputField value="{!contact.firstName}"/>
                </apex:outputlink>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.id}">
                <apex:outputField value="{!contact.lastName}"/>
                </apex:outputlink>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.account.id}">
                <apex:outputField value="{!contact.account.name}"/>
                </apex:outputlink>
            </apex:column>
          
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Address" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingStreet" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingStreet}"/>
            </apex:column>
          
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="City" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingCity" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingCity}"/>
            </apex:column>
          
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="State" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingState" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingState}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="CMILeadership" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="CMI_Leadership__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.CMI_Leadership__c}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>

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

  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />
              
  </apex:pageBlock>  

  </apex:pageBlock>

  </apex:form>

</apex:page>

Thank you so much!!
My code is pretty much right off of Jeff Douglas's wonderful blog (http://blog.jeffdouglas.com/2010/07/13/building-a-dynamic-search-page-in-visualforce/) and while it compiles just fine, the search doesn't actually work. I think there's something wrong with my SQL query because the dynamic search isn't altering it (as you can see in the debug log)--I think it's something related to the doSearch but I just can't figure it out.

Anyone want to give it a shot?:

Class:
public with sharing class RClassTest {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public RClassTest() {
    soql = 'select firstname, lastname, Id, account.name, CMI_Leadership__c, account.BillingStreet, account.BillingCity, account.BillingState from contact where account.name != null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {

    String firstName = Apexpages.currentPage().getParameters().get('firstname');
    String lastName = Apexpages.currentPage().getParameters().get('lastname');
    String accountName = Apexpages.currentPage().getParameters().get('accountName');
    String CMILeadership = Apexpages.currentPage().getParameters().get('CMILeadership');
    String billingCity = Apexpages.currentPage().getParameters().get('billingCity');
    String billingState = Apexpages.currentPage().getParameters().get('billingState');

    soql = 'select firstname, lastname, account.name, account.BillingStreet, account.BillingState, account.BillingCity, CMI_Leadership__c from contact where account.name != null';
    if (!firstName.equals(''))
      soql += ' and firstname LIKE \''+String.escapeSingleQuotes(firstName)+'%\'';
    if (!lastName.equals(''))
      soql += ' and lastname LIKE \''+String.escapeSingleQuotes(lastName)+'%\'';
    if (!accountName.equals(''))
      soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+'%\''; 
    if (!CMILeadership.equals(''))
      soql += ' and CMI_Leadership__c includes (\''+CMILeadership+'\')';
    if (!billingCity.equals(''))
      soql += ' and account.BillingCity LIKE \''+String.escapeSingleQuotes(billingCity)+'%\'';
    if (!billingState.equals(''))
      soql += ' and account.BillingState LIKE \''+String.escapeSingleQuotes(billingState)+'%\'';

    // run the query again
    runQuery();

    return null;
  }

  // use apex describe to build the picklist values
  public List<String> CMILeadership {
    get {
      if (CMILeadership == null) {

        CMILeadership = new List<String>();
        Schema.DescribeFieldResult field = Contact.CMI_Leadership__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          CMILeadership.add(f.getLabel());

      }
      return CMILeadership;         
    }
    set;
  }

}

Page:
<apex:page controller="RClassTest" sidebar="false">

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

  <apex:pageBlock title="Search the Referral Database" mode="edit">

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

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

      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("firstName").value,
          document.getElementById("lastName").value,
          document.getElementById("accountName").value,
          document.getElementbyId("billingCity").value,
          document.getElementbyId("billingState").value,
          document.getElementById("CMILeadership").options[document.getElementById("CMILeadership").selectedIndex].value
          );
      }
      </script>

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="firstName" value="" />
          <apex:param name="lastName" value="" />
          <apex:param name="accountName" value="" />
          <apex:param name="billingCity" value="" />
          <apex:param name="billingState" value="" />
          <apex:param name="CMILeadership" value="" />
      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
        <input type="text" id="firstName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Last Name<br/>
        <input type="text" id="lastName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="accountName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">City<br/>
        <input type="text" id="billingCity" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">State<br/>
        <input type="text" id="billingState" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">CMI Leadership<br/>
          <select id="CMILeadership" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!CMILeadership}" var="CMI">
              <option value="{!CMI}">{!CMI}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>

      </apex:pageBlock>

    </td>
    <td valign="top">

    <apex:pageBlock mode="edit" id="results">

        <apex:pageBlockTable value="{!contacts}" var="contact">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.id}">
                <apex:outputField value="{!contact.firstName}"/>
                </apex:outputlink>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.id}">
                <apex:outputField value="{!contact.lastName}"/>
                </apex:outputlink>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputlink value="/{!contact.account.id}">
                <apex:outputField value="{!contact.account.name}"/>
                </apex:outputlink>
            </apex:column>
           
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Address" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingStreet" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingStreet}"/>
            </apex:column>
           
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="City" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingCity" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingCity}"/>
            </apex:column>
           
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="State" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingState" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.BillingState}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="CMILeadership" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="CMI_Leadership__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.CMI_Leadership__c}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>

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

  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />
               
  </apex:pageBlock>   

  </apex:pageBlock>

  </apex:form>

</apex:page>

Thank you so much!!

Hello,

 

I'm trying to write a trigger that will do three things: 

1. take info from a custom object 

2. create an account from that info

3. create a contact from that info

 

I lifted this code from here but I don't really know what I'm doing. I think the first problem is declaring the Account variable; my error message says "Name" does not exist.

 

Thank you for your help!

 

trigger CreateContact on Intake_Phone_Screen_Information__c (after update, after insert) {
    
    List<Intake_Phone_Screen_Information__c> IntakeList = new List<Intake_Phone_Screen_Information__c>();
    List<Account> AccList = new List<Account>();
        for(Intake_Phone_Screen_Information__c i:Trigger.new){
              Account a = new Account(Name = i.Caller_First_Name__c, RecordTypeId = '012A0000000dlDz'); 
              }
              insert a;
    //newAccount has IDs since been inserted, so parallel list to Trigger.new
              
    Integer cnt = 0;
        for(Intake_Phone_Screen_Information__c i:Trigger.new){
              if (i.Boolean_Appointment__c = TRUE){
              cnt++;
              continue;
              }
              newContact.add(FirstName = i.Caller_First_Name__c, LastName = i.Caller_Last_Name__c, Date_entered_as_new_patient__c = System.today(), Account = newAccount[cnt].Id);
              cnt++; 
              }
     if (!newContact.isEmpty()) insert newContact;
    
}

 

 

I'm trying to write what I think is a really simple trigger: I want to change the contact field "2013 Clinician" if certain criteria are met in a related task. Below is my code: it doesn't have any compile errors but it also just plain doesn't work. 

 

Thank you!

 

trigger updateConsTask on Task (after update, after insert)
{

Map<Id, Contact> consMap = new Map<Id, Contact>();
Set<id> Ids = new Set <id>();
    for (Task tk: Trigger.new)
    {
    Ids.add(tk.WhoId);
    }
Map<id, Contact> consMap2 = new Map<id, Contact>([SELECT Id FROM Contact WHERE Id in :Ids]);
    for (Task t: Trigger.new)
    if (t.WhoId != null && t.Status == 'Cultivate')
    {
    Contact c = consMap2.get(t.WhoId);
    c.X2013_Clinician__c = t.Clinician__c;
    
    consMap.put(c.id,c);
    }
    }

 

 Hai..............

                  I created Dynamic search page with custom object (applicant) having fields firstname,skillset(text datatype), expected annual salary(currency data type)  ,location(text data type) etc.......


 i got the table with all the field values.But the thing is when i enter the values in the input field ,the query is not exectuing can any one help me .............

 

 I think  the values are not passing from javascript to controller...............

Here is my Controller code....

 

public with sharing class SearchapplicantsController {   
    
    private String soql {get;set;}
    // the collection of contacts to display
      Public List<Applicant__c>  applicants {get;set;}
    // the current sort direction. deaults to asc
      public String sortDir{
      get { if (sortDir == null) { sortDir = 'asc'; } 
             return sortDir;
             }
             set;
             }
    // the current field to sort by. defaults to last name 
        public String sortField {
          get {
                if  ( sortField == null) {
                sortField = 'First_Name__c'; } return sortField; }
                set;
                }
      // format the soql for display on the visualforce page 
           public String debugSoql {
              get { return soql + ' order by ' + sortField + ' ' + sortDir + 'limit 20 '; }
               set;
               }
      // init the contrller and display some sample data when the page loads
          public SearchapplicantsController() {
            soql='select First_name__c,Skill_set__c,Experience__c,Qualification__c,Expected_Annual_Salary__c,Location__c from Applicant__c  where Applicant__c.First_name__c != null ';    
                   runQuery();
                   }
        // toggles the sorting  of query from asc<-->desc
            public void toggleSort() {
              //simply toggle the direction  
                   sortDir = sortDir.equals('asc') ? 'desc' : 'asc' ;
                  // run the query again
                    runQuery();
                    }             
        //runs the actualquery
           public void runQuery() {
              try {
                   applicants  = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20 ');
                    }
                    catch (Exception e) {
                     ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, ' OOOps! ') );
                     }
                   }                                
    // runs the search with parameters passed via JavaScript
      public PageReference runSearch(){
      
      
          String FirstName = Apexpages.currentPage().getParameters().get('First_Name__c');
    String Skillset = Apexpages.currentPage().getParameters().get('Skill_set__c');
    String Experience = Apexpages.currentPage().getParameters().get('Experience__c');
    String ExpectedSalary = Apexpages.currentPage().getParameters().get('Expected_Annual_Salary__c');
String Location = Apexpages.currentPage().getParameters().get('Location__c');
String Qualification = Apexpages.currentPage().getParameters().get('Qualification__c');

 
    soql='select First_name__c,Skill_set__c,Experience__c,Qualification__c,Expected_Annual_Salary__c,Location__c from Applicant__c where Applicant__c.First_name__c != null' ;    

    if (!FirstName.equals(''))
      soql += ' and First_Name__c LIKE \''+String.escapeSingleQuotes(FirstName)+'%\'';
    if (!Skillset.equals(''))
      soql += ' and Skill_Set__c LIKE \''+String.escapeSingleQuotes(Skillset)+'%\'';
    if (!Experience.equals(''))
      soql += ' and Experience__c LIKE \''+String.escapeSingleQuotes(Experience)+'%\'';  
    if (!ExpectedSalary.equals(''))
      soql += ' and Expected_Annual_Salary__c LIKE  \''+String.escapeSingleQuotes(Expectedsalary)+'%\' ';
if (!Qualification.equals(''))
      soql += ' and Qualification__c LIKE (\' '+Qualification+'\')';
 
    // run the query again
    runQuery();
 
    return null;
  }
 
  // use apex describe to build the picklist values
  public List<String> Qualification {
    get {
      
      
      
      if (Qualification == null) {
 
        Qualification = new List<String>();
        Schema.DescribeFieldResult field = Applicant__c.Qualification__c.getDescribe();
 
        for (Schema.PicklistEntry f : field.getPicklistValues())
         Qualification.add(f.getLabel());
 
      }
      return Qualification;          
    }
    set;
  }
 
}

 

 

 

 

Here is my visualforce code............

 

<apex:page controller="SearchapplicantsController" sidebar="false">

 <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("First_Name__c").value,
          document.getElementById("Skill_set__c").value,
          document.getElementById("Experience__c").value,
           document.getElementById("Expected_Annual_Salary__c").value,
          document.getElementById("Location__c").value,
          document.getElementById("Qualification__c").options[document.getElementById("Qualification__c").selectedIndex].value
          );
      }
      </script>
 
  <apex:form >
  <apex:pageMessages id="errors" />
 
  <apex:pageBlock title="Find Me A Candidate!" mode="edit">
 
  <table width="100%" border="0">
  <tr>  
    <td width="200" valign="top">
 
      <apex:pageBlock title="Parameters" mode="edit" id="criteria">
 
       
 
      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="First_name__c" value="" />
          <apex:param name="Skill_set__c" value="" />
          <apex:param name="Experience__c" value="" />
          <apex:param name="Expected_Annual_salary__c" value="" />
          <apex:param name="Location__c" value="" />
          <apex:param name="Qualification__c" value="" />
      </apex:actionFunction>
 
      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
        <input type="text" id="First_name__c" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Skillset<br/>
        <input type="text" id="Skill_set__c" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Experience<br/>
        <input type="text" id="Experience__c" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Expected salary<br/>
        <input type="text" id="Expected_Annual_salary__c" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Location<br/>
        <input type="text" id="Location__c" onkeyup="doSearch();"/>
        </td>
      </tr>

      <tr>
        <td style="font-weight:bold;">Qualification<br/>
          <select id="Qualification__c" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!Qualification}" var="qua">
              <option value="{!qua}"> {!qua}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>
 
      </apex:pageBlock>
 
    </td>
    <td valign="top">
 
    <apex:pageBlock mode="edit" id="results">
 
        <apex:pageBlockTable value="{!applicants}" var="applicant">
 
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="first_name__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!applicant.First_Name__c}"/>
            </apex:column>
 
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Skill set" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Skill_set__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!applicant.Skill_set__c}"/>
            </apex:column>
 
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Experience" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Experience__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!applicant.Experience__c}"/>
            </apex:column>
 
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Expected salary" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Expected_Annual_salary__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!applicant.Expected_Annual_Salary__c}"/>
            </apex:column>
                   <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Location" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Location__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!applicant.Location__c}"/>
            </apex:column>
  <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Education" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Qualification__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!applicant.Qualification__c}"/>
            </apex:column>
 
        </apex:pageBlockTable>
 
    </apex:pageBlock>
 
    </td>
  </tr>
  </table>
 
  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />           
  </apex:pageBlock>    
 
  </apex:pageBlock>
 
  </apex:form>
 
</apex:page>

Hello,

 

I have a really basic issue: When a specific boolean field = true on a contact object, I want the ID of that contact to populate into a field on the associated Account object. I don't think this should be too hard but I am really new to Apex so I appreciate all the help I can get!

 

here's the code I have so far:

trigger Secondary on Contact (after update) {
List<Contact> cons = new List<Contact>();
    List<Contact> consToSecondary = new List<Contact>();
    
    for(Contact c:trigger.new){
        if(c.SecCon_Checkbox__c != null && c.cv__Head_of_Household__c != true){
            cons.add(c); 
        }
    }
    
    for(Contact c: cons){
    c.Account.cv__Secondary_Contact__c = c.Id;
    consToSecondary.add(c);
    }
    
    update consToSecondary;
}

 The code compiles alright but when I try to test it I get this error: 

 

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

 

Any help is appreciated, and thank you!

I wrote a trigger that works perfectly in sandbox and has 100% test coverage and deployed it to production; now that it's in the production instance, it doesn't work. I don't get any error messages, but the thing that it's supposed to do (create a contact if a specific field is filled in) just doesn't happen. In production, it also has 100% coverage. Any ideas what's going on?

 

Here's the code:

trigger SpouseTrigger on Contact (before insert) {
 2	      List<Contact> cons = new List<Contact>();
 3	      List<Contact> consToInsert = new List<Contact>();
 4	      
 5	      for(Contact c:trigger.new){
 6	          if(c.Sig_Other_First_Name__c != null && c.Sig_Other_Last_Name__c != null){
 7	              cons.add(c);
 8	          }
 9	      }
 10	      
 11	      for(Contact c: cons){
 12	          Contact newCon = new Contact();
 13	          newCon.FirstName = c.Sig_Other_First_Name__c;
 14	          newCon.LastName = c.Sig_Other_Last_Name__c;
 15	          newCon.AccountId = c.AccountId;
 16	          consToInsert.add(newCon);
 17	      }
 18	      
 19	      insert consToInsert;
 20	  }

 Thanks for your help!

Hello,

 

I'm really new to Apex and to code in general, so please try to not laugh at my pathetic test code. The code itself works (I tested manually) and it's a really basic trigger; the test code fails, though, and I can't figure out why. Can anyone help me figure out what's going on? Thank you!!

 

Trigger:

 

trigger SpouseTrigger on Contact (before insert) {
    List<Contact> cons = new List<Contact>();
    List<Contact> consToInsert = new List<Contact>();
    
    for(Contact c:trigger.new){
        if(c.Sig_Other_First_Name__c != null && c.Sig_Other_Last_Name__c != null){
            cons.add(c);
        }
    }
    
    for(Contact c: cons){
        Contact newCon = new Contact();
        newCon.FirstName = c.Sig_Other_First_Name__c;
        newCon.LastName = c.Sig_Other_Last_Name__c;
        newCon.AccountId = c.AccountId;
        consToInsert.add(newCon);
    }
    
    insert consToInsert;
}

 

Here's the test code, where something isn't working:

@istest
private class SpouseTriggerTest {

    static TestMethod void Test1_TestInsertContact() {
        Account acc = new Account(Name = 'My Account', RecordTypeid = '012A0000000dlDz');
        insert acc;
    
        Contact testC1 = new Contact(LastName='Test1 Contact', Sig_Other_First_Name__c='John', Sig_Other_Last_Name__c='Smith', AccountId = acc.Id);
        insert testC1;
        
        //pull the account info for that contact
        Contact SecContact1 = [SELECT FirstName, LastName, AccountId FROM Contact WHERE Id = :testC1.id];
        
        //verify that the insert updated by creating another contact as in the trigger
        System.assert(SecContact1.Id != null);
        System.assertEquals(SecContact1.FirstName, testC1.Sig_Other_First_Name__c);
        System.assertEquals(SecContact1.LastName, testC1.Sig_Other_Last_Name__c);
        System.assertEquals(SecContact1.AccountId, testC1.AccountId);
        
        Contact testC2 = new Contact(LastName='Test1 Contact', Sig_Other_First_Name__c=null, Sig_Other_Last_Name__c='Smith', AccountId = acc.Id);
        insert testC2;
        
        //pull the account info for that contact
        Contact SecContact2 = [SELECT FirstName, LastName, AccountId FROM Contact WHERE Id = :testC2.id];
        
        //verify that the insert updated by creating another contact as in the trigger
        System.assert(SecContact2.Id != null);
        System.assertNotEquals(SecContact2.FirstName, testC2.Sig_Other_First_Name__c);
        System.assertNotEquals(SecContact2.LastName, testC2.Sig_Other_Last_Name__c);
        System.assertNotEquals(SecContact2.AccountId, testC2.AccountId);
        
        Contact testC3 = new Contact(LastName='Test1 Contact', Sig_Other_First_Name__c='John', Sig_Other_Last_Name__c=null, AccountId = acc.Id);
        insert testC3;
        
        //pull the account info for that contact
        Contact SecContact3 = [SELECT FirstName, LastName, AccountId FROM Contact WHERE Id = :testC3.id];
        
        //verify that the insert updated by creating another contact as in the trigger
        System.assert(SecContact3.Id != null);
        System.assertNotEquals(SecContact3.FirstName, testC3.Sig_Other_First_Name__c);
        System.assertNotEquals(SecContact3.LastName, testC3.Sig_Other_Last_Name__c);
        System.assertNotEquals(SecContact3.AccountId, testC3.AccountId);
        
        Contact testC4 = new Contact(LastName='Test1 Contact', Sig_Other_First_Name__c=null, Sig_Other_Last_Name__c=null, AccountId = acc.Id);
        insert testC4;
        
        //pull the account info for that contact
        Contact SecContact4 = [SELECT FirstName, LastName, AccountId FROM Contact WHERE Id = :testC4.id];
        
        //verify that the insert updated by creating another contact as in the trigger
        System.assert(SecContact4.Id != null);
        System.assertNotEquals(SecContact4.FirstName, testC4.Sig_Other_First_Name__c);
        System.assertNotEquals(SecContact4.LastName, testC4.Sig_Other_Last_Name__c);
        System.assertNotEquals(SecContact4.AccountId, testC4.AccountId);
        
    }
}

 

Here's the error message I receive:

 

ClassSpouseTriggerTest
Method NameTest1_TestInsertContact
Pass/FailFail
Error MessageSystem.AssertException: Assertion Failed: Expected: null, Actual: John
Stack TraceClass.SpouseTriggerTest.Test1_TestInsertContact: line 16, column 1

 

I'm brand new to Apex and I'm working on my first trigger, pasted below. Through manual testing, I know that it works--however, i'm not quite sure how to create test code for it (my attempt is also pasted below). 

 

Any help would be appreciated, and thank you!

 

Trigger code:


trigger SpouseTrigger on Contact (before insert) {
    List<Contact> cons = new List<Contact>();
    List<Contact> consToInsert = new List<Contact>();
    
    for(Contact c:trigger.new){
        if(c.Sig_Other_First_Name__c != null && c.Sig_Other_Last_Name__c != null){
            cons.add(c);
        }
    }
    
    for(Contact c: cons){
        Contact newCon = new Contact();
        newCon.FirstName = c.Sig_Other_First_Name__c;
        newCon.LastName = c.Sig_Other_Last_Name__c;
        newCon.AccountId = c.AccountId;
        consToInsert.add(newCon);
    }
    
    insert consToInsert;
}

This trigger checks to see if two fields (Sig_Other_First_Name and Sig_Other_Last_Name) are filled in, and if they are, creates a new contact record. The contact record uses the First_Name as the First Name and the Last_Name as the last, and puts the contact within the same account as the original contact.

 

 My attempt at a test:

@istest
private class SpouseTriggerTest
{

static TestMethod void Test1_TestInsertContact()
{
Contact testC1 = new Contact(Text(80)='Test1 Contact', Sig_Other_First_Name__c='John', Sig_Other_Last_Name__c='Smith');
insert testC1;

//pull the account info for that contact
Contact SecContact = [SELECT cv__Contact__c FROM Account WHERE Id = :testc1.id];

//verify that the insert updated by creating another contact as in the trigger
System.assertEquals(testC1.account, SecContact.account);

}
}

I know this test is really awful but I don't even know where to start! So again, any help at all would be appreciated. Thank you!!

Hi

 

I have utilised the excellent demo from Jeff Douglas at http://blog.jeffdouglas.com/2010/07/13/building-a-dynamic-search-page-in-visualforce/ for building a custom dynamic search page in visual force. There is a great demo app there.

 

I have amended the code so that it works from my custom object. The page works fine, but I have an extra function that I would like but am not sure how to develop. 

 

In the search results on my VF page I want to be able to click on the name of each custom objects record so that it opens the record in the normal layout for the custom object. The custom object has a master detail relationship to Contacts and the field for this relationship has the link automatically displayed. Can anyone enlighten me as to the peice of code I need to allow the Name field to be clickable?

 

The code I have in the VF page for this field is:

 

 

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

 

 

Many thanks in advance

 

Justyn