• Magesh Mani Yadav
  • SMARTIE
  • 795 Points
  • Member since 2016


  • Chatter
    Feed
  • 26
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 133
    Replies

Hello all,

I found some code on how to create an Apex Class that allows users to send an email to salesforce with a specific subject format to create tasks.

The problem is that this code seems to be a little old and I'm having some trouble updating it as I'm not overly familiar with Apex coding. 

 

global class clsInboundEmailHandler implements Messaging.InboundEmailHandler { 

	global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){ 
		Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); 
			
			string subject = email.Subject; 
			string userID = ''; 
			integer userIDNumber = 0; 
			string restOfSubject = ''; 
			if(subject.contains('-') == false){ 
				result.success = false; 
				return result; 
			} 
			list<String> subjectSplit = new list<String>(); 
			subjectSplit = subject.split('-'); 
			userID = subjectSplit[0]; 
			userID = userID.trim(); 
			if(userID.isNumeric() == false){ 
				result.success = false; 
				return result; 
			}else{ 
				userIDNumber = integer.valueOf(userID); 
			} 
			boolean firstOne = true; 
			for(string s : subjectSplit){ 
				if(firstOne){ 
						firstOne = false; 
					}else{ 
						restOfSubject += s; 
					} 
				} 
				
				//Now find the user 
				string userIDForTask = getUserIDForTask(userIDNumber); 
				if(userIDForTask == ''){ 
					result.success = false; 
					return result; 
				} 
				
				Task t = new Task(); 
				t.Subject = restOfSubject; //This is from the subject line 
				t.ActivityDate = date.today(); 
				t.Description = email.plainTextBody; //or email.htmlbody; 
				t.Priority = 'Normal'; 
				t.OwnerId = userIDForTask; //Set to owner 
				t.Status = 'Not Started'; 
				t.IsReminderSet = true; 
				t.ReminderDateTime = System.now() + 1; 
				insert t; 
				
				result.success = true; 
				return result; 
			} 
			
			private string getUserIDForTask(integer userIDNumber){ 
				list<boolean> userList = new list<boolean>(); 
			string userIDForTask = ''; 
			userList = [Select ID 
								From User 
								Where EmailTaskID__c = :userIDNumber]; 
			if(userList.size() <> 1){ 
				return ''; 
				}else{ 
					return userList[0].id; 
				} 
			} 
		}

The problem is at line 58, I am getting the error "Illegal assignment from List to List". I believe the error is related to the way userIDNumber is declared, but for the life of me I cannot figure out the solution.

Would anyone have any suggestions or a solution?

Thank you.
Hi iam tring to execute the java script file . i have uploaded the java script file in staticresouces  and impoted that file in to the VFpage. this is my code,


<apex:page>

<apex:pageBlock>


<apex:form>

<!-- Ext JS -->
<head>
   <apex:includeScript value="{!$Resource.jsss}"/> 
   
   </head>
    
</apex:form>

</apex:pageBlock>

</apex:page>

so please sugget me any one.

Regards,
Siva
This code queries the current opportunity's line item Name, Quantity, TotalPrice and Description and places them into custom fields and executes without error.

The problem is it only places the first two characters of the Name. 
The receiving field is a text (100) field

By commenting out this line, it works as expected but I don’t know how to fix it.
I was graciously helped with this by the community so I am not sure what this line is supposed to do or if I even need it  

if(strProductNames.length>0){ strProductNames = strProductNames.substring(0,strProductNames.length-2); } ​
 
{!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/32.0/apex.js")} 

var record = new sforce.SObject("Opportunity"); 
record.Id = '{!Opportunity.Id}'; 

result = sforce.connection.query("Select PricebookEntry.Product2.Name, Quantity, TotalPrice, Description, ServiceDate From OpportunityLineItem WHERE OpportunityId = '{!Opportunity.Id}' and (NOT Name like '%Discount%')"); 
records = result.getArray("records"); 

var strProductNames = ''; 
var strProductQuantity = ''; 
var strProductPrice = ''; 
var strDescription = ''; 
var strServiceDate = ''; 
for(var i=0; i<records.length ; i++){ 
strProductNames = records[i].PricebookEntry.Product2.Name 
strProductQuantity = records[i].Quantity 
strProductPrice = records[i].TotalPrice 
strDescription = records[i].Description 
strServiceDate = records[i].ServiceDate; 
} 

if(strProductNames.length>0){ 
strProductNames = strProductNames.substring(0,strProductNames.length-2); 
} 
record.Sample_Name__c = strProductNames; 
record.Sample_Quantity__c = strProductQuantity; 
record.Sample_Price__c = strProductPrice; 
record.Sample_Description__c = strDescription; 
record.Sample_Service_Date__c =strServiceDate; 

sforce.connection.update([record]); 
window.location.reload();

 
Object class in Custom Controller
public transient List< PaymentList > PaymentWrapperList;

public class PaymentWrapper {
    	public Payment__c payment { get; set; }
    	public isSelected { get; set; }
    	
    	public PaymentWrapper ( payment p ){
    		payment = p;
    		isSelected = false;
    	}
}

Apex Test
CustomController cc = new CustomController();

        //for question
        for(PaymentWrapper payWrap: PaymentWrapperList) {
        	// error occurs: Save error: Invalid type: PaymentWrapper
        	// How do I reference PaymentWrapper in CustomController?
        }


How do I reference PaymentWrapper from CustomController in my Apex Test class?
Does PaymentWrapperList being a transient variable hinder me for iterating over it?
All, need help. I`m getting an error at line 17 unexpected token: ')' and I cant figure out why. Can someone please help?
 
public class callout {


Settings__c ts = [SELECT Name, Client_Secret__c, ConsumerKey__c, Password__c, SecurityToken__c,Username__c from Settings__c];



String clientId = ts.ConsumerKey__c;
String clientSecret = ts.Client_Secret__c;
String username=ts.Username__c;
String password=ts.Password__c+ts.SecurityToken__c; 

String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;

Http h = new Http ();
HttpRequest req = new HttpRequest ();
req.setBody(reqbody);
req.setMethod('POST');
req.setEndpoint(ts.URL__c+'/services/oauth2/token');

HttpResponse res = h.send(req);
OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);
RequestWrapper reqst=new RequestWrapper();
if(objAuthenticationInfo.access_token!=null){
Http h1 = new Http();
HttpRequest req1 = new HttpRequest();

req1.setHeader('Authorization','Bearer '+objAuthenticationInfo.access_token);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
req1.setBody(jsonstr);//Send JSON body
req1.setMethod('POST');
req1.setEndpoint(ts.URL__c+URL);
HttpResponse res1 = h1.send(req1);
system.debug('RESPONSE_BODY'+res1 .getbody());
}
}

 
Hi
I need to built a page with say two or more fields – their values will be Yes or No – based on if it is selected or not.
Get these field values in class and based on field values set variable values and call the function e.g:
VF Page:
Text1: Yes(it is a radio button)
Text2: Yes(radio)
call saveList from action button on VF page.
Apex Class:
Public String Cat
Public String Req
public PageReference saveList()
{
if(Text1 == Yes):
Cat = ‘abc’
Req = ‘abc’
CallFunction(Cat,Req)
}
if(Text2 == ‘Yes’){
Cat = ‘def’
Req = ‘def’
CallFunction(Cat,Req)
}
}
public void CallFuntion(String Cat, String Req)
{
statements;
}
public class stagesize 
{
    public stagesize() 
    {
    lstOpp = new List<Opp>();
  stages = new list<string>();
        Schema.DescribeFieldResult fieldResult = Opportunity.StageName.getDescribe();
        System.debug(fieldResult);
        List<Schema.PicklistEntry> pichlstval = fieldResult.getPicklistValues(); 
        system.debug('--pichlstval -->>'+pichlstval );              
        for( Schema.PicklistEntry f : pichlstval )
        {
           stages.add(f.getLabel());
          System.debug('@@@@@stages' +stages);
        }
        
        map < string , list<opportunity>> lststage = new map < string , list<opportunity>>();
          for(Opportunity opp : [select id,Name,StageName from Opportunity])
          {
           if(lststage.get(opp.StageName)== null)
            {
             lststage.put(opp.StageName , new list<Opportunity>());
            }
           lststage.get(opp.StageName).add(opp);    
          System.debug('@@@@@lststage.size()' +lststage.size());
          }     
     for(string opp : stages)
     {
     integer i = lststage.size();
    String prefix = String.getCommonPrefix(stages);
     System.debug('@@@@@i' +i );
      System.debug('@@@@@prefix' +prefix );

    Opp o = new opp(prefix , i);
    lstOpp.add(o);
   //     lstOpp.add((prefix),(i));
     }
     
      }
     public List<Opp> lstOpp {get;set;} 
    public List<string> stages {get;set;}
    
    public class Opp  
    {
        public String stage {get;set;}    
        public Integer size {get; set;}
        
      public  opp(string s , Integer I)  
      {
        stage = s;
        size = i ;
      }
    }
}
Hi Folks,

I am very new to salesforce I am trying to create my first Recruting app from the book force_com_platform_fundamentals.pdf available on the website but unfortunately I couldn't find this screen:
Setup ares


I am trying to find this here:
Lightening website


Since both UIs are different I think I am trying to fing it at wrong place. Please let me know the exact URL to get the first screen. Also let me know do I need to purchase any salesforce edition to create the app.

Thanks in advance!

Regards,
Neetu
  • August 30, 2016
  • Like
  • 0

Afternoon All, 

I am trying to save my VF page but i am getting the following error "Error: Unknown property 'testWrapper.materialWrapper.select' ". 

Aim - The user will go to the sales_and_marketing__c object ,scroll down to the Materials_Junction related list. click "new", this should then call the VF page listed below. and return all the records from the Materials object which are active (Crtieria in Class). The user then selects the Materials, fills in quantity. When the User Saves this should then be mapped back to the sales_and_marketing__c object

Really appreciate your help 

I have the following Controller : 

public with sharing class testWrapper
{
    public List<Materials__c> Materials {get;set;} 
    public List<materialWrapper> materialWrapperList {get;set;} 
    
    public testWrapper()
    {
        Materials = [select ID,name,Product__c, Item__c,Quanity__c, Active__c from Materials__c where Active__c =true limit 10];
        for(Materials__c obj : Materials)
        {
            materialWrapper tempObj= new materialWrapper();
            tempObj.recordId = obj.id;
            tempObj.name = obj.name;
            tempObj.product = obj.Product__c;
            tempObj.item = obj.Item__c;
            tempObj.quantity = obj.Quanity__c;
            tempObj.selectB = false;
            materialWrapperList.add(tempObj);
        }
    }

    //save method
    public void save()
    {
        list<Materials_Junction__c> recordToInsert = new list<Materials_Junction__c>();
        
        for(materialWrapper obj : materialWrapperList)
        {
         Materials_Junction__c temp ;
            if(obj.selectB == true)
            {
                temp = new Materials_Junction__c();
                temp.sales_and_marketing__c = '01I20000000rV6V';
                temp.Materials__C= obj.recordId;
                temp.quantity__C = obj.quantity; 
            }
            recordToInsert.add(temp);
        }
        insert recordToInsert;
    }
    
    
    public class materialWrapper
    {
        public string recordId {get; set;}
        public string name {get; set;}
        public string product {get; set;}
        public string item {get; set;}
        public Decimal quantity {get; set;}
        public boolean selectB {get; set;}
        
        public void materialWrapper()
        {
            recordId = '';
            name = '';
            product = '';
            item = '';
            quantity = 0.0;
            selectB = false;
        }
    }
}

Visual Force Page :

apex:page controller="testWrapper">
<apex:form >
    <apex:pageBlock title="Select Product">

        <apex:pageBlockButtons >
            <apex:commandButton value="Save" action="{!save}"/>
        </apex:pageBlockButtons>

        <apex:pageBlockTable value="{!materialWrapperList}" var="MKT"> 
            <apex:column value="{!MKT.select}"/>
            <apex:column value="{!MKT.name}"/>       
            <apex:column value="{!MKT.Product}"/>
            <apex:column value="{!MKT.Item}"/>
            <apex:column headerValue="Quanity">
                <apex:inputField value="{!MKT.Quanity}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>
</apex:form>
Hi,

I am trying to set up a validation method when the user finishes typing and leaves the inputText.  I am grabbing that input and passing it to the controller extension and then grab a list of all the contact's emails and comparing it to the input to see if there is a match.  When I press the submit button to save a record, the apexclass will go into the validation method.  It just won't enter the method using onblur for some reason.  I am just wondering if there are any clues to as why this may be?

Also this messes up with some of the fields I am rerendering, even though email is not a condition in the rerender statement things will not show up unless I type an email.

Below is the javascript calling the validation method within the apex class:
    <script type="text/javascript">
        function getEmail(selectedValue){
            alert('Inside the javascript the email is: ' + selectedValue.value);
            ValidateEmail(selectedValue.value);
            return false;
        }    
    </script>

Below here is the inputText line with the onblur method:
<apex:inputText value="{!emailid}" styleClass="form-control" style="text-align: left;width:45%" required="true" onblur=" getEmail(this);" />
        <apex:actionFunction action="{!ValidateEmail}" name="ValidateEmail">        
            <apex:param id="emailid" name="emailid" value="" assignTo="{!emailid}"/> 
        </apex:actionFunction>  

Then below is the method within the apex class:
public void ValidateEmail(){
        System.debug('Just entered ValidateEmail');
        List<Contact> contactList = [SELECT Email FROM Contact];
        String tmp = Apexpages.currentPage().getParameters().get('emailid');
        Boolean match = false;
        
        for(Contact c: contactList)
        {
            if(emailid == c.Email){
                System.debug('There is a match');
                System.debug('tmp email: ' + tmp);
                System.debug('emailid: ' + emailid);
                System.debug('list email: ' + c.Email);
                match = true;
                break;
            }
        }
        if(match == false){
            System.debug('There is no match');
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, 'Email not in database please enter valid email');        
        }
    }

Thanks!
Hi there,

I am trying to run a trigger for a while with different patterns but not getting the results except errors.
One custom field(value_to_be_copied__c) is on lead and one custom field(copied_value__c ) is on task.
The condition is whenever a task related to a lead is created, the value of value_to_be_copied__c should be copied to copied_value__c. 
First pattern is :-
trigger leadtasktrigger on Task (after insert) {

set<id> leid = new set<id>();
for(task ta :trigger.new){
if(string.valueof(ta.whoid).startsWith('OOQ'))
        {
          leid.add(ta.whoid);
         }
       }
 for(lead le2 :[select id, (select id, subject, copied_value__c from task), value_to_be_copied__c from lead where id in :leid]){
   le2.task.copied_value__c = le2.value_to_be_copied__c;
 }
}

Error for the above code is 
Error: Compile Error: Didn't understand relationship 'task' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. at line 10 column 16

Second pattern is -

trigger leadtasktrigger on Task (after insert) {

set<id> taid = new set<id>();
list<task> taid1 = new list<task>();
for(task ta :trigger.new){
if(string.valueof(ta.whoid).startsWith('OOQ'))
        {
          taid.add(ta.id);
         }
       }
   for(task ta1 : [select id, subject, copied_value__c, whoid from task where id in: taid]){
     
     taid1.add(ta1);
     
   } 
   
   for(task ta2 : taid){
   ta2.copied_value__c = ta2.who.value_to_be_copied__c ;
   }
 }
Error: Compile Error: Invalid field value_to_be_copied__c for SObject Name at line 18 column 26.

Please help .. TIA..    
 
Hi guys,

below is the code in which if we change the value of picklist the details of the selected record has to be shown below and initiallling the detail block should be hidden and on every change of picklist value the detail block should be refreshed

<apex:page controller="sc">
<apex:form >
  Select country:  <apex:selectList size="1" value="{!accid}" >
                      <apex:selectOptions value="{!option}" ></apex:selectOptions> 
                      <apex:actionSupport event="onchange"  action="{!find}" rerender="pb"/> 
                 </apex:selectList><br/><br/>
                 <apex:messages />
                 
                 <apex:outputPanel id="pb" rendered="{!booblock}" >
                 <apex:pageblock title="Detail secton"  >
                 
                 <apex:pageBlockSection id="pbs">
                 <apex:pageBlockTable value="{!acc}" var="a" id="pbt">
                 <apex:column value="{!a.name}"/>
                 <apex:column value="{!a.phone}"/>
                 <apex:column value="{!a.billingcity}"/>
                 </apex:pageBlockTable>
                 </apex:pageBlockSection>
                 </apex:pageblock>
                 </apex:outputPanel>
</apex:form>
</apex:page>

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

public with sharing class sc {

public boolean booblock{set;get;}
public string accid {set;get;}
public list<selectoption> option {set;get;}
public list<account> acclist = [select id,name from account limit 999];
public account acc{set;get;}

    public sc() {

option = new list<selectoption>();
 option.add(new selectoption('None','None'));
 
for(account ac : acclist){
option.add(new selectoption(ac.id,ac.name));

    }
    }

public void find(){


try{
acc = [select id,name,phone,billingcity from account where id =:accid];
booblock = true;
}
catch(exception e){
system.debug('exception type is'+e.gettypename());
system.debug('exception message is'+e.getMessage());
ApexPages.addMessages(e);
/*ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please enter value'));*/
}
}
}

But in the above code if i remove the "rendered="{!booblock}" " component it is working fine ...but here my requirement is detail component should be shown only when picklist value is changed any help would be appriciated
Hi All,
 I've created simple page to show contact basic info. When I used preview and it is opening in context of Contact but I used record id to see values of specific records. code not fetching any records.

URL: https://c.ap2.visual.force.com/apex/ContactView?core.apexpages.request.devconsole=0032800000WyJgW

<apex:page title="Contact" standardController="Contact">
    <apex:pageBlock title="Contact Summary">
        <apex:pageBlockSection>
            Name: {! Contact.FirstName } <br/>
            Phone: {! Contact.LastName } <br/>
            Email: {! Contact.owner.email } <br/>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

Please let me know what could be the issue.
Hi there,

I'm attempting to cobble together some code for a lead convert trigger that will (after update, after insert) ensure the resulting Account's name is the Last Name plus the last 4 digits of the phone number and I'm a little stuck. For example, if you were converting a lead named John Smith and his phone number was 123-456-7890, the resulting account would be called "Smith-7890". The piece for the trigger to autoconvert works fine, but the portion updating the account is giving me from trouble. Any advice would be appreciated!
trigger LeadConvert on Lead (after insert,after update) {
//Bulkified
    List<String> LeadNames = new List<String>{};
        for(Lead myLead: Trigger.new){
         if((myLead.isconverted==false) && (myLead.Status == 'Scheduled Appointment')) {
            Database.LeadConvert lc = new database.LeadConvert();
            lc.setLeadId(myLead.Id);
            lc.convertedStatus = 'Scheduled Appointment';
        //Database.ConvertLead(lc,true);
            lc.setDoNotCreateOpportunity(true);
            Database.LeadConvertResult lcr = Database.convertLead(lc);
            System.assert(lcr.isSuccess());
            }
        }
        List <Account> account = [SELECT acc.Id, acc.Description FROM Account acc WHERE acc.Id = :Trigger.new.ConvertedAccountId];
        for (Account acc: account) {
    	acc.Name = Trigger.new.LastName + Trigger.new.RIGHT(Phone, 4);
        update acc;
    }
}

 
<apex:page controller="getrecordtype">
<apex:form >
YEAR<apex:selectList Size="1">
<apex:selectOptions value="{!items}"></apex:selectOptions>
</apex:selectList>
<apex:selectList >
<apex:selectOption value="{!RecordTypeSelectedId}"></apex:selectOption>
 </apex:selectList>
 </apex:form>
</apex:page>
------------------------------------------------------------------------------------------------------------
public with sharing class getrecordtype {

    public String getRecordTypeSelectedId(){
  String recordTypeName;
    String rtId;
    List<RecordType> rtList = New List<RecordType>([Select ID, Name From RecordType Where sObjectType = 'contact']);
    for(RecordType rt : rtList) {
        if(rt.Name == recordTypeName) {
             rtId = rt.Id;
        }
    }
    return rtId;        


public List<SelectOption> getItems() {
            List<SelectOption> options = new List<SelectOption>();
            options.add(new SelectOption('2014','2014'));
            options.add(new SelectOption('2015','2015'));
            options.add(new SelectOption('2016','2016'));
            return options;
        }
            
 
}
VF page:
<apex:page controller="Time_date"  sidebar="false">
 <apex:form >
  <apex:pageBlock title="Displaying all records of s object">
   <apex:pageBlockSection columns="1">
    <apex:pageBlockTable var="b" value="{!bk}" cellpadding="4" cellspacing="4">
     
     <apex:column headervalue="Name" value="{!b.name}"/>
     <apex:column headervalue="EDITION" value="{!b.Edition__c}"/>
     <apex:column headervalue="Price" value="{!b.price__c}"/>
     <apex:column headervalue="Created Date">
     Date:<apex:outputText value="{!dt}"/>
     Time:<apex:outputText value="{!tm}"/>
     </apex:column>
     <apex:column headervalue="modified Date" value="{!b.LastModifiedDate}"/>
     
    </apex:pageBlockTable>
   </apex:pageBlockSection>
  </apex:pageBlock>
 </apex:form>
</apex:page>

Apex Class:

public with sharing class Time_date {

    public time tm { get; set; }

    public date dt { get; set; }

    public List<book__c> bk { get; set; }
    public Time_date(){
    bk=[select id,name,edition__c,price__c,Createddate,lastmodifieddate from book__c];
    //dt=DATEVALUE(CreatedDate);+
    //tm=MID(TEXT(CreatedDate - 0.1667), 12, 5);
   datetime Createddate;
    
    //dt=Createddate.date();  //display Error
    //tm=Createddate.Time();


 
    }
}

Output:
createddate field in out I want to display separate date and time

 
DeleteDMl class
public class DeleteDml {
    public void accountInserting(){
        //fetching old records with name kanus
        List<Account> accounts =[SELECT id,name from Account WHERE name='kanus'];
        try{
        delete accounts;
        }catch(Exception e){
            system.debug('records are not deleted');
            
        }
    }
}

testclass
@istest
public class DeleteDML_test {
    public static testMethod Account insertingAccount(){
        test.startTest();
        Account a = new Account();
        a.Name='kanus';
        insert a;
        DeleteDml d = new DeleteDml();
        d.accountInserting();
        Test.stopTest();
        return a;
       
    }
    public static testMethod void Method2(){
      Test.startTest();
        Account a1=insertingAccount();
        Account a2=[SELECT id,name FROM Account WHERE name='kanus123'];
        try{
            delete a2;
        }catch(Exception e){
            system.debug('no record with name kanus123');
        }
        
        test.stopTest();
         DeleteDml d1 = new DeleteDml();
        d1.accountInserting();
    }
}

Hi All,

I want to display one <div>Content</div> as like popup.But it will display when i will click on <apex:inputtextField />.

How i will do it?

Please help me.

Thanks in advance,

Dileep

Hi all,

 

How can I populate the case account id field through a web-to-case submition?

I've tried to use the fields: account.id and accountid but none worked.

Upon case submition I already know the account id value.

Thanks.

 

 

 

 

 

 

Hello there,

I wonder if salesforce's Apex runtime can process batches of two different classes at the same time (simultaneouly)? If yes, can we track using AsyncApexJob which class is executing current batch?

Thanks in advance.
Hello i need only to reload frame with VF page.
I use <apex:commandButton value="Check" id="checkBtn" oncomplete="window.location.reload( true );"/>, but it reloads parrent page inside the visual forece page, how to fix it?
Trigger not getting fired , using an object from managed package.

Trying to update fields in shipper record after insert from the fields of Sales order record.

here is the code, 

trigger UpdateContactInfo on rstk__soship__c (after insert) {
    System.debug('********trigger is called');
    rstk__soship__c[] shipments = Trigger.new;
    rstk__sohdr__c[] orders = null;
    for(rstk__soship__c shipment:shipments){
        orders = [Select    rstk__sohdr_contact__c, rstk__sohdr_conemail__c,rstk__sohdr_conphone__c 
                  from rstk__sohdr__c 
                  where rstk__sohdr_order__c =: shipment.rstk__soship_order__c ];
        
        System.debug('Here in the for loop shipment ordernumber '+shipment.rstk__soship_order__c);
        
        if(orders.size() > 0){
            System.debug('Found the order order name :'+orders[0].rstk__sohdr_contact__c+
                         'email: '+orders[0].rstk__sohdr_conemail__c+
                         'Phone :'+orders[0].rstk__sohdr_conphone__c);
            shipment.rstk__soship_contact__c = orders[0].rstk__sohdr_contact__c;
            shipment.rstk__soship_email__c = orders[0].rstk__sohdr_conemail__c;
            shipment.rstk__soship_phone__c = orders[0].rstk__sohdr_conphone__c;
         }
    }

}

Any suggestion would be very much appreciated. Thanks,

Hello all,

I found some code on how to create an Apex Class that allows users to send an email to salesforce with a specific subject format to create tasks.

The problem is that this code seems to be a little old and I'm having some trouble updating it as I'm not overly familiar with Apex coding. 

 

global class clsInboundEmailHandler implements Messaging.InboundEmailHandler { 

	global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){ 
		Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); 
			
			string subject = email.Subject; 
			string userID = ''; 
			integer userIDNumber = 0; 
			string restOfSubject = ''; 
			if(subject.contains('-') == false){ 
				result.success = false; 
				return result; 
			} 
			list<String> subjectSplit = new list<String>(); 
			subjectSplit = subject.split('-'); 
			userID = subjectSplit[0]; 
			userID = userID.trim(); 
			if(userID.isNumeric() == false){ 
				result.success = false; 
				return result; 
			}else{ 
				userIDNumber = integer.valueOf(userID); 
			} 
			boolean firstOne = true; 
			for(string s : subjectSplit){ 
				if(firstOne){ 
						firstOne = false; 
					}else{ 
						restOfSubject += s; 
					} 
				} 
				
				//Now find the user 
				string userIDForTask = getUserIDForTask(userIDNumber); 
				if(userIDForTask == ''){ 
					result.success = false; 
					return result; 
				} 
				
				Task t = new Task(); 
				t.Subject = restOfSubject; //This is from the subject line 
				t.ActivityDate = date.today(); 
				t.Description = email.plainTextBody; //or email.htmlbody; 
				t.Priority = 'Normal'; 
				t.OwnerId = userIDForTask; //Set to owner 
				t.Status = 'Not Started'; 
				t.IsReminderSet = true; 
				t.ReminderDateTime = System.now() + 1; 
				insert t; 
				
				result.success = true; 
				return result; 
			} 
			
			private string getUserIDForTask(integer userIDNumber){ 
				list<boolean> userList = new list<boolean>(); 
			string userIDForTask = ''; 
			userList = [Select ID 
								From User 
								Where EmailTaskID__c = :userIDNumber]; 
			if(userList.size() <> 1){ 
				return ''; 
				}else{ 
					return userList[0].id; 
				} 
			} 
		}

The problem is at line 58, I am getting the error "Illegal assignment from List to List". I believe the error is related to the way userIDNumber is declared, but for the life of me I cannot figure out the solution.

Would anyone have any suggestions or a solution?

Thank you.
Hi iam tring to execute the java script file . i have uploaded the java script file in staticresouces  and impoted that file in to the VFpage. this is my code,


<apex:page>

<apex:pageBlock>


<apex:form>

<!-- Ext JS -->
<head>
   <apex:includeScript value="{!$Resource.jsss}"/> 
   
   </head>
    
</apex:form>

</apex:pageBlock>

</apex:page>

so please sugget me any one.

Regards,
Siva
i want to find the label for field and i am using this code to find that,it is returning me label but for Type picklist lable is Type but it is returning Account Type,any help just to get label as Type?

String type='Account';
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Schema.SObjectType leadSchema = schemaMap.get(type);
Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();

for (String fieldName: fieldMap.keySet()) {
System.debug('##Field API Name='+fieldName);// list of all field API name
 
System.debug(fieldMap.get(fieldName).getDescribe().getLabel());//It provides to get the object fields label.
}
This code queries the current opportunity's line item Name, Quantity, TotalPrice and Description and places them into custom fields and executes without error.

The problem is it only places the first two characters of the Name. 
The receiving field is a text (100) field

By commenting out this line, it works as expected but I don’t know how to fix it.
I was graciously helped with this by the community so I am not sure what this line is supposed to do or if I even need it  

if(strProductNames.length>0){ strProductNames = strProductNames.substring(0,strProductNames.length-2); } ​
 
{!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/32.0/apex.js")} 

var record = new sforce.SObject("Opportunity"); 
record.Id = '{!Opportunity.Id}'; 

result = sforce.connection.query("Select PricebookEntry.Product2.Name, Quantity, TotalPrice, Description, ServiceDate From OpportunityLineItem WHERE OpportunityId = '{!Opportunity.Id}' and (NOT Name like '%Discount%')"); 
records = result.getArray("records"); 

var strProductNames = ''; 
var strProductQuantity = ''; 
var strProductPrice = ''; 
var strDescription = ''; 
var strServiceDate = ''; 
for(var i=0; i<records.length ; i++){ 
strProductNames = records[i].PricebookEntry.Product2.Name 
strProductQuantity = records[i].Quantity 
strProductPrice = records[i].TotalPrice 
strDescription = records[i].Description 
strServiceDate = records[i].ServiceDate; 
} 

if(strProductNames.length>0){ 
strProductNames = strProductNames.substring(0,strProductNames.length-2); 
} 
record.Sample_Name__c = strProductNames; 
record.Sample_Quantity__c = strProductQuantity; 
record.Sample_Price__c = strProductPrice; 
record.Sample_Description__c = strDescription; 
record.Sample_Service_Date__c =strServiceDate; 

sforce.connection.update([record]); 
window.location.reload();

 
Hi,

There are some account records in one org which had been created in 2015. But when i migrate these records in other org using data loader in 2016 the date is changing. But i want to keep the same date. Can anyone provide me solution for this?

 

Hi all,
      my requirment to find greatest integer in the list. In below code map have a size of integer. I want to take maximum integer value in the list(map1 contain integer list) and show on the page.

public class sizeorder 
{
public list<Ordered__c> lstorder {get;set;}

    public sizeorder()
    {
        lstorder = [select id,Name, Customer__c, Email__c from Ordered__c];
    map<string,list<Ordered__c>> map1 = new map<string,list<Ordered__c>>();
    
        for(Ordered__c ord : lstorder)
        {
            if(map1.get(ord.Customer__c )==null)
            {
             map1.put(ord.Customer__c ,  new list<Ordered__c >());
            }
           map1.get(ord.Customer__c).add(ord);
        }
     for(string str : map1.keyset())
     {
     list<Ordered__c> lst = map1.get(str);
     integer inte = lst.size();
     System.debug('@@@@@inte' + inte );
     integer i;
     integer j;
     integer k;
     integer l ;
     for(i=0; i<inte ; i++)
      {
     j = i++ ; 
     l= j ;
     system.debug('####j' +j); 
     system.debug('####l' +l); 
     system.debug('####i++' +i++); 
      }
      for (i = 1; i < inte ; i++)
      {
        if ( i > j)
        {
           j = k ; 
           system.debug('####j' +j); 
        }
      }
    }
  }
}
Object class in Custom Controller
public transient List< PaymentList > PaymentWrapperList;

public class PaymentWrapper {
    	public Payment__c payment { get; set; }
    	public isSelected { get; set; }
    	
    	public PaymentWrapper ( payment p ){
    		payment = p;
    		isSelected = false;
    	}
}

Apex Test
CustomController cc = new CustomController();

        //for question
        for(PaymentWrapper payWrap: PaymentWrapperList) {
        	// error occurs: Save error: Invalid type: PaymentWrapper
        	// How do I reference PaymentWrapper in CustomController?
        }


How do I reference PaymentWrapper from CustomController in my Apex Test class?
Does PaymentWrapperList being a transient variable hinder me for iterating over it?
Hi All,,

I am writing the Validation rule for specific record type on check of check box i want the mobile field to become madator. I have written below code and it is not working :-

IF( RecordType.DeveloperName  = "Testing", AND(Text_Consent__c = True, ISBLANK(MobilePhone__c)), NULL)

If I just write below code it works fine :-
AND(Text_Consent__c = True, ISBLANK(MobilePhone__c))

Any idea what is going wrong when i am adding the record type.

Thanks,
Pankaj Pandey
 
All, need help. I`m getting an error at line 17 unexpected token: ')' and I cant figure out why. Can someone please help?
 
public class callout {


Settings__c ts = [SELECT Name, Client_Secret__c, ConsumerKey__c, Password__c, SecurityToken__c,Username__c from Settings__c];



String clientId = ts.ConsumerKey__c;
String clientSecret = ts.Client_Secret__c;
String username=ts.Username__c;
String password=ts.Password__c+ts.SecurityToken__c; 

String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;

Http h = new Http ();
HttpRequest req = new HttpRequest ();
req.setBody(reqbody);
req.setMethod('POST');
req.setEndpoint(ts.URL__c+'/services/oauth2/token');

HttpResponse res = h.send(req);
OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);
RequestWrapper reqst=new RequestWrapper();
if(objAuthenticationInfo.access_token!=null){
Http h1 = new Http();
HttpRequest req1 = new HttpRequest();

req1.setHeader('Authorization','Bearer '+objAuthenticationInfo.access_token);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
req1.setBody(jsonstr);//Send JSON body
req1.setMethod('POST');
req1.setEndpoint(ts.URL__c+URL);
HttpResponse res1 = h1.send(req1);
system.debug('RESPONSE_BODY'+res1 .getbody());
}
}

 
Hi
I need to built a page with say two or more fields – their values will be Yes or No – based on if it is selected or not.
Get these field values in class and based on field values set variable values and call the function e.g:
VF Page:
Text1: Yes(it is a radio button)
Text2: Yes(radio)
call saveList from action button on VF page.
Apex Class:
Public String Cat
Public String Req
public PageReference saveList()
{
if(Text1 == Yes):
Cat = ‘abc’
Req = ‘abc’
CallFunction(Cat,Req)
}
if(Text2 == ‘Yes’){
Cat = ‘def’
Req = ‘def’
CallFunction(Cat,Req)
}
}
public void CallFuntion(String Cat, String Req)
{
statements;
}
Hi there,

I'm attempting to cobble together some code for a lead convert trigger that will (after update, after insert) ensure the resulting Account's name is the Last Name plus the last 4 digits of the phone number and I'm a little stuck. For example, if you were converting a lead named John Smith and his phone number was 123-456-7890, the resulting account would be called "Smith-7890". The piece for the trigger to autoconvert works fine, but the portion updating the account is giving me from trouble. Any advice would be appreciated!
trigger LeadConvert on Lead (after insert,after update) {
//Bulkified
    List<String> LeadNames = new List<String>{};
        for(Lead myLead: Trigger.new){
         if((myLead.isconverted==false) && (myLead.Status == 'Scheduled Appointment')) {
            Database.LeadConvert lc = new database.LeadConvert();
            lc.setLeadId(myLead.Id);
            lc.convertedStatus = 'Scheduled Appointment';
        //Database.ConvertLead(lc,true);
            lc.setDoNotCreateOpportunity(true);
            Database.LeadConvertResult lcr = Database.convertLead(lc);
            System.assert(lcr.isSuccess());
            }
        }
        List <Account> account = [SELECT acc.Id, acc.Description FROM Account acc WHERE acc.Id = :Trigger.new.ConvertedAccountId];
        for (Account acc: account) {
    	acc.Name = Trigger.new.LastName + Trigger.new.RIGHT(Phone, 4);
        update acc;
    }
}

 
All,

Hoping you can help as i logged a case with Salesforce and they can't resolve it as it is not supported by them. 

We launced a new website last week and i set up the 301 redirects to the landing pages of the new site. However, they aren't working and are just giving the site maintenance message. Unfortunately over the weekend we had 85 hits to one of these links where people had bookmarked them and weren't redirected, possibly resulting in lost business for us.

Has anyone ever come across this issue before?

Just for further info all redirects are activated and the link redirects are:

     //directpersonnel.force.com/SiteLogin to http://directpersonnel.com/jobs/
//directpersonnel.force.com/ts2__JobSearch to https://directpersonnel.com/jobs
    //directpersonnel.force.com/ts2__Register to     http://directpersonnel.com/jobs/

Thanks,

Claire
Hi,

I'm using Salesforce Lightning Design System with a Visualforce page and using <svg> tag to get SLDS Icons on Page header and Buttons. Initially on page load all works fine but when I try to re-render any <apex:outputPanel> that have <svg> icons inside it, on complete of rerendering it vanish my all <svg> icons.
I tried to debbug it by Inspect element in chrome and found after re-rendering any block my <svg> icon tags are not there.

anyone else experiencing this issue?

Any advise or guidance would be greatly appreciated.

Thanks,
@thatherahere
Hi,

I'm using Lightning Design System with a Visualforce page and using <svg> tag to get SLDS Icons on Page header and Buttons. Initially on page load all works fine but when I try to re-render any <apex:outputPanel> that have <svg> icons inside it, on complete of rerendering it vanish my all <svg> icons.
I tried to debbug it by Inspect element in chrome and found after re-rendering any block my <svg> icon tags are not there.

anyone else experiencing this issue?

Any advise or guidance would be greatly appreciated.

Thanks,
@thatherahere
While going thru Trailhead and learning many things, I decided to put together my own version of yet another Trailhead Leader board. I've fleshed out an example that keeps track of Name, ID, Badges, Superbadges, Comm Badges and Total Points. Sorting, ID validation are also being done. I did all of this for my own edification and learning to better reinforce the skills that Trailhead provided me. Trailhead is really quite amazing

Link to Dev Org Public Site: http://trailhead-leaderboard-developer-edition.na35.force.com

This App is one VisualSource Page and Apex controller running as a Public Site. Refresh occurs periodically from a .Net Web App using the Partner WSDL API

I'm hoping to move all of that over to Apex once I figure out a bunch of things. I see some other suggestions about dates. It would be nice to incorporate that also. I'm sure that something like this could be incorporated into Salesforce Orgs for folks to keep track of training of their employees with Trailhead. Part of the loader I've built using the Partner WSDL scans thru all of the badges of a profile and can load them into the Org somewhere.