• Cheyne
  • SMARTIE
  • 971 Points
  • Member since 2012


  • Chatter
    Feed
  • 31
    Best Answers
  • 4
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 182
    Replies
I'm using Decimal round up, but it seems it always give me the round-down integer but not the up-integer.

Decimal pages = this.processedNum/pageSize; 
          
this.totalpages = (Integer)pages.round(System.RoundingMode.CEILING);
processedNum = 56;
pageSize = 10;

The excepted totalpages should be 6, but it returns 5..

Any wrong with my code?

Thanks

hi i have a requirement where at the end of every month a field is set to 0 by itself.
I think about workflow but in worflow i have to create or edit a record then only workflow will fire.
So, please help.
Hi iam getting below error in production  when ever i click on the button on a related list on the case object that  to only one particular case.But in my developer sandbox  it is working fine .what may be the problem.Can anybody help on this.

 User-added image


And below is the code behind that button.

{!REQUIRESCRIPT("/support/console/26.0/integration.js")}
srcUp('/apex/PPS_CaseHolderPage?id={!Case.Id}&btname=New_Service_Order');



Regards,
Isha




This is my page..

<apex:page standardController="Employee__c" extensions="recordExt">
  <apex:form>
 
    <apex:pageBlock title="Employee Records">
    <apex:messages/>
   
    <apex:pageBlockButtons>
    <apex:commandButton value="Save" action="{!mySave}"/>
    <apex:commandButton value="Cancel"/>
    </apex:pageBlockButtons>
   
    <apex:pageBlockSection>
    <apex:pageBlockTable value="{!employee__c}" var="e" >
      <apex:column headerValue="Employee Name">
        <apex:inputField value="{!e.Name}"/>
      </apex:column>
     
      <apex:column headerValue="Last Name">
        <apex:inputField value="{!e.Last_Name__c}"/>
      </apex:column>
     
      <apex:column headerValue="Joining Date">
        <apex:inputField value="{!e.Join_Date__c}"/>
      </apex:column>
     
      <apex:column headerValue="City">
        <apex:inputField value="{!e.City__c}"/>
      </apex:column>
   
      <apex:column headerValue="Phone">
        <apex:inputField value="{!e.phone__c}"/>
      </apex:column>
   
      <apex:column>
        <apex:commandButton value="+" action="{!add}"/>
      </apex:column>
     
    </apex:pageBlockTable>
    </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>


and here is my controller.
public class recordExt {

    public Employee__c emp {get; set;}
    public List<Employee__c> empList {get; set;}
    public static Integer addCount {get; set;}
   
    public recordExt(ApexPages.StandardController controller) {
    this.emp = (Employee__c)Controller.getRecord();
    empList = new List<employee__c>();
    }
    
    public void add() {
       empList.add(new employee__c());
      //this.empList = new List<employee__c>();
     }
    
    public pageReference mySave() {
    try{
        insert emp;
        }
    catch(Exception ex){
            ApexPages.addmessages(ex);
        }
        return null;
   }
   
}
I have written the below trigger which creates a related record when a checkbox is updated. The problem is, it is creating a new record everytime the record is edited since the criteria is being met. Can anyone advise how I can edit my trigger so that it only fires once. (ie.The first time the criteria is met) ?

Trigger
Trigger copyEquipmentonsite on Unit_Placements_Sales__c(after insert, after update)
{
     List<Services__c> sub=new List<Services__c>();
     for(Unit_Placements_Sales__c u : Trigger.new)
     {
           if(u.Service_Month_is_Next_Month__c == TRUE)
           {
                   Services__c s=new Services__c();
                   
                   s.Equipment_Onsite__c=u.ID;
                   s.Equipment_Type__c=u.Equipment__c;
                   s.Machine_Specific_Notes__c=u.Machine_Specific_Notes__c;   
                   s.Product__c=u.The_Product__c;  
                   s.Dell_Tag_Number__c=u.Dell_Tag_Number__c;
                   s.Serial_Number__c=u.Serial_Number__c; 
                   s.XD_Number__c=u.XD_Number__c;
                   
                                                  
                   
                                    
                   sub.add(s);
            }
            if(sub.size()>0)
            insert sub;
     }
}

Thank you
Hi All ,

I have a custom object Opportunity_Attachment__c which has master-detail with Opportunity(master).

I have a button on the  opportunity attachment related list on the opportunity page,which creates an attachment .

Now i tried to modfy the code where i want to redirect after creating the attachment to another page where i add one more attachment

The redirect is working ,but the insert on the second page is giving an error as Iam not able to pass all the id's in the first page.
Please help me modify the code to pass the id's

when iam at the first page

browser has:
https://c.cs18.visual.force.com/apex/OpportunityAttachment1?retURL=%2F00611000003XbMi&CF00Nb0000003eDo6_lkid=00611000003XbMi&CF00Nb0000003eDo6=B%C4%81+Restaurant+%26+Lounge+-+2015+-+100.00+AED&sfdc.override=1&scontrolCaching=1

At the second page its just:
https://c.cs18.visual.force.com/apex/OpportunityAttachment2

So how do i pass all the parameters from first page to the second so that second page has:

https://c.cs18.visual.force.com/apex/OpportunityAttachment2?retURL=%2F00611000003XbMi&CF00Nb0000003eDo6_lkid=00611000003XbMi&CF00Nb0000003eDo6=B%C4%81+Restaurant+%26+Lounge+-+2015+-+100.00+AED&sfdc.override=1&scontrolCaching=1

Please find the controller codes below.

On the second page iam getting an insert error as id's are not passed.

Please help.
************************

public with sharing class OpportunityAttachmentController1{
  
    public Opportunity_Attachment__c objOppAtt {get; set;}
    public OpportunityAttachmentController1(ApexPages.StandardController controller) {
        attach = new Attachment();
        objOppAtt = (Opportunity_Attachment__c)controller.getRecord();
    }

    public Attachment attach {get;set;}
 
    //When user clicks upload button on Visualforce Page, perform upload/insert
    public ApexPages.Pagereference save(){
        if(attach.body==null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please select a file to upload'));
            return null;
        }
        insert objOppAtt;
      
        attach.ParentId = objOppAtt.id;
        insert attach;
      
        objOppAtt.URL__c = URL.getSalesforceBaseUrl().toExternalForm()+'/servlet/servlet.FileDownload?file='+attach.id;
        objOppAtt.name = attach.Name;
        update objOppAtt;
        //return new PageReference('/'+objOppAtt.Opportunity__c); 
    PageReference congratsPage = Page.OpportunityAttachment2;


//Opportunityattachment2 controller is OpportunityAttachmentController2,its just exactle the same page to add one more attachment
//how to pass all id's here to OpportunityAttachmentController2

  congratsPage.setRedirect(true);

  return congratsPage;






    }
}

*************************************

public with sharing class OpportunityAttachmentController2{
  
    public Opportunity_Attachment__c objOppAtt {get; set;}
    public OpportunityAttachmentController2(ApexPages.StandardController controller) {
        attach = new Attachment();
        objOppAtt = (Opportunity_Attachment__c)controller.getRecord();
    }

    public Attachment attach {get;set;}
 
    //When user clicks upload button on Visualforce Page, perform upload/insert
    public ApexPages.Pagereference save(){
        if(attach.body==null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please select a file to upload'));
            return null;
        }
        insert objOppAtt;
      
        attach.ParentId = objOppAtt.id;
        insert attach;
      
        objOppAtt.URL__c = URL.getSalesforceBaseUrl().toExternalForm()+'/servlet/servlet.FileDownload?file='+attach.id;
        objOppAtt.name = attach.Name;
        update objOppAtt;
        return new PageReference('/'+objOppAtt.Opportunity__c); 
  




    }
}


******************************
Hi, I need to do a workflow (or validation rule I'm not sure which one to use) and it should do this "Setup status can be saved as "Cancelled" only if prior value has been "In delivery".
But when I do it like this the first Error goes : Extra " , " then when I take it off it says "Extra Pickval" 

AND(ISCHANGED(Setup_Status__c), "Cancelled"),
ISPICKVAL(PRIORVALUE(Setup_Status__c), "In Delivery"))

What would be a better solution for this?
Hi Team,

We have Notes & Attachments related lists to Opportunity. And i have Date__c field on Opportunity.

I want to update Date__c field on Opportunity with recently note created date.


Please let me know if you have any suggestions.

Thanks,
Anil
Hi there,

I was wondering if it were possible to create a visualforce email template based on a specific record. 

I will explain my situation.

I have account and transactions__c is a custom object which is a child or Account. I was wondering if it is possible to create an email template which basically shows all the fields related to the transaction. Then I could either write a trigger which will send said email template whenever a transaction record is created or use my current email trigger to reference a specific record and then send out an email with the transaction information.

Thank you for your time
Hi all .

I've used <apex:repeat> and following structure is iterated :
Please provide the the model of printer field and Please specify field

In below image when i select Other for 'Please provide the model of printer' only i should display please specific Text box.
But  since this block created dynamically i can not use javascript. How can i handle this situation??

note that i've used  pageblocksection between please specific Text box.


This image is not available because: You don’t have the privileges to see it, or it has been removed from the system


Please help me.


This is a sample. When I click 'hide it', it supposed to hide the text, but nothing happened. Could some one help?

/***************Page**********************/

<apex:page sidebar="false" showChat="false" showHeader="false" controller="TestRenderCtrl">
    <apex:form >
        <apex:outputPanel id="panel1"  rendered="{!isRendered}">
            Panel: it is used for testing render.
        </apex:outputPanel>
        <apex:outputPanel >
            <apex:commandButton value="hide it" action="{!hidePanel}" reRender="panel1" />  
            <apex:commandButton value="show it" action="{!showPanel}" reRender="panel1" />
        </apex:outputPanel>
    </apex:form> 
</apex:page>

/***************Controller*****************/

public class TestRenderCtrl{
  
    public Boolean isRendered {get; set;}
      
    public TestRenderCtrl(){
        isRendered = true;
    }
  
    public PageReference hidePanel(){
        isRendered = false;
        return null;
    }
  
    public PageReference showPanel(){
        isRendered = true;
        return null;
    }
}
Can anyone please look into this and help to find the error?  code works perfectly fine when i validate only one profile ID in the 'IF' condition when add other 2 profile ID's its not respecting the conditions and leting all actions entering to into the IF.


{!REQUIRESCRIPT('/soap/ajax/28.0/connection.js')}

var sr = new sforce.SObject("Contract");

sr.Status = "{!Contract.Status}";
var initial = sr.Status;
if ( '{!$User.ProfileId}'!='00e30000000bqt9'|| '{!$User.ProfileId}' !='00e80000001BvTe'||'{!$User.ProfileId}' != '00eA0000000MKTH')
{
alert('{!$User.ProfileId}');
alert('You are not authorized to cancel the agreement ...........');
window.parent.location.href=window.parent.location.href;
}
else
{
if(initial=='Draft'||initial=='Executed')
{
var sr = new sforce.SObject("Contract");
sr.id = "{!Contract.Id}";
sr.Status = 'Cancelled';
result = sforce.connection.update([sr]);
window.location.reload();
}
else
{
alert("You cannot cancel expired agreements.");
}
}
I would like to remove primary campaign source from the contact and opportunity on lead conversion unless the lead had Responded to the campaign.  

I tried this trigger, but it doenst work, and i cant figure out why

trigger checkPrimaryCampaignSource on Opportunity (before update) {
for (Opportunity o: Trigger.new) {
Lead l = [SELECT id,converteddate FROM Lead WHERE ConvertedOpportunityId =:o.ID LIMIT 1];
try {
if(l.converteddate!=null){
CampaignMember cm = [Select id,Status, HasResponded FROM campaignmember WHERE LeadId=:l.id AND CampaignId=:o.Campaign.id];
if (cm.HasResponded ==false){
o.CampaignId=null;
}
}
} catch (Exception e){
system.debug('error: ' +e);
}
}



}
Hi i'm trying to write this validation and seems i cannot get syntax properly:

If Email.Package or Fax.Package = today , Salutation cannot be blank

can someone please help me?

thx in advance :)

  • April 09, 2014
  • Like
  • 0
Hello Everyone,
I am an APEX newbie trying to create a trigger that posts when an Opp is won. I have no other requirements besides that the when an Opportunity is updated to the won stage, it posts a pedesigned message to a specific Chatter Group. I took the code from another post (https://developer.salesforce.com/forums/ForumsMain?id=906F00000009AFJIA2) and tried to modify it to do just that but I am running into a problem in the IDE at the "for" line, with the error stating "Save error: Loop must iterate over collection type: Boolen". I tried to add an else statement to break and exit the loop but that gave me a bracket error. Am I totally off base here? Should I pulling a list first for the function to iterate over? Any help would be much appreciated! Thanks!

trigger ChatterPostWonOpp on Opportunity (after update) {

String status;
String OppAccName;
String OppOwnerName;

FeedItem post = new FeedItem();
  
    for(Opportunity o : Trigger.isupdate) {
                if(o.IsWon == true ) //This will be executed on new record insertion when Opp is won
                    for (Opportunity oppty : [SELECT Account.Name, Owner.Name FROM Opportunity])
                     {
                        OppAccName = oppty.Account.Name;
                        OppOwnerName = oppty.Owner.Name;
                      }  
                
                    status = OppOwnerName + ' just won ' + OppAccName + ' for ' + o.Amount + '!';

                    post.ParentId = '0F9g00000008b7c';
                    post.Title = o.Name;
                    post.Body = status;
                  
                    insert post;
          }
    }
Hi

  There are 3 Objects Asset, Contracts and Contract_Line_C 

Contract_Line_C is associated to ( Asset and Contracts) Below is a trigger I am writing to Update If Asset AccountId is update all its associated Contracts and its associted Assets AccountId must be updated. 

trigger Asset_Account_Update on Asset (After Update)
{

/* Set<Asset> Ast = New Set<Asset>([SELECT AccountId FROM Asset WHERE Id in :trigger.newmap.keyset() limit 1]);
System.Debug('Asset AccountId = ' + Ast); */

Asset A;
A = [SELECT AccountId FROM Asset WHERE Id in :trigger.newmap.keyset() limit 1 ];
System.Debug('Asset AccountId = ' + A.AccountId);

List<Contract_Lines__c> CL = [SELECT Contract__c FROM Contract_Lines__c WHERE Asset__c  = :A.AccountId ];

List<Contract> Cont = [SELECT Id,AccountId FROM Contract
                       WHERE Id in (SELECT Contract__c FROM Contract_Lines__c WHERE Asset__c  = :A.AccountId) ];

for( Contract UpdCont : Cont)
{
UpdCont.AccountId = A.AccountId;
Update UpdCont;  
}

/ *  This Part is not working need advise how to change.  */
List<Contract_Lines__c> CL2 = [SELECT Asset__c FROM Contract_Lines__c WHERE Contract__c in :Cont.Id ];

List<Asset> A2 = [SELECT Id,AccountId FROM Asset WHERE Asset__c in :CL2.Asset__c];

   for ( Asset Ast : A2)
    {
      Ast.AccountId = :AccountIDSet;
     }
     Update Ast;

}


I get unexpected token error. Please suggest me how to pass values from one list of SOQL to another and make update

Thanks
Sudhir
Hello All,

I have one sample list to retreive contact information and data is below.
list<contact> lstcont = [select id,name,accountid,sequence__c from contact where accountid=:accids ];

sample data when I execute the list from developer console:

Contact{Name=a01i000000D6EeW, Account__c=acc1, Id=a01i000000D6EeWAAV, Sequence_Number__c=1},
Contact{Name=a01i000000D6EeX, Account__c=acc2, Id=a01i000000D6EeXAAV, Sequence_Number__c=1},
Contact:{Name=testaccount, Account__c=acc1, Id=a01i000000D6EeaAAF, Sequence_Number__c=2})

I want to modify the list order by Account wise, for example

Contact{Name=a01i000000D6EeW, Account__c=acc1, Id=a01i000000D6EeWAAV, Sequence_Number__c=1},
Contact{Name=a01i000000D6EeX, Account__c=acc1, Id=a01i000000D6EeXAAV, Sequence_Number__c=2},
Contact:{Name=testaccount, Account__c=acc2, Id=a01i000000D6EeaAAF, Sequence_Number__c=1})

Please share the ideas how to change the list order as required.

Thanks,
Krishna
Hey there,

I have a roll up tool that I found on the internet called LREngine, created by someone named: abhinavguptas. The trigger is amazing and is the most reliable trigger for rolling up values through a lookup I have come across, especially when you are rolling up more than one field. However, this trigger has two bugs. One is that it doesn't like to accept filtering methods and the other is that...should the rolluped records be deleted one by one, the value will deduct each records number worth, until the last record where it will keep the last figure in the rollup field.

E.G. Parent: Rolled up field = 6, child fields = 2 per record. Deleted one by one and when all child records are deleted, rolled up field will still equal 2.

Thank you for any help in advance. Below I will post the Class and the standard trigger with the bits I have changed or added as bold:

Class:

/*
Copyright (c) 2012 tgerm.com
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
    LREngine("L"ookup "R"ollup Engine) : This class simplifies rolling up on the child records in lookup relationship.
*/
public class LREngine {

    /*
        Tempalte tokens
            0 : Fields to project
            1 : Object to query
            2 : Optional WHERE clause filter to add
            3 : Group By field name
    */
    static String SOQL_TEMPLATE = 'SELECT {0} FROM {1} {2} GROUP BY {3}';

    /**
        Key driver method that rolls up lookup fields based on the context. This is specially useful in Trigger context.

        @param ctx Context the complete context required to rollup
        @param detailRecordsFromTrigger child/detail records which are modified/created/deleted during the Trigger
        @returns Array of in memory master objects. These objects are not updated back to the database
                because we want client or calling code to have this freedom to do some post processing and update when required.
    */
    public static Sobject[] rollUp(Context ctx, Sobject[] detailRecordsFromTrigger) {

        // API name of the lookup field on detail sobject
        String lookUpFieldName = ctx.lookupField.getName();

        Set<Id> masterRecordIds = new Set<Id>();
        for (Sobject kid : detailRecordsFromTrigger) {
            masterRecordIds.add((Id)kid.get(lookUpFieldName));
        }
        return rollUp(ctx, masterRecordIds);
    }

    /**
        Key driver method that rolls up lookup fields based on the context. This is meant to be called from non trigger contexts like
        scheduled/batch apex, where we want to rollup on some master record ids.

        @param Context the complete context required to rollup
        @param masterIds Master record IDs whose child records should be rolled up.
        @returns Array of in memory master objects. These objects are not updated back to the database
                because we want client or calling code to have this freedom to do some post processing and update when required.
    */
    public static Sobject[] rollUp(Context ctx,  Set<Id> masterIds) {
        // K: Id of master record
        // V: Empty sobject with ID field, this will be used for updating the masters
        Map<Id, Sobject> masterRecordsMap = new Map<Id, Sobject>();
        for (Id mId : masterIds) {
            masterRecordsMap.put(mId, ctx.master.newSobject(mId));
        }

        // #0 token : SOQL projection
        String soqlProjection = ctx.lookupField.getName();
        // k: detail field name, v: master field name
        Map<String, String> detail2MasterFldMap = new Map<String, String>();
        // k: detail field name, v: detail field small alias
        Map<String, String> detailFld2AliasMap = new Map<String, String>();
        Integer aliasCounter = 1;
        for (RollupSummaryField rsf : ctx.fieldsToRoll) {
            /* Keeping alias short i.e. d1, d2...dn to allow more chars in SOQL to avoid SOQL char limit.
                It also helps in avoiding this exception when field names are more than 25 chars i.e.
                System.QueryException: alias is too long, maximum of 25 characters: Annualized_Recurring_Revenue__c
               
                A Sample query with new alias format will look like following
                SELECT AccountId, Avg(Amount) d1, Count(CloseDate) d2 FROM Opportunity  GROUP BY AccountId
            */
            String aliasName = 'd' + aliasCounter++;
            // create aggreate projection with alias for easy fetching via AggregateResult class
            // i.e. SUM(Amount) Amount
            soqlProjection += ', ' + rsf.operation + '(' + rsf.detail.getName() + ') ' + aliasName;
            detail2MasterFldMap.put(rsf.detail.getName(), rsf.master.getName());
            // store the alias for the detail field name, it will be used for loading up later
            detailFld2AliasMap.put(rsf.detail.getName(), aliasName);
        }

        // #1 token for SOQL_TEMPLATE
        String detailTblName = ctx.detail.getDescribe().getName();
       
        // #2 Where clause
        String whereClause = '';
        if (ctx.detailWhereClause != null && ctx.detailWhereClause.trim().length() > 0) {
            whereClause = 'WHERE ' + ctx.detailWhereClause ;
        }
       
        // #3 Group by field
        String grpByFld = ctx.lookupField.getName();
       
        String soql = String.format(SOQL_TEMPLATE, new String[]{soqlProjection, detailTblName, whereClause, grpByFld});
       
        // aggregated results
        List<AggregateResult> results = Database.query(soql);
       
        for (AggregateResult res : results){
            Id masterRecId = (Id)res.get(grpByFld);
            Sobject masterObj = masterRecordsMap.get(masterRecId);
            if (masterObj == null) {
                System.debug(Logginglevel.WARN, 'No master record found for ID :' + masterRecId);
                continue;
            }

            for (String detailFld : detail2MasterFldMap.keySet()) {
                // Load the alias name to fetch the value from the aggregated result
                String aliasName = detailFld2AliasMap.get(detailFld);
                Object aggregatedDetailVal = res.get(aliasName);
                masterObj.put(detail2MasterFldMap.get(detailFld), aggregatedDetailVal);
            }          
        }
       
        return masterRecordsMap.values();  
    }




    /**
        Exception throwed if Rollup Summary field is in bad state
    */
    public class BadRollUpSummaryStateException extends Exception {}

   /**
       Which rollup operation you want to perform
    */
    public enum RollupOperation {
        Sum, Max, Min, Avg, Count
    }
   
    /**
        Represents a "Single" roll up field, it contains
        - Master field where the rolled up info will be saved
        - Detail field that will be rolled up via any operation i.e. sum, avg etc
        - Operation to perform i.e. sum, avg, count etc
           
    */
    public class RollupSummaryField {
        public Schema.Describefieldresult master;
        public Schema.Describefieldresult detail;
        public RollupOperation operation;
       
        // derived fields, kept like this to save script lines later, by saving the same
        // computations over and over again
        public boolean isMasterTypeNumber;
        public boolean isDetailTypeNumber;
        public boolean isMasterTypeDateOrTime;
        public boolean isDetailTypeDateOrTime;
       
        public RollupSummaryField(Schema.Describefieldresult m,
                                         Schema.Describefieldresult d, RollupOperation op) {
            this.master = m;
            this.detail = d;
            this.operation = op;
            // caching these derived attrbutes for once
            // as their is no view state involved here
            // and this caching will lead to saving in script lines later on
            this.isMasterTypeNumber = isNumber(master.getType());
            this.isDetailTypeNumber = isNumber(detail.getType());
            this.isMasterTypeDateOrTime = isDateOrTime(master.getType());
            this.isDetailTypeDateOrTime = isDateOrTime(detail.getType());
            // validate if field is good to work on later
            validate();
        }  
       
        void validate() {
            if (master == null || detail == null || operation == null)
                throw new BadRollUpSummaryStateException('All of Master/Detail Describefieldresult and RollupOperation info is mandantory');

            if ( (!isMasterTypeDateOrTime && !isMasterTypeNumber)
                  || (!isDetailTypeDateOrTime && !isDetailTypeNumber)) {
                    throw new BadRollUpSummaryStateException('Only Date/DateTime/Time/Numeric fields are allowed');
            }
           
            if (isMasterTypeDateOrTime && (RollupOperation.Sum == operation || RollupOperation.Avg == operation)) {
                throw new BadRollUpSummaryStateException('Sum/Avg doesnt looks like valid for dates ! Still want, then implement the IRollerCoaster yourself and change this class as required.');
            }
        }
       
        boolean isNumber (Schema.Displaytype dt) {
            return dt == Schema.Displaytype.Currency
                   || dt == Schema.Displaytype.Integer
                   || dt == Schema.Displaytype.Percent
                   || dt == Schema.Displaytype.Double;
        }
       
        boolean isDateOrTime(Schema.DisplayType dt) {
            return dt == Schema.Displaytype.Time
                   || dt == Schema.Displaytype.Date
                   || dt == Schema.Displaytype.Datetime;
        }
    }
   
    /**
        Context having all the information about the rollup to be done.
        Please note : This class encapsulates many rollup summary fields with different operations.
    */
    public class Context {
        // Master Sobject Type
        public Schema.Sobjecttype master;
        // Child/Details Sobject Type
        public Schema.Sobjecttype detail;
        // Lookup field on Child/Detail Sobject
        public Schema.Describefieldresult lookupField;
        // various fields to rollup on
        public List<RollupSummaryField> fieldsToRoll;

        // Where clause or filters to apply while aggregating detail records
        public String detailWhereClause;           

        public Context(Schema.Sobjecttype m, Schema.Sobjecttype d,
                           Schema.Describefieldresult lf) {
            this(m, d, lf, '');                            
        }
       
        public Context(Schema.Sobjecttype m, Schema.Sobjecttype d,
                           Schema.Describefieldresult lf, String detailWhereClause) {
            this.master = m;
            this.detail = d;
            this.lookupField = lf;
            this.detailWhereClause = detailWhereClause;
            this.fieldsToRoll = new List<RollupSummaryField>();
        }

        /**
            Adds new rollup summary fields to the context
        */
        public void add(RollupSummaryField fld) {
            this.fieldsToRoll.add(fld);
        }
    }   
}

Trigger:

trigger OffInvRollup on Office_Invoice__c (after insert, after update,
                                        after delete, after undelete) {



   // modified objects whose parent records should be updated
     Office_Invoice__c[] objects = null;  

     if (Trigger.isDelete) {
         objects = Trigger.old;
     } else {
        /*
            Handle any filtering required, specially on Trigger.isUpdate event. If the rolled up fields
            are not changed, then please make sure you skip the rollup operation.
            We are not adding that for sake of similicity of this illustration.
        */
        objects = Trigger.new;
     }
    

         List<Office_Invoice__c > objects1 = new List<Office_Invoice__c >();
    for(Office_Invoice__c m : objects)
        if(m.Payment_Method__c == 'Commission Deduction')
            objects1.add(m);

    
    

     /*
      First step is to create a context for LREngine, by specifying parent and child objects and
      lookup relationship field name
     */
     LREngine.Context ctx = new LREngine.Context(Office_Commission__c.SobjectType, // parent object
                                            Office_Invoice__c.SobjectType,  // child object
                                            Schema.SObjectType.Office_Invoice__c.fields.Office_Commission__c);    
     /*
      Next, one can add multiple rollup fields on the above relationship.
      Here specify
       1. The field to aggregate in child object
       2. The field to which aggregated value will be saved in master/parent object
       3. The aggregate operation to be done i.e. SUM, AVG, COUNT, MIN/MAX
     */

     ctx.add(
            new LREngine.RollupSummaryField(
                                            Schema.SObjectType.Office_Commission__c.fields.Office_Invoice_Amount_Total__c,
                                            Schema.SObjectType.Office_Invoice__c.fields.Office_Invoice_Amount__c,
                                            LREngine.RollupOperation.Sum
                                         ));
                                        
                                 ctx.add(
            new LREngine.RollupSummaryField(
                                            Schema.SObjectType.Office_Commission__c.fields.Office_Invoice_GST_Amount_Total__c,
                                            Schema.SObjectType.Office_Invoice__c.fields.Office_Invoice_GST_Amount__c,
                                            LREngine.RollupOperation.Sum
                                         ));
                                        
          
     /*
      Calling rollup method returns in memory master objects with aggregated values in them.
      Please note these master records are not persisted back, so that client gets a chance
      to post process them after rollup
      */
     Sobject[] masters = LREngine.rollUp(ctx, objects1);   

     // Persiste the changes in master
   try{     update masters;
   } catch(DmlException e) {
                for(integer i=0;i<e.getNumDml();i++) {
                    System.debug(e.getDmlMessage(i));
                }
                }
}

Thank you for your help
Hi all
I am new to salesforce i just want to write atest class on the trigger  below is the code please help me .... urgent 


Thanks in Advance




trigger Updatactcontact on Opportunity (after update) {

    Set<Id> accountidset=new Set<Id>(); 
    Map<Id,Account> mapaccount=new Map<Id,Account>();
    Map<Id,List<Contact>> mapcontacts=new Map<Id,List<Contact>>();
    List<Contact> lstcontact=new List<Contact>();

   for(Opportunity oppobj:trigger.new){
      

if(trigger.newmap.get(oppobj.id).stagename!=trigger.oldmap.get(oppobj.id).stageName)

{
           if(oppobj.accountid!=null){
               accountidset.add(oppobj.accountid);
           }             
       }  
   }
   if(accountidset!=null && accountidset.size()>0){
       for(Account actobj:[select id,name,description,(select

id,name,OpportunityUpdate__c from Contacts) from Account where id in:accountidset]){
           mapaccount.put(actobj.id,actobj);
           mapcontacts.put(actobj.id,actobj.contacts);     
       }  
   }
   for(Opportunity oppobj:trigger.new){
      

if(trigger.newmap.get(oppobj.id).stagename!=trigger.oldmap.get(oppobj.id).stageName)
{
              if(oppobj.AccountiD!=null)
              {
mapaccount.get(oppobj.AccountId).Description='Opportunity :'+oppobj.Name+'stagename changed from'+trigger.oldmap.get(oppobj.id).stageName+'to '+ trigger.newmap.get(oppobj.id).stageName;
                   for(Contact cont:mapcontacts.get(oppobj.AccountId)){
                      Contact contobj=new

Contact(id=Cont.id,OpportunityUpdate__c='Opportunity :'+oppobj.Name+' stagename changed from '+trigger.oldmap.get(oppobj.id).stageName+' to '+

trigger.newmap.get(oppobj.id).stageName);
                      lstcontact.add(contobj);
                  }           
              }
       }  
   }
  
   if(lstcontact!=null && lstcontact.size()>0)

           update lstcontact;
          
   if(mapaccount!=null && mapaccount.size()>0)
           update mapaccount.values();
}

  • January 24, 2014
  • Like
  • 0

Hi Everyone,

 

On the object ,there is a picklist ,whenever the field is edited/ changed ,i need to update the datetime field on the same object.

 

Can you please let me who to do ?

by using workflow trigger.

 

Regards

Sailer.

 

 

 

  • November 11, 2013
  • Like
  • 0
I have a Visualforce that includes two Account fields, which have a field dependency defined. The controlling field is a single-select picklist and the dependent field is a multi-select picklist. When both fields are displayed on page load, they both display correctly, with the correct values that are in the Account record. However, when I display the dependent (multi-select) field in an outputpanel that is only rendered via an ajax event, after clicking a commandlink, the value in the dependent field shows as null, even though it is not actually null on the record.

Below is a simplified example. In this example, all of the outputfields display the value that is on the account. However, the inputField for Dependent_Field__c in the "bottom-area" outputpanel always shows null after clicking the "Set String" commandlink (the Controlling_Field__c input in the "bottom-area" panel displays the correct value after the rerender).

Has anyone run across this issue before or have any ideas as to what the problem might be?

Visualforce
<apex:page controller="MultiSelectController">
    <apex:form >
        <apex:commandLink action="{!setStr}" rerender="bottom-area" value="Set String"/>
        
        <br/><br/>
        
        <apex:outputField value="{!acct.Controlling_Field__c}"/><br/>
        <apex:outputField value="{!acct.Dependent_Field__c}" /><br/>
        <apex:inputField value="{!acct.Controlling_Field__c}" label="Controlling Field"/><br/>
        <apex:inPutField value="{!acct.Dependent_Field__c}" label="Dependent Field"/> <br/>
        
        <br/><br/>
        
        <apex:outputPanel id="bottom-area">
            <apex:outputPanel rendered="{!str != null}">
                <apex:outputField value="{!acct.Controlling_Field__c}" /><br/>
                <apex:outputField value="{!acct.Dependent_Field__c}" /><br/>
                <apex:inputField value="{!acct.Controlling_Field__c}" label="Controlling Field"/><br/>
                <apex:inPutField value="{!acct.Dependent_Field__c}" label="Dependent Field"/> <br/>
            </apex:outputPanel>
        </apex:outputPanel>
    </apex:form>
</apex:page>

Apex Controller
public class MultiSelectController {
    public Account acct {get; set;}
    public String str {get; set;}
    
    public MultiSelectController() {
        this.acct = [SELECT Controlling_Field__c, Dependent_Field__c FROM Account WHERE Id = '001E0000010iUnj'];
    }
    
    public void setStr() {
        this.str = 'test';
    }
}

 
  • November 05, 2014
  • Like
  • 0
I'm trying to run a location based SOQL query from javascript, using the AJAX toolkit, and I'm getting an error telling me that the location field is not defined. I have geolocation field, called Location__c, defined on the Contact. Here is my code:

<apex:page >
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="../soap/ajax/25.0/connection.js" ></script>
    <script type="text/javascript">
        $(document).ready(function() {
            sforce.connection.sessionId = '{!$Api.Session_ID}';
            var query = "SELECT Id FROM Contact WHERE DISTANCE(Location__c, GEOLOCATION(42.0, -76.0), 'mi') < 10";
            console.log(query);
            var res = sforce.connection.query(query);
            console.log(res);
        });
    </script>
</apex:page>

The post request is returning a 500 error, with the message, "No such column 'Location__c' on entity 'Contact'." However, there is a field called Location__c; furthermore, this query works just fine from the Developer Console. Can anyone see what might be going on here?
  • August 20, 2014
  • Like
  • 1
I have a Force.com site set up, which will be used by un-authenticated users. My site automatically has two domians associated with it

http://mydomain.force.com
https://mydomain.secure.force.com

Since users will be making purchases (using a credit card) through this site, I would like to force them to use the secure version. The URL Redirect settings on the site don't allow me to do redirects at the domain level, however, and the documentation that I have found regarding forcing HTTPS refers to users who are logged in. 

Is there a way to redirect un-authenticated users to https://mydomain.secure.force.com when they attempt to access http://mydomain.force.com?
  • February 27, 2014
  • Like
  • 3
I'm trying to run a location based SOQL query from javascript, using the AJAX toolkit, and I'm getting an error telling me that the location field is not defined. I have geolocation field, called Location__c, defined on the Contact. Here is my code:

<apex:page >
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="../soap/ajax/25.0/connection.js" ></script>
    <script type="text/javascript">
        $(document).ready(function() {
            sforce.connection.sessionId = '{!$Api.Session_ID}';
            var query = "SELECT Id FROM Contact WHERE DISTANCE(Location__c, GEOLOCATION(42.0, -76.0), 'mi') < 10";
            console.log(query);
            var res = sforce.connection.query(query);
            console.log(res);
        });
    </script>
</apex:page>

The post request is returning a 500 error, with the message, "No such column 'Location__c' on entity 'Contact'." However, there is a field called Location__c; furthermore, this query works just fine from the Developer Console. Can anyone see what might be going on here?
  • August 20, 2014
  • Like
  • 1
I have a Force.com site set up, which will be used by un-authenticated users. My site automatically has two domians associated with it

http://mydomain.force.com
https://mydomain.secure.force.com

Since users will be making purchases (using a credit card) through this site, I would like to force them to use the secure version. The URL Redirect settings on the site don't allow me to do redirects at the domain level, however, and the documentation that I have found regarding forcing HTTPS refers to users who are logged in. 

Is there a way to redirect un-authenticated users to https://mydomain.secure.force.com when they attempt to access http://mydomain.force.com?
  • February 27, 2014
  • Like
  • 3
 if (!Name.equals(''))
      soql +=  ' and firstname LIKE \'String.escapeSingleQuotes(Name)'+'%\'';
    if (!Department.equals(''))
      soql += ' and Department LIKE \'String.escapeSingleQuotes(Department)'+'%\'';  
    if (!Leadsource.equals(''))
     soql += 'and Leadsource includes (''+Leadsource+'')';
               /***************Error in this line********************/

 
I have a Visualforce that includes two Account fields, which have a field dependency defined. The controlling field is a single-select picklist and the dependent field is a multi-select picklist. When both fields are displayed on page load, they both display correctly, with the correct values that are in the Account record. However, when I display the dependent (multi-select) field in an outputpanel that is only rendered via an ajax event, after clicking a commandlink, the value in the dependent field shows as null, even though it is not actually null on the record.

Below is a simplified example. In this example, all of the outputfields display the value that is on the account. However, the inputField for Dependent_Field__c in the "bottom-area" outputpanel always shows null after clicking the "Set String" commandlink (the Controlling_Field__c input in the "bottom-area" panel displays the correct value after the rerender).

Has anyone run across this issue before or have any ideas as to what the problem might be?

Visualforce
<apex:page controller="MultiSelectController">
    <apex:form >
        <apex:commandLink action="{!setStr}" rerender="bottom-area" value="Set String"/>
        
        <br/><br/>
        
        <apex:outputField value="{!acct.Controlling_Field__c}"/><br/>
        <apex:outputField value="{!acct.Dependent_Field__c}" /><br/>
        <apex:inputField value="{!acct.Controlling_Field__c}" label="Controlling Field"/><br/>
        <apex:inPutField value="{!acct.Dependent_Field__c}" label="Dependent Field"/> <br/>
        
        <br/><br/>
        
        <apex:outputPanel id="bottom-area">
            <apex:outputPanel rendered="{!str != null}">
                <apex:outputField value="{!acct.Controlling_Field__c}" /><br/>
                <apex:outputField value="{!acct.Dependent_Field__c}" /><br/>
                <apex:inputField value="{!acct.Controlling_Field__c}" label="Controlling Field"/><br/>
                <apex:inPutField value="{!acct.Dependent_Field__c}" label="Dependent Field"/> <br/>
            </apex:outputPanel>
        </apex:outputPanel>
    </apex:form>
</apex:page>

Apex Controller
public class MultiSelectController {
    public Account acct {get; set;}
    public String str {get; set;}
    
    public MultiSelectController() {
        this.acct = [SELECT Controlling_Field__c, Dependent_Field__c FROM Account WHERE Id = '001E0000010iUnj'];
    }
    
    public void setStr() {
        this.str = 'test';
    }
}

 
  • November 05, 2014
  • Like
  • 0
hello all,

i am working on a visualforce page and i want to replace the dot in decimal with comma can and one help me please .

<apex:column headerValue="Preço de lista">
<apex:outputText value="{!oliWrapper.price}" id="unitPrice"/>
</apex:column>

Thanks in Advance

 
I'm using Decimal round up, but it seems it always give me the round-down integer but not the up-integer.

Decimal pages = this.processedNum/pageSize; 
          
this.totalpages = (Integer)pages.round(System.RoundingMode.CEILING);
processedNum = 56;
pageSize = 10;

The excepted totalpages should be 6, but it returns 5..

Any wrong with my code?

Thanks

Hi everyone,
   There is a custom field of type 'checkbox' called "Primary" in Contact object. If this Primary is checked, then the value of the contact's Email field has to be updated in the custom email field named "PrimaryContactEmail"  in the Account Standard object. How can this be done in Trigger. Please do suggest a solution
hi i have a requirement where at the end of every month a field is set to 0 by itself.
I think about workflow but in worflow i have to create or edit a record then only workflow will fire.
So, please help.
Hi iam getting below error in production  when ever i click on the button on a related list on the case object that  to only one particular case.But in my developer sandbox  it is working fine .what may be the problem.Can anybody help on this.

 User-added image


And below is the code behind that button.

{!REQUIRESCRIPT("/support/console/26.0/integration.js")}
srcUp('/apex/PPS_CaseHolderPage?id={!Case.Id}&btname=New_Service_Order');



Regards,
Isha




<html>
<head>
<script type="text/javascript">
<!--
function getConfirmation(){
   var retVal = confirm("Do you want to continue ?");
   if( retVal == true ){
      alert("User wants to continue!");
   return true;
   }else{
      alert("User does not want to continue!");
   return false;
   }
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>

Outputbox:OK and cancel button but i want yes ,no Button label

Plz guide me 
'I m new in jquery...........................

Thank you 
Radhika pawar
This is my page..

<apex:page standardController="Employee__c" extensions="recordExt">
  <apex:form>
 
    <apex:pageBlock title="Employee Records">
    <apex:messages/>
   
    <apex:pageBlockButtons>
    <apex:commandButton value="Save" action="{!mySave}"/>
    <apex:commandButton value="Cancel"/>
    </apex:pageBlockButtons>
   
    <apex:pageBlockSection>
    <apex:pageBlockTable value="{!employee__c}" var="e" >
      <apex:column headerValue="Employee Name">
        <apex:inputField value="{!e.Name}"/>
      </apex:column>
     
      <apex:column headerValue="Last Name">
        <apex:inputField value="{!e.Last_Name__c}"/>
      </apex:column>
     
      <apex:column headerValue="Joining Date">
        <apex:inputField value="{!e.Join_Date__c}"/>
      </apex:column>
     
      <apex:column headerValue="City">
        <apex:inputField value="{!e.City__c}"/>
      </apex:column>
   
      <apex:column headerValue="Phone">
        <apex:inputField value="{!e.phone__c}"/>
      </apex:column>
   
      <apex:column>
        <apex:commandButton value="+" action="{!add}"/>
      </apex:column>
     
    </apex:pageBlockTable>
    </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>


and here is my controller.
public class recordExt {

    public Employee__c emp {get; set;}
    public List<Employee__c> empList {get; set;}
    public static Integer addCount {get; set;}
   
    public recordExt(ApexPages.StandardController controller) {
    this.emp = (Employee__c)Controller.getRecord();
    empList = new List<employee__c>();
    }
    
    public void add() {
       empList.add(new employee__c());
      //this.empList = new List<employee__c>();
     }
    
    public pageReference mySave() {
    try{
        insert emp;
        }
    catch(Exception ex){
            ApexPages.addmessages(ex);
        }
        return null;
   }
   
}
Hi All,

Am uploading CSV file that contain around 4 MB ,but am not to upload into salesforce its showing me error " System.LimitException: Regex too complicated "

I read in Salesforce limitation pdf its saying we can upload upto 10 MB,but my file is failing does any one what is the reason ?
Can any one tell me how can i rectify with out going batch apex class,
how the salesforce will calculate Heapsize ?


Reagrds,
Venkatesh.
I have written the below trigger which creates a related record when a checkbox is updated. The problem is, it is creating a new record everytime the record is edited since the criteria is being met. Can anyone advise how I can edit my trigger so that it only fires once. (ie.The first time the criteria is met) ?

Trigger
Trigger copyEquipmentonsite on Unit_Placements_Sales__c(after insert, after update)
{
     List<Services__c> sub=new List<Services__c>();
     for(Unit_Placements_Sales__c u : Trigger.new)
     {
           if(u.Service_Month_is_Next_Month__c == TRUE)
           {
                   Services__c s=new Services__c();
                   
                   s.Equipment_Onsite__c=u.ID;
                   s.Equipment_Type__c=u.Equipment__c;
                   s.Machine_Specific_Notes__c=u.Machine_Specific_Notes__c;   
                   s.Product__c=u.The_Product__c;  
                   s.Dell_Tag_Number__c=u.Dell_Tag_Number__c;
                   s.Serial_Number__c=u.Serial_Number__c; 
                   s.XD_Number__c=u.XD_Number__c;
                   
                                                  
                   
                                    
                   sub.add(s);
            }
            if(sub.size()>0)
            insert sub;
     }
}

Thank you
i have 2 objects namely objA,objB.
i have created lookup relationship on objB to objA. objA have some values like abc,xyz(two record names).

here i want to write a validation rule on objA.

While creating objB records when i select abc record from objA i want to make one field mandatory in objB.when i select another record that is xyz record i dont want to validate that field.


i hope im clear with my question.

Regards
Lakshman
I'm trying to run a location based SOQL query from javascript, using the AJAX toolkit, and I'm getting an error telling me that the location field is not defined. I have geolocation field, called Location__c, defined on the Contact. Here is my code:

<apex:page >
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="../soap/ajax/25.0/connection.js" ></script>
    <script type="text/javascript">
        $(document).ready(function() {
            sforce.connection.sessionId = '{!$Api.Session_ID}';
            var query = "SELECT Id FROM Contact WHERE DISTANCE(Location__c, GEOLOCATION(42.0, -76.0), 'mi') < 10";
            console.log(query);
            var res = sforce.connection.query(query);
            console.log(res);
        });
    </script>
</apex:page>

The post request is returning a 500 error, with the message, "No such column 'Location__c' on entity 'Contact'." However, there is a field called Location__c; furthermore, this query works just fine from the Developer Console. Can anyone see what might be going on here?
  • August 20, 2014
  • Like
  • 1
This might to the stupiest question I've ever asked (or the most genius) but is there a way to assign a VF page DIRECTLY to a user page-layout under the custom object settings?  I could have swore that I saw how to do this at some point.  (And not just creating a regular page-layout and having the VF page in that strange windowed mode.  
Browsed around for half an hour, but could only find where you can assign VF pages to tabs.  If I want to create a different VF for each user then do I have to assign those to individual tabs?  Seems like that would be kind of silly.

Hi,

I'm writing a trigger which copies data from the Campaign Member to its Campaign (as cross object workflows don't work from Campaign Members).

I've hit a problem with my test class that I can't get around:

Invalid initial expression type for field Campaign, expecting: SOBJECT:Campaign (or single row query result of that type)

The error is on Line 40, which says:

        CampaignMember cm = new CampaignMember(Campaign = cam.Id, Contact = c.Id, Send_tutor_details_to_client__c = 'First');

This is the whole of the test class:

@isTest 
public class TestUpdateTutor1onCampaign{

        static testMethod void TestUpdateTutor1onCampaign() {
       // create an Account, a Tutor, a Job and a Job Member
  
       Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
       User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
       EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
       LocaleSidKey='en_US', ProfileId = p.Id, 
       TimeZoneSidKey='America/Los_Angeles', UserName='4323f1a8-2698-44c4-a234-dfcf80fa6a6c@testorg.com');
        
       test.StartTest();
       insert u;
       u = [SELECT Id FROM User WHERE Alias = 'standt' AND Email='standarduser@testorg.com'];
      
       Account acc = new Account(Name = 'Test Account');
       insert acc;

       acc = [SELECT Id FROM Account WHERE Name = 'Test Account'];
       
       //Get the Contact record types
       List<RecordType> listRecordTypes = [Select Name, Id From RecordType where sObjectType='Contact' and isActive=true];
       Map<String,String> mapRecordTypes = new Map<String,String>();
       for(RecordType rt: listRecordTypes) {
           mapRecordTypes.put(rt.Name,rt.Id);
       }      

       Contact c = new Contact(AccountID = acc.Id, FirstName = 'Test', LastName = 'Contact', Main_Profile__c = 'www.google.com',
                               RecordTypeId = mapRecordTypes.Get('Tutor') 
                               );
        insert c;
        c = [SELECT Id FROM Contact WHERE FirstName = 'Test'];
        
        Campaign cam = new Campaign(Name = 'Test Job');
        insert cam;
        cam = [SELECT Id FROM Campaign WHERE Name = 'Test Job'];
            
        // insert a Campaign Member
        CampaignMember cm = new CampaignMember(Campaign = cam.Id, Contact = c.Id, Send_tutor_details_to_client__c = 'First');
        insert cm;
        cm = [SELECT Id FROM CampaignMember WHERE Contact =: c.Id AND Send_tutor_details_to_client__c = 'First' ];
        
        system.assertEquals(cam.Tutor_1__c, cm.Tutor_details_for_email__c);
        
        List<Campaign> camtest = [SELECT Id FROM Campaign WHERE Tutor_1__c =: cm.Tutor_details_for_email__c];
        
        system.assertEquals(1, camtest.size());

       test.StopTest();
    }

}

Any help would be greatly appreciated!

Hi .

I would like to display some conditional data when my VF page loads.I had written my soql query in constructor.But i am not sure how to dispaly in VF page.
My Vf page is a search page.So when page loads i want that data to show up .When search is done,that data has to disappear and my search results has to be showed up.

Please help.

Here is my VF page and apex class

<apex:page standardController="customobject__c" extensions="searchpageController">
<apex:form >
<apex:outputPanel id="errorPanel">
        <apex:pageMessages />
    </apex:outputPanel>

   <apex:pageblock title="Searach Records" >
  
       <apex:outputText value="Name"/>&nbsp;&nbsp;&nbsp;
       <apex:inputtext value="{!inputNametext}"/> &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
      
       <apex:outputText value="Account Name"/>
       <apex:inputtext value="{!inputAccounttext}"/> &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
      
       <apex:outputtext value="Contact Name"/>
       <apex:inputtext value="{!inputContacttext}"/> &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
      
       <apex:commandbutton value=" Search " action="{!searchRecords}"/>
   </apex:pageblock>
   <apex:pageBlock >
     <apex:pageblocktable value="{!accList}" var="acc">
      <apex:column >
         <apex:outputLink value="/{!acc.id}"><apex:outputText value="{!acc.Name}" />
         </apex:outputLink>
         </apex:column>
      <apex:column value="{!acc.Account__c}"/>
      <apex:column value="{!acc.Contact__c}"/>
     </apex:pageblocktable>    
     </apex:pageBlock>
</apex:form>
</apex:page>

Apex class:

Public class  FARsearchpageController {
   Public string inputNametext{get;set;}
   Public string inputAccounttext{get;set;}
   Public string inputContacttext{get;set;}
   Public string inputstatustext{get;set;}
   Public String soql{get;set;}
   Public List<Fuel_Analysis_Report__c> accList{get;set;}
   Public String usernames=UserInfo.getName();

   public FARsearchpageController (ApexPages.StandardController controller) {
       String soql = 'select Name,Account__c,ContactStatus__c,Closed_Date__c  from customobject__c  where name != null and Name =:Usernames';
    }
       
   Public void searchRecords(){
     soql = 'select Name,Account,Contact,Status__c,Closed_Date__c from customobject__c where Name =:Usernames';

if (string.isnotBlank(inputAccounttext)){
    soql += ' and Account.Name like '+'\''+'%'+inputaccounttext+'%'+'\'';
    }
    if (string.isnotBlank(inputnametext)){
    soql += ' and Name like '+'\''+'%'+inputnametext+'%'+'\'';
       }
    if (string.isnotBlank(inputContacttext)){
    soql += ' and Contact.Name like '+'\''+'%'+inputcontacttext+'%'+'\'';
       }
    accList= Database.query(soql);
    }
  }
}
}
hi,
 can anyone help me to find a way to get current weather report for account records???? 
Same code works in anonymous window but in test class it shows list index out of bound error .

@istest

public class setMethod{
 
    public static testmethod void main(){
        
        List<student__c> sts = new List<student__c>();
  sts =[select name from student__c ] ;
        
        
           string temp = sts.get(2).name ;
     
        system.debug(temp);
    }    
}