-
ChatterFeed
-
10Best Answers
-
1Likes Received
-
0Likes Given
-
100Questions
-
121Replies
Help with Trigger on Attachments
I am trying to get the latest attachment id on to the case object fields based on the Name of the document . I have 2 fields on cases ( A,X)and If an attachement is added to case with the name ABC then its Id should be filled in Filed A on case and if Attachment is added with Name XYZ then Field X on the case should be filled with the ID of XYZ. If there are mutiple attachments with the same name then we should take the latest attachment.
I am trying this below way and it is able to bring in Att.Name or Att. ParentID but for some reason it could not bring in the Att.id field . And i still have to include by date condition
I am trying this below way and it is able to bring in Att.Name or Att. ParentID but for some reason it could not bring in the Att.id field . And i still have to include by date condition
trigger CaseAttachment on Attachment (before insert) { Boolean isCaseAttachment = FALSE; List<Case> Cases = new List<Case>(); Set<Id> accIds = new Set<Id>(); for(Attachment att : trigger.New){ /*Check if uploaded attachment is related to Case Attachment and same Case is already added*/ if(att.ParentId.getSobjectType() == Case.SobjectType && (!accIds.contains(att.ParentId)) && att.Name.contains('XYZ')){ //prepare a Case object for update Cases.add( new Case( Id=att.ParentId, A__c= att.ID ) ); //add the Caseid in set to eliminate dupe updates accIds.add(att.ParentId); } if(att.ParentId.getSobjectType() == Case.SobjectType && (!accIds.contains(att.ParentId)) && att.Name.contains('ABC')){ //prepare a Case object for update Cases.add( new Case( Id=att.ParentId, X__c = att.ID ) ); //add the Caseid in set to eliminate dupe updates accIds.add(att.ParentId); } } //finally update Cases update Cases; }
- SF7
- July 29, 2016
- Like
- 0
Help with Custom Button to access Visual force page
Hi ,
I have an Object Order Calendar which is a Lookup to Account . I have a calendar visual force page which contains all the records when i access it through apex/calendar . Order calendar will be a realted list on account and when i click a button from the related list or from account deatil page how do i make sure that records on the page only shows that account and not for all accounts . This is the URL i am using now
/apex/calendar?id=&Object=Order_Calendar__c
I have an Object Order Calendar which is a Lookup to Account . I have a calendar visual force page which contains all the records when i access it through apex/calendar . Order calendar will be a realted list on account and when i click a button from the related list or from account deatil page how do i make sure that records on the page only shows that account and not for all accounts . This is the URL i am using now
/apex/calendar?id=&Object=Order_Calendar__c
<apex:page controller="CalendarExample_Controller" action="{!pageLoad}"> <link href="{!$Resource.fullCalendarCSS}" rel="stylesheet" /> <link href="{!$Resource.fullCalendarPrintCSS}" rel="stylesheet" media="print" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script src="{!$Resource.fullCalendarMinJS}"></script> <script> //We need to wrap everything in a doc.ready function so that the code fires after the DOM is loaded $(document).ready(function() { //Call the fullCallendar method. You can replace the '#calendar' with the ID of the dom element where you want the calendar to go. $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month' //right: 'month,agendaWeek,agendaDay' }, editable: false, events: [ //At run time, this APEX Repeat will reneder the array elements for the events array <apex:repeat value="{!events}" var="e"> { title: "{!e.title}", start: '{!e.startString}', end: '{!e.endString}', url: '{!e.url}', allDay: {!e.allDay}, className: '{!e.className}', Account:'{e.account}' }, </apex:repeat> ] }); }); </script> <!--some styling. Modify this to fit your needs--> <style> #cal-options {float:left;} #cal-legend { float:right;} #cal-legend ul {margin:0;padding:0;list-style:none;} #cal-legend ul li {margin:0;padding:5px;float:left; } #cal-legend ul li span {display:block; height:16px; width:16px; margin-right:4px; float:left; border-radius:4px;} #calendar {margin-top:1px;} #calendar a:hover {color:#fff !important;} .fc-event-inner {padding:0px;} .event-Order {background:#1797c0;border-color:#56458c;} .event-Orders {background:#24f424;border-color:#24f424;} .event-Orderss {background:#ff0000;border-color:#ff0000;} </style> <apex:includeScript value="{!$Resource.moment_min_js}" /> <apex:sectionHeader title="Order Calendar"/> <apex:outputPanel id="calPanel"> <apex:form > <div id="cal-options"> <!-- <apex:commandButton value="{!IF(includeMyEvents,'Hide My Events','Show My Events')}" action="{!toggleMyEvents}"/> --> </div> <div id="cal-legend"> <ul> <li><span class="event-Order"></span>Order Calendar</li> </ul> <div style="clear:both;"><!--fix floats--></div> </div> <div style="clear:both;"><!--fix floats--></div> <div id="calendar"></div> </apex:form> </apex:outputPanel> </apex:page>
public class CalendarExample_Controller extends CCMTY_BaseController { public Boolean includeMyEvents {get;set;} public list<calEvent> events {get;set;} //The calendar plugin is expecting dates is a certain format. We can use this string to get it formated correctly String dtFormat = 'EEE, d MMM yyyy HH:mm:ss u'; //String dtFormat = 'yyyy-MM-dd HH:mm:ss u'; //constructor public CalendarExample_Controller() { //Default showing my events to on includeMyEvents = true; } public PageReference pageLoad() { events = new list<calEvent>(); //Get Order Calendar for(Order_Calendar__c Ocald : [select Id, Order_Date__c,Type_of_Event__c,Account__c from Order_Calendar__c // where Account__c =:this.getCurrentUserAccount().Id ]){ DateTime startDT = datetime.newInstance(Date.Today().Year(),Ocald.Order_Date__c.Month(), Ocald.Order_Date__c.Day()); //DateTime endDT = Ocald.Delivery_Date__c; If (Ocald.Type_of_Event__c =='Place Order') { calEvent OrderEvent = new calEvent(); OrderEvent.startString = startDT.format(dtFormat); OrderEvent.title = Ocald.Type_of_Event__c; OrderEvent.allDay = true; OrderEvent.endString = ''; OrderEvent.account = Ocald.Account__c; OrderEvent.url = '/' + Ocald.Id; OrderEvent.className = 'event-Order'; events.add(OrderEvent); } If (Ocald.Type_of_Event__c =='Delivery') { calEvent OrderEvents = new calEvent(); OrderEvents.startString = startDT.format(dtFormat); OrderEvents.title = Ocald.Type_of_Event__c; OrderEvents.allDay = true; OrderEvents.endString = ''; OrderEvents.url = '/' + Ocald.Id; OrderEvents.className = 'event-Orders'; events.add(OrderEvents); } If (Ocald.Type_of_Event__c =='Holiday') { calEvent OrderEventss = new calEvent(); OrderEventss.startString = startDT.format(dtFormat); OrderEventss.title = Ocald.Type_of_Event__c; OrderEventss.allDay = true; OrderEventss.endString = ''; OrderEventss.url = '/' + Ocald.Id; OrderEventss.className = 'event-Orderss'; events.add(OrderEventss); } } return null; } public PageReference toggleMyEvents() { if(includeMyEvents){ includeMyEvents = false; } else{ includeMyEvents = true; } pageload(); return null; } //Class to hold calendar event data public class calEvent{ public String title {get;set;} public Boolean allDay {get;set;} public String startString {get;set;} public String endString {get;set;} public String url {get;set;} public String className {get;set;} public String account {get;set;} } }
- SF7
- April 19, 2016
- Like
- 0
Trigger not populating Lookup field on child object
Hi ,
I am Auto creating multiple child records based on other objects . When a Financial Batch record is created i need to create multiple child records (line items) based on some other related object. This is the relationship of objects . Account--- Financial_Batch ---- Financial_ Line_Items
Every thing is working as intended . When i have 20 Financials on the Account then 20 new Financial Batch items are created as child records to Financila batch when Financial Batch is created . Only issue is i am unable to pupluate Financils__cid on financial Batch item Lookup field
I am Auto creating multiple child records based on other objects . When a Financial Batch record is created i need to create multiple child records (line items) based on some other related object. This is the relationship of objects . Account--- Financial_Batch ---- Financial_ Line_Items
trigger CCMTY_CreatePaymentLineItems on Financial_Batch__c (after insert) { List<Financial_Batch_Item__c> PItem = new List<Financial_Batch_Item__c>(); Set<Id> setAccountId = new Set<Id>(); // Set of Id to hold Account id's in Payment Map<Id,Id> accountInvMap = new Map<Id,Id>(); Map<Id,Integer> mapAccountIdInvoiceCount = new Map<Id,Integer>(); // Map of Id to Integer to hold Account Id and corresponding number of Invoices for (Financial_Batch__c Pay : trigger.new) { setAccountId.add(pay.Account__c); //Here Account__c is the relationship field in Financial_Batch__c which relates to Account } for(Financials__c Inv:[Select Id ,Account__c,Type__c from Financials__c where Status__c NOT IN ('Closed', 'Paid')and Financial_External_Key__c like 'Mexico%' and Account__c IN:SetAccountid Order by Type__c ]) { accountInvMap.put(Inv.id,Inv.Parent_Financials__C); } for(Account a : [Select Id,(Select Id ,Type__c from Financials__r where Status__c NOT IN ('Closed', 'Paid')and Financial_External_Key__c like 'Mexico%' Order by Type__c) from account where id IN: setAccountId]) { mapAccountIdInvoiceCount.put(a.Id,a.Financials__r.size()); // Populate map with Account Id and corresponding list of invoice size } for (Financial_Batch__c Pay : trigger.new) { for(Integer i=0; i<mapAccountIdInvoiceCount.get(pay.Account__c);i++) { Financial_Batch_Item__c PBI = new Financial_Batch_Item__c(); PBI.Financial_Batch__c = Pay.Id; // PBI.Financials__c = accountInvMap.get(i).id; PItem.add(PBI); } } insert PItem; }
Every thing is working as intended . When i have 20 Financials on the Account then 20 new Financial Batch items are created as child records to Financila batch when Financial Batch is created . Only issue is i am unable to pupluate Financils__cid on financial Batch item Lookup field
- SF7
- April 15, 2016
- Like
- 0
Auto Clone and create 2 new orders when an existing order is updated with a different status
<apex:commandButton value="Submit Order" action="{!submitOrder}" rendered="{!isOrderSubmitable}" reRender="pgBlock" onclick="if ( !confirm('{!$Label.CCMTY_Submit_Msg}') ){return false;}" status="status" /> public PageReference submitOrder(){ PageReference pr = null; try{ // Calculate the time Difference between Qoute Submition to uptil now Order ordTemp = [select Quote_Created_Date__c from Order where id =:orderRecord.ID]; Double qouteSubmitTimeDiff = double.valueOf(((System.now().getTime())/1000/60/60) - ((ordTemp.Quote_Created_Date__c.getTime())/1000/60/60)); // Don't process the order with 24hrs older qoutes. if(qouteSubmitTimeDiff > 24){ addErrorMessage(Label.ErrorMsg_QuoteExpired); return pr; } eiJcCreateOrderServices.createOrderRequestType cor = new eiJcCreateOrderServices.createOrderRequestType(); cor.orderNumber = CCMTY_StringUtil.stripRegionFromId(this.orderRecord.Order_Quote_Number__c); eiJcCreateOrderServices.PSCreateOrderSOAP osp = new eiJcCreateOrderServices.PSCreateOrderSOAP(); osp.inputHttpHeaders_x = new Map<String, String>{'apikey' => CCMTY_Settings__c.getInstance().EI_API_Key__c}; osp.timeout_x = 60000; eiJcCreateOrderServices.createOrderResponseType restp;// = osp.createOrder(cor.orderNumber); restp = osp.createOrder(cor.orderNumber); System.debug(restp); System.debug('restp.orderNumber: ' + restp.orderNumber); if( !String.isBlank(restp.orderNumber) ) { this.orderRecord.Order_External_Key__c = this.orderRecord.Order_Region__c + '-' + restp.orderNumber; this.orderRecord.Status = 'Submitted'; this.orderRecord.Order_Submit_Date__c = System.today(); System.debug('order rebate total:'+orderRecord.Order_Total_Rebate__c+' status:'+orderRecord.Status); update this.orderRecord; List<OrderItem> orderItems = [select Order_Products_Line_Number__c from OrderItem where OrderId = :this.orderRecord.Id]; for ( OrderItem oi : orderItems ) { oi.Order_Products_External_Key__c = this.orderRecord.Order_External_Key__c + '-' + oi.Order_Products_Line_Number__c; } update orderItems; if(test.isRunningTest()) { orderRecord = [Select accountId, Order_Total_Rebate__c,Status,OrderNumber, (Select id,name, Order_Discount_Value__c,Order_Discount_Type__c from Order_Discounts__r ) from order where id=: ordTemp.Id limit 1 ]; } System.debug('order rebate total:'+orderRecord.Order_Total_Rebate__c+' status:'+orderRecord.Status+' this.orderRecord.Order_Discounts__r:'+this.orderRecord.Order_Discounts__r); if(orderRecord.Order_Total_Rebate__c > 0 && orderRecord.Status.equals('Submitted')) { List<Rebate_Transaction__c> rebateTransactions = new List<Rebate_Transaction__c>(); System.debug('this.orderRecord.Order_Discounts__r: ' + this.orderRecord.Order_Discounts__r); for ( Order_Discount__c od : this.orderRecord.Order_Discounts__r ) { if ( od.Order_Discount_Type__c == 'Rebate' ) { Decimal startingBal = (rebateTypesAvailableAmtMap.get(od.Name) != null)? rebateTypesAvailableAmtMap.get(od.Name) : 0 ; rebateTransactions.add(getRebateConsumedRecord(od.Name, od.Order_Discount_Value__c,startingBal, (startingBal - od.Order_Discount_Value__c))); } } insert rebateTransactions; } pr = new PageReference( '/' + this.getOrderKeyPrefix() ); pr.getParameters().put('feedback', 'OrderSubmitted'); pr.getParameters().put('orderNumber', this.orderRecord.OrderNumber); pr.getParameters().put('selectedFilterId', CCMTY_Settings__c.getInstance().Orders_Default_List_View_ID__c); } }catch( DmlException e){ this.orderRecord.Order_Submit_Date__c = null; this.addGenericErrorMessage(); } return pr; }
// This is another class which Auto Clones the Order when a clone button is clicked on the Front end maully by the user . <apex:page standardController="Order" extensions="OrderCloneWithItemsController" action="{!cloneWithItems}"> <apex:pageMessages /> </apex:page> public class OrderCloneWithItemsController { //added an instance varaible for the standard controller private ApexPages.StandardController controller {get; set;} // add the instance for the variables being passed by id on the url private Order po {get;set;} // set the id of the record that is created -- ONLY USED BY THE TEST CLASS public ID newRecordId {get;set;} // initialize the controller public OrderCloneWithItemsController(ApexPages.StandardController controller) { //initialize the stanrdard controller this.controller = controller; // load the current record po = (Order)controller.getRecord(); } // method called from the VF's action attribute to clone the po public PageReference cloneWithItems() { // setup the save point for rollback Savepoint sp = Database.setSavepoint(); Order newPO; try { //copy the purchase order - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE po = [select Id, Name, accountId, Order_Total_Rebate__c,EffectiveDate,Status,Order_Region__c,OrderNumber,Order_ShipTo_Address__c,CurrencyIsoCode , PoNumber, Order_Requested_Delivery_Date__c ,Order_Comments__c, Pricebook2Id from Order where id = :po.id]; newPO = po.clone(false); insert newPO; // set the id of the new po created for testing newRecordId = newPO.id; // copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE List<OrderItem> items = new List<OrderItem>(); for (OrderItem pi : [Select p.Id, p.UnitPrice,p.Price_Book_External_Key__C, p.Quantity,p.Order_Products_Line_Number__c,p.Description,p.Brand__c,p.PricebookEntryId From OrderItem p where OrderId = :po.id]) { OrderItem newPI = pi.clone(false); newPI.OrderId = newPO.id; items.add(newPI); } insert items; } catch (Exception e){ // roll everything back in case of error Database.rollback(sp); ApexPages.addMessages(e); return null; } return new PageReference('/'+newPO.id+'/e?retURL=%2F'+newPO.id); } }I want to auto clone and create 2 new orders from an existing order when the Order is submitted (Status on order is changed to Submitted ).
I was able to cretae a button from the front end and clone the records but i want this clone called from the first class and create the records without manul intervention like clicking the clone button.
Thanks
- SF7
- April 12, 2016
- Like
- 0
Trigger to create multiple child records when a parent is created
Hi ,
i am tryinng to create multiple child records when a parent record is created . The records in child object should be coming from an another relaetd object . Here is my data model
Data model 1: Account (Parent)<<<<<< Invoices (Child)
Date Model 2 : Account (Master Parent)<<<<<<Payment(Parent)<<<<<<Payment Line Items (Child) <<<<<< Invoices
Example Salesforce is my account and it has 20 Invoices , now i am creating a Payment ( notthing related to invoice at this time ) record and when i save this payment record 20 payment line items should be created. One record for each invoice salesforce account has .
I can create a child to a parent automatically but not sure how to create mutiple child records based on the Invoices object .
Here is the start with able to create single child record
Thanks,
Akhil
i am tryinng to create multiple child records when a parent record is created . The records in child object should be coming from an another relaetd object . Here is my data model
Data model 1: Account (Parent)<<<<<< Invoices (Child)
Date Model 2 : Account (Master Parent)<<<<<<Payment(Parent)<<<<<<Payment Line Items (Child) <<<<<< Invoices
Example Salesforce is my account and it has 20 Invoices , now i am creating a Payment ( notthing related to invoice at this time ) record and when i save this payment record 20 payment line items should be created. One record for each invoice salesforce account has .
I can create a child to a parent automatically but not sure how to create mutiple child records based on the Invoices object .
Here is the start with able to create single child record
trigger CreatePaymentLineItems on Payment__c (after insert) { List<Payment_Item__c> PItem = new List<Payment_Item__c>(); for (Payment__c Pay : trigger.new) { Payment_Item__c PBI = new Payment_Item__c(); PBI.Payment__c = Pay.Id; // PBI.Financial__c = Pay.; PItem.add(PBI); } insert PItem; }
Thanks,
Akhil
- SF7
- April 05, 2016
- Like
- 1
How can I display month in chinese in apex code?
public with sharing class ScorecardController extends BaseController { public Map<String, Map<String, Double>> gradeToUnitsMap {get; private set;} public Map<String, Map<String, Double>> applicationToUnitsMap {get; private set;} public Map<String, Map<String, Double>> brandToUnitsMap {get; private set;} public List<SelectOption> fiscalYearOptions {get; private set;} public String selPeriod {get; set;} public String selYear {get; set;} public List<SelectOption> monthOptions { get { if ( this.monthOptions == null ) { this.monthOptions = new List<SelectOption>{new SelectOption('', System.Label.CCMTY_Month)}; for ( Integer i = 1; i <= 12; i++ ) { DateTime dt = DateTime.newInstance(2015, i, 5); this.monthOptions.add(new SelectOption(String.valueOf(i), dt.format('MMMM'))); } } return this.monthOptions; } private set; } public ScorecardController() { // Initialize period variables this.selPeriod = ''; // Default to the previous month Integer defaultMonth = System.today().month() - 1; // If current month is January, then set month to December if ( defaultMonth == 0 ) { defaultMonth = 12; } this.selPeriod = String.valueOf(defaultMonth); // Default to current calendar year Integer currYear = System.today().year(); // If default month is Oct or Nov, then increment current calendar year to set correct FY // If default month is December, it means that current calendar month is January, and // there's no need to increment the current calendar year if ( defaultMonth > 9 && defaultMonth != 12 ) { currYear += 1; } this.selYear = String.valueOf(currYear); this.fiscalYearOptions = CCMTY_Util.getSelectOptionsListByField(Sales_Plan__c.Fiscal_Year__c, null); doCalculations(); }
- SF7
- January 11, 2016
- Like
- 0
Save and New- Need to redirect to Same VF Page with parent ID
Hi ,
I have a Visual force page and Need a Custom Save and New Functionality,
Opportunity (Parent Object) ------- Client_Discovery__C (Child Object) ,
Client_Discovery__C (Parent Object) ----- Client_Site__C (Child Object)
Client_Site__C (Parent Object) ------ Client Supplier (Child Object)
What i am trying to achive with my visual force page is , On Opportunity related list i have New Client Disovery Button withich is Standard Visual Page.
When user Clicks New Client Disocvery and enters data
and hits save page is Redirected to new Visual Force page where users can create Client Site and Multipole Supplier at the Same time .
Here when user finishes enetring data He needs to hit Save & New and again go to the same VF page where he just hit save & new . I am able to redirect to that page but missing the Parent ID.
First Vf Page Standard page ClientQuestionarrie with Custom Save method in Client Questionarrie Controller.
Missing Client Disovery ID
Thanks
Akhil
I have a Visual force page and Need a Custom Save and New Functionality,
Opportunity (Parent Object) ------- Client_Discovery__C (Child Object) ,
Client_Discovery__C (Parent Object) ----- Client_Site__C (Child Object)
Client_Site__C (Parent Object) ------ Client Supplier (Child Object)
What i am trying to achive with my visual force page is , On Opportunity related list i have New Client Disovery Button withich is Standard Visual Page.
When user Clicks New Client Disocvery and enters data
and hits save page is Redirected to new Visual Force page where users can create Client Site and Multipole Supplier at the Same time .
Here when user finishes enetring data He needs to hit Save & New and again go to the same VF page where he just hit save & new . I am able to redirect to that page but missing the Parent ID.
First Vf Page Standard page ClientQuestionarrie with Custom Save method in Client Questionarrie Controller.
public with sharing class ClientQuestionarrie { Apexpages.StandardController controller; public Client_Discovery__c myCustomObject; public ClientQuestionarrie(ApexPages.StandardController sc) { this.controller = sc; myCustomObject = (Client_Discovery__c) sc.getRecord(); } public PageReference SaveQuestionarrie() { upsert myCustomObject; Pagereference ref = new Pagereference('/Apex/ClientSite'); ref.getParameters().put('Client_Discovery__c', myCustomObject.Id); ref.setRedirect(true); return ref; } }
public with sharing class ClientSiteExt { public ClientSiteExt(ApexPages.StandardController controller) { Client_Site__c c = (Client_Site__c) controller.getRecord(); c.Client_Discovery__c = ApexPages.currentPage().getParameters().get('Client_Discovery__c'); } }
<apex:page standardController="Client_Site__c" extensions="AddClientSupplier,ClientSiteExt" tabStyle="Client_Site__c"> <apex:form id="myForm" > <apex:sectionHeader title="New Client Site" /> <apex:pageBlock title=" Client Site Edit" mode="edit"> <apex:pageBlockButtons location="top" > <apex:commandButton value="Save" action="{!saveClientSite}" /> <apex:commandButton value="Save & New" action="{!SaveAndNew}"/> <apex:commandButton value="Cancel" action="{!Cancel}"/> </apex:pageBlockButtons> <apex:pageBlockSection title="Information" columns="2"> <apex:inputField value="{!Client_Site__c.Client_Site_Name__c}" taborderhint="1"/> <apex:inputField value="{!Client_Site__c.Client_Discovery__c}" taborderhint="6"/> <apex:inputField value="{!Client_Site__c.City__c}" taborderhint="2"/> <apex:inputField value="{!Client_Site__c.Number_of_Shifts__c}" taborderhint="7"/> <apex:inputField value="{!Client_Site__c.State__c}" taborderhint="3"/> <apex:inputField value="{!Client_Site__c.Number_of_Team_Leads__c}" taborderhint="8"/> <apex:inputField value="{!Client_Site__c.Head_count__c}" taborderhint="4"/> <apex:inputField value="{!Client_Site__c.Number_of_On_Site_Managers__c}" taborderhint="9"/> <apex:inputField value="{!Client_Site__c.Job_Titles__c}" taborderhint="5"/> <apex:inputField value="{!Client_Site__c.Union_or_Non_Union__c}" taborderhint="10"/> </apex:pageBlockSection> <apex:pageBlockSection title="Client Suppliers" columns="4"> </apex:pageBlockSection> <apex:repeat value="{!lClientSuppliers}" var="x"> <apex:panelGrid columns="6"> <apex:panelGrid > <apex:facet name="header">Client Supplier Name</apex:facet> <apex:inputField value="{!x.c.Supplier_Name__c}" style="width:200px" /> </apex:panelGrid> <apex:panelGrid > <apex:facet name="header">Is This a New or Incumbent Supplier?y</apex:facet> <apex:inputField value="{!x.c.Is_This_a_New_or_Incumbent_Supplier__c}" style="width:200px" /> </apex:panelGrid> <apex:panelGrid > <apex:facet name="header">Skill Type</apex:facet> <apex:inputField value="{!x.c.Skill_Type__c}" style="width:200px"/> </apex:panelGrid> <apex:panelGrid > <apex:facet name="header"> Will Manpower manage this supplier?</apex:facet> <apex:inputField value="{!x.c.Will_Manpower_Manage_This_Supplier__c}" style="width:200px" /> </apex:panelGrid> <apex:panelGrid > </apex:panelGrid> <apex:commandButton action="{!deleteClientSupplier}" style="Button" value="Delete ClientSite" reRender="myForm" immediate="true"> <apex:param value="{!x.counter}" name="selected" assignTo="{!selectedContact}"/> </apex:commandButton> </apex:panelGrid> </apex:repeat> <apex:pageBlockButtons location="bottom"> <apex:panelGrid ></apex:panelGrid> <apex:commandButton value="Add Client Supplier" action="{!addAClientSupplier}" reRender="myForm" immediate="true" /> <apex:commandButton value="Save" action="{!saveClientSite}" /> <apex:commandButton value="Cancel" action="{!cancel}"/> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page>
public class AddClientSupplier { ApexPages.StandardController sc; public Client_Site__c acct{get;set;} public Client_Discovery__c cDiscovery; public Integer marker=2; public Integer selectedClientSupplier{get;set;} public List<WrapperClass> lClientSuppliers{get;set;} public String queryString {get;set;} public AddClientSupplier(ApexPages.StandardController controller) { sc=controller; this.acct = (Client_Site__c)controller.getRecord(); lClientSuppliers=new List<WrapperClass>(); Client_Supplier__c c=new Client_Supplier__c(); lClientSuppliers.add(new WrapperClass(c,1)); } public PageReference deleteClientSupplier(){ Integer x=-1; for(WrapperClass wc:lClientSuppliers){ x++; if(wc.counter==selectedClientSupplier){ System.debug('-->selected ClientSupplier:'+selectedClientSupplier+' position:'+x); break; } } lClientSuppliers.remove(x); return null; } public PageReference saveClientSite(){ Database.SaveResult sr = Database.insert(acct, false); Id idey=sr.getId(); List<Client_Supplier__c> ClientSupplierList=new List<Client_Supplier__c>(); for(WrapperClass wc:lClientSuppliers){ if(!string.isblank(wc.c.Supplier_Name__c) ){ Client_Supplier__c c=new Client_Supplier__c(); c.Is_This_a_New_or_Incumbent_Supplier__c=wc.c.Is_This_a_New_or_Incumbent_Supplier__c; c.Skill_Type__c=wc.c.Skill_Type__c; c.Supplier_Name__c=wc.c.Supplier_Name__c; c.Will_Manpower_Manage_This_Supplier__c=wc.c.Will_Manpower_Manage_This_Supplier__c; c.Client_Site__c=idey; ClientSupplierList.add(c); } } insert ClientSupplierList; return(new PageReference('/'+sr.id).setRedirect(True)); // return new PageReference('/' + Schema.getGlobalDescribe().get('Client_Discovery__c').getDescribe().getKeyPrefix() + '/o'); } public PageReference addAClientSupplier(){ Client_Supplier__c c=new Client_Supplier__c(); lClientSuppliers.add(new WrapperClass(c,marker)); marker=marker+1; return null; } public class WrapperClass{ public Integer counter{get;set;} public Client_Supplier__c c{get;set;} public WrapperClass(Client_Supplier__c cntc,Integer i){ this.c=cntc; this.counter=i; } } public PageReference saveAndNew() { sc.save(); PageReference pRef = Page.ClientSite; pRef.setRedirect(true); //pRef.getParameters().put('Client_Discovery__c', cDiscovery.id); return pRef; } }When i Hit Save and New
Missing Client Disovery ID
Thanks
Akhil
- SF7
- October 02, 2015
- Like
- 0
Save and New - redirect to a VF along with Parent ID in Visual force page
<apex:page standardController="Client_Site__c" extensions="AddClientSupplier,ClientSiteExt" tabStyle="Client_Site__c"> <apex:form id="myForm" > <apex:sectionHeader title="New Client Site" /> <apex:pageBlock title=" Client Site Edit" mode="edit"> <apex:pageBlockButtons location="top" > <apex:commandButton value="Save" action="{!saveClientSite}" /> <!-- <apex:commandButton value="Save & New" action="{!saveandnew1}" /> --> <apex:commandButton value="Cancel" action="{!Cancel}"/> </apex:pageBlockButtons> </Apex:Page>
public class AddClientSupplier { ApexPages.StandardController sc; public Client_Discovery__c myCustomObject; public Client_Site__c acct{get;set;} public Integer marker=2; public Integer selectedClientSupplier{get;set;} public List<WrapperClass> lClientSuppliers{get;set;} public String queryString {get;set;} public AddClientSupplier(ApexPages.StandardController controller) { this.acct = (Client_Site__c)controller.getRecord(); sc=controller; lClientSuppliers=new List<WrapperClass>(); Client_Supplier__c c=new Client_Supplier__c(); lClientSuppliers.add(new WrapperClass(c,1)); } public PageReference deleteClientSupplier(){ Integer x=-1; for(WrapperClass wc:lClientSuppliers){ x++; if(wc.counter==selectedClientSupplier){ System.debug('-->selected ClientSupplier:'+selectedClientSupplier+' position:'+x); break; } } lClientSuppliers.remove(x); return null; } public PageReference saveClientSite(){ Database.SaveResult sr = Database.insert(acct, false); Id idey=sr.getId(); List<Client_Supplier__c> ClientSupplierList=new List<Client_Supplier__c>(); for(WrapperClass wc:lClientSuppliers){ if(!string.isblank(wc.c.Supplier_Name__c) ){ Client_Supplier__c c=new Client_Supplier__c(); c.Is_This_a_New_or_Incumbent_Supplier__c=wc.c.Is_This_a_New_or_Incumbent_Supplier__c; c.Skill_Type__c=wc.c.Skill_Type__c; c.Supplier_Name__c=wc.c.Supplier_Name__c; c.Will_Manpower_Manage_This_Supplier__c=wc.c.Will_Manpower_Manage_This_Supplier__c; c.Client_Site__c=idey; ClientSupplierList.add(c); } } insert ClientSupplierList; return(new PageReference('/'+sr.id).setRedirect(True)); // return new PageReference('/' + Schema.getGlobalDescribe().get('Client_Discovery__c').getDescribe().getKeyPrefix() + '/o'); } public PageReference addAClientSupplier(){ Client_Supplier__c c=new Client_Supplier__c(); lClientSuppliers.add(new WrapperClass(c,marker)); marker=marker+1; return null; } public class WrapperClass{ public Integer counter{get;set;} public Client_Supplier__c c{get;set;} public WrapperClass(Client_Supplier__c cntc,Integer i){ this.c=cntc; this.counter=i; } } /* public PageReference saveandnew(){ try { sc.save(); Schema.DescribeSObjectResult describeResult = sc.getRecord().getSObjectType().getDescribe(); PageReference pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e?' + queryString); pr.setRedirect(true); return pr; } catch(System.DMLException e) { // Note: not spitting out any error messages, as SF seems to be handling the errors fine, at least for my simple object; your mileage my vary. return null; } }*/ }
public with sharing class ClientSiteExt { public ClientSiteExt(ApexPages.StandardController controller) { Client_Site__c c = (Client_Site__c) controller.getRecord(); c.Client_Discovery__c = ApexPages.currentPage().getParameters().get('Client_Discovery__c'); } }Hi ,
I need a Custom Save and New button which when hit need to direct me to the same VF page which i just created the record on . pb is i am unable have the parent ID for the LookUp field.
- SF7
- October 01, 2015
- Like
- 0
Custom Save method to redirect to child Edit page along with Parent ID
Hi ,
I have a Visual force page for creating a parent record in which i have a custom Save method and when save is clicked the the page has to be redirected to the new page to create a child object and pb is i am unable to pull in the parent ID into the Child object page.
I have a Visual force page for creating a parent record in which i have a custom Save method and when save is clicked the the page has to be redirected to the new page to create a child object and pb is i am unable to pull in the parent ID into the Child object page.
<apex:page standardController="Client_Discovery__c" Controller ="AddClientSite" sidebar="false"> <apex:commandButton value="Save" action="{!saveDiscovery}"/> <apex:commandButton value="Cancel" action="{!cancel}"/> </Apex:page>
public class AddClientSite { ApexPages.StandardController sc; public Client_Discovery__c acct{get;set;} public PageReference saveAccount1(){ Insert acct; PageReference reRend = new PageReference('/a1k/e?CF00N1300000BRJGg_lkid='+acct.id+'&retUrl=' + acct.Id); reRend.setRedirect(true); return reRend; }
- SF7
- September 21, 2015
- Like
- 0
System.LimitException: Too many SOQL queries: 101 Only in Production not in UAT
Hi,
I have a code which is causing issues while deploying . Pb is it is fine in UAT and not in Production,
TestOppLineItemControllerExtension testChangeLOB System.LimitException: Too many SOQL queries: 101
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testChangeLOB: line 231, column 1
TestOppLineItemControllerExtension testInsertOLI System.LimitException: Too many SOQL queries: 101
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testInsertOLI: line 57, column 1
TestOppLineItemControllerExtension testPageMessages System.LimitException: Too many SOQL queries: 101
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testPageMessages: line 169, column 1
TestOppLineItemControllerExtension testcancelMethod System.LimitException: Too many SOQL queries: 101
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testcancelMethod: line 202, column 1
Thanks
Akhil
I have a code which is causing issues while deploying . Pb is it is fine in UAT and not in Production,
TestOppLineItemControllerExtension testChangeLOB System.LimitException: Too many SOQL queries: 101
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testChangeLOB: line 231, column 1
TestOppLineItemControllerExtension testInsertOLI System.LimitException: Too many SOQL queries: 101
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testInsertOLI: line 57, column 1
TestOppLineItemControllerExtension testPageMessages System.LimitException: Too many SOQL queries: 101
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testPageMessages: line 169, column 1
TestOppLineItemControllerExtension testcancelMethod System.LimitException: Too many SOQL queries: 101
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testcancelMethod: line 202, column 1
static testMethod void testChangeLOB() { //Create test data Opportunity opp = new opportunity(); opp = createTestData(); // Set the current page to OpportunityLineItemEdit VF Page PageReference servicesPage = new PageReference('apex/OpportunityLineItemEdit?opp_id='+opp.id); Test.setCurrentPage(servicesPage); //Create an object of the OppLineItemControllerExtension class OppLineItemControllerExtension oliCE = new OppLineItemControllerExtension (); //The values of service Line and sub-service are not null system.assertnotEquals(null, oliCE.selFamily); system.assertEquals(null, oliCE.selService); //re-populate the value of LOB and invoke the changeLOB method oliCE.changeLOB(); //Retrieve the values of service line and sub-service // The service line will be none because the LOB has changed system.assertEquals('-None-', oliCE.selFamily); // The sub-service will be null because the service line is NONE system.assertEquals(null, oliCE.selService); } }
static testMethod void testcancelMethod() { //Create test data Opportunity opp = new opportunity(); opp = createTestData(); // Set the current page to OpportunityLineItemEdit VF Page PageReference servicesPage = new PageReference('apex/OpportunityLineItemEdit?opp_id='+opp.id); Test.setCurrentPage(servicesPage); //Create an object of the OppLineItemControllerExtension class OppLineItemControllerExtension oliCE = new OppLineItemControllerExtension (); //Invoke the cancel method and verify the url of the page it navigates to String nextpage = oliCE.cancel().getUrl(); PageReference p = new ApexPages.Standardcontroller (opp).view (); system.assertequals(p.getUrl(),nextpage); }
This is the class code part where the stack is pointing public OppLineItemControllerExtension() { selLOB = '-None-'; selFamily = '-None-'; if ((ApexPages.currentPage().getParameters().get('opp_id') != null)&&(ApexPages.currentPage().getParameters().get('opp_id').length() > 0)) { System.debug ('*****Opp in URL: '+ ApexPages.currentPage().getParameters().get('opp_id').length()); this.oli = new OpportunityLineItem(); oli.OpportunityId = ApexPages.currentPage().getParameters().get('opp_id'); opp = [select Name, Account.name, CurrencyIsoCode,IsClosed ,ServiceEdit__c from Opportunity where id=:oli.OpportunityId]; accountName = opp.Account.Name; oppName = opp.Name; oppCurrencyIsoCode = opp.CurrencyIsoCode; for (pricebookentry pbe : [SELECT product2.recordtype.name, product2.family, product2.Sub_Service__c, product2Id from pricebookentry where pricebook2.name like 'OPP%' and isActive = TRUE and pricebookentry.CurrencyIsoCode =: oppCurrencyIsoCode order by product2.recordtype.name, product2.family, product2.Sub_Service__c]) { if (LOBName != pbe.product2.recordtype.name) { LOBName = pbe.product2.recordtype.name; System.debug('LOB NAME::::'+LOBName); LOBServicesMap.put (LOBName, new Map <String, Map <ID, String>> ()); } if (Family != pbe.product2.family) { Family = pbe.product2.family; LOBServicesMap.get (LOBName).put (Family, new Map <ID, String> ()); } LOBServicesMap.get (LOBName).get (Family).put (pbe.id, pbe.product2.Sub_Service__c); } displayOLIDetails = true; } //PU:03/04/2011 - When the Opportunity Id is null the below error message has to be displayed. else { displayOLIDetails = false; ApexPages.addMessage(new ApexPages.Message (ApexPages.Severity.Error, Label.oppLI_ErrMsgOppRequired)); } wrappers=new List<OcrWrapper>(); for (Integer idx=0; idx<1; idx++) { List<selectOption> opt = LOBNames(); wrappers.add(new OcrWrapper(nextIdent+1,opt)); } }
Thanks
Akhil
- SF7
- September 04, 2015
- Like
- 0
An error occurred when processing your submitted information
Hi ,
When i save the record in a LookUp , This weird error comes up. Any idea why this is happening.
When i save the record in a LookUp , This weird error comes up. Any idea why this is happening.
<apex:page controller="CustomContactLookupController" title="Search" showHeader="false" sideBar="false" tabStyle="Contact" id="pg"> <apex:form > <apex:outputPanel id="page" layout="block" style="margin:5px;padding:10px;padding-top:2px;"> <apex:tabPanel switchType="client" selectedTab="name1" id="tabbedPanel"> <!-- SEARCH TAB --> <apex:tab label="Contact Search" name="tab1" id="tabOne"> <apex:actionRegion > <apex:outputPanel id="top" layout="block" style="margin:1px;padding:10px;padding-top:2px;"> <apex:outputLabel value="{!$Label.OptyContRolePage_Search_Button}" style="font-weight:Bold;padding-right:10px;" for="txtSearch"/> <apex:inputText id="txtSearch" value="{!searchString}"/> <span style="padding-left:5px"> <apex:commandButton id="btnGo" value="{!$Label.OptyContRolePage_Go_Button}" action="{!Search}" rerender="searchResults"> </apex:commandButton> </span> </apex:outputPanel> <apex:outputPanel id="pnlSearchResults" style="margin:10px;height:350px;overflow-Y:auto;font-size:small" layout="block"> <apex:outputLabel value="{!$Label.OptyContRolePage_ResultSection}" style="font-weight:Bold;padding-right:10px;"/> <br/><br/> <apex:pageBlock id="searchResults" title="Contacts[{!searchContactCount}]"> <apex:pageBlockTable value="{!results}" var="a" id="tblResults"> <apex:column > <apex:facet name="header"> <apex:outputPanel >Name</apex:outputPanel> </apex:facet> <apex:outputLink value="javascript:top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.Name}',false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Name}</apex:outputLink> </apex:column> <apex:column > <apex:facet name="header"> <apex:outputPanel >Client Name</apex:outputPanel> </apex:facet> <apex:outputText value="{!a.Account.Name}" rendered="{!NOT(ISNULL(a.Id))}"/> </apex:column> <apex:column > <apex:facet name="header"> <apex:outputPanel >Phone</apex:outputPanel> </apex:facet> <apex:outputText value="{!a.Phone}" rendered="{!NOT(ISNULL(a.Id))}"/> </apex:column> <apex:column > <apex:facet name="header"> <apex:outputPanel >Email</apex:outputPanel> </apex:facet> <apex:outputText value="{!a.Email}" rendered="{!NOT(ISNULL(a.Id))}"/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> </apex:outputPanel> </apex:actionRegion> </apex:tab> <apex:tab label="New Contact" name="tab2" id="tabTwo"> <apex:pageBlock id="newContact" title="New Contact"> <apex:pageBlockButtons > <apex:commandButton action="{!SaveContact}" value="Save"/> </apex:pageBlockButtons> <apex:pageMessages /> <apex:pageBlockSection columns="2"> <apex:repeat value="{!$ObjectType.Contact.FieldSets.CustomContactLookup}" var="f"> <apex:inputField value="{!Contact[f]}"/> </apex:repeat> <!-- <apex:inputField value="{!Contact.LastName}"/> <apex:inputField value="{!Contact.Email}"/> <apex:inputField value="{!Contact.AccountID}"/> --> </apex:pageBlockSection> </apex:pageBlock> </apex:tab> </apex:tabPanel> </apex:outputPanel> </apex:form> </apex:page>
public with sharing class CustomContactLookupController { public Contact Contact {get;set;} // new Contact to create public List<Contact> results{get;set;} // search results public string searchString{get;set;} // search keyword public Id ultiAccId; public Id localAccId; public Integer searchContactCount {get;set;} public CustomContactLookupController() { // get the current search string searchString = System.currentPageReference().getParameters().get('lksrch'); ultiAccId = System.currentPageReference().getParameters().get('ultimateAccId'); localAccId= System.currentPageReference().getParameters().get('localAccId'); runSearch(); } // performs the keyword search public PageReference search() { searchContactCount = 0; runSearch(); return null; } // prepare the query and issue the search command private void runSearch() { // TODO prepare query string for complex serarches & prevent injections results = performSearch(searchString); } // run the search and return the records found. private List<Contact> performSearch(string searchString) { //String[] tokens; //String accIds; List<Account> SudsidaryAccounts = [select Id from Account where Ultimate_Parent_Client__c =:ultiAccId and id!=null limit 10000]; List<String> accIds = new List<String>(); accIds.add(ultiAccId); for(Account acc : SudsidaryAccounts) { accIds.add(acc.Id); } List<contact> conts = [select id, name,AccountId,Email,Phone,Account.Name from Contact where Name LIKE: '%'+searchString +'%' and AccountId IN: accIds]; searchContactCount = conts.size(); return conts; } // save the new Contact record public PageReference saveContact() { insert Contact; // reset the Contact Contact = new Contact(); return null; } // used by the visualforce page to send the link to the right dom element public string getFormTag() { return System.currentPageReference().getParameters().get('frm'); } // used by the visualforce page to send the link to the right dom element for the text box public string getTextBox() { return System.currentPageReference().getParameters().get('txt'); } }
- SF7
- March 17, 2015
- Like
- 0
Error on VF ( An error occurred when processing your submitted information)
pg:j_id0:newContact:j_id52:j_id53:0:j_id54: An error occurred when processing your submitted information.
Hi,
I have a VF page for a Custom lookup and when i save the record a weird error is showing up . Any help please, after much research i found this happens sometimes due to Space issues and i already corrected all the Spaces and still i have the issue.
Hi,
I have a VF page for a Custom lookup and when i save the record a weird error is showing up . Any help please, after much research i found this happens sometimes due to Space issues and i already corrected all the Spaces and still i have the issue.
<apex:page controller="CustomContactLookupController" title="Search" showHeader="false" sideBar="false" tabStyle="Contact" id="pg"> <apex:form > <apex:outputPanel id="page" layout="block" style="margin:5px;padding:10px;padding-top:2px;"> <apex:tabPanel switchType="client" selectedTab="name1" id="tabbedPanel"> <!-- SEARCH TAB --> <apex:tab label="Contact Search" name="tab1" id="tabOne"> <apex:actionRegion > <apex:outputPanel id="top" layout="block" style="margin:1px;padding:10px;padding-top:2px;"> <apex:outputLabel value="{!$Label.OptyContRolePage_Search_Button}" style="font-weight:Bold;padding-right:10px;" for="txtSearch"/> <apex:inputText id="txtSearch" value="{!searchString}"/> <span style="padding-left:5px"> <apex:commandButton id="btnGo" value="{!$Label.OptyContRolePage_Go_Button}" action="{!Search}" rerender="searchResults"> </apex:commandButton> </span> </apex:outputPanel> <apex:outputPanel id="pnlSearchResults" style="margin:10px;height:350px;overflow-Y:auto;font-size:small" layout="block"> <apex:outputLabel value="{!$Label.OptyContRolePage_ResultSection}" style="font-weight:Bold;padding-right:10px;"/> <br/><br/> <apex:pageBlock id="searchResults" title="Contacts[{!searchContactCount}]"> <apex:pageBlockTable value="{!results}" var="a" id="tblResults"> <apex:column > <apex:facet name="header"> <apex:outputPanel >Name</apex:outputPanel> </apex:facet> <apex:outputLink value="javascript:top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.Name}',false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Name}</apex:outputLink> </apex:column> <apex:column > <apex:facet name="header"> <apex:outputPanel >Client Name</apex:outputPanel> </apex:facet> <apex:outputText value="{!a.Account.Name}" rendered="{!NOT(ISNULL(a.Id))}"/> </apex:column> <apex:column > <apex:facet name="header"> <apex:outputPanel >Phone</apex:outputPanel> </apex:facet> <apex:outputText value="{!a.Phone}" rendered="{!NOT(ISNULL(a.Id))}"/> </apex:column> <apex:column > <apex:facet name="header"> <apex:outputPanel >Email</apex:outputPanel> </apex:facet> <apex:outputText value="{!a.Email}" rendered="{!NOT(ISNULL(a.Id))}"/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> </apex:outputPanel> </apex:actionRegion> </apex:tab> <apex:tab label="New Contact" name="tab2" id="tabTwo"> <apex:pageBlock id="newContact" title="New Contact"> <apex:pageBlockButtons > <apex:commandButton action="{!saveContact}" value="Save"/> </apex:pageBlockButtons> <apex:pageMessages /> <apex:pageBlockSection columns="2"> <apex:repeat value="{!$ObjectType.Contact.FieldSets.CustomContactLookup}" var="f"> <apex:inputField value="{!Contact[f]}"/> </apex:repeat> </apex:pageBlockSection> </apex:pageBlock> </apex:tab> </apex:tabPanel> </apex:outputPanel> </apex:form> </apex:page>
public with sharing class CustomContactLookupController { public Contact Contact {get;set;} // new Contact to create public List<Contact> results{get;set;} // search results public string searchString{get;set;} // search keyword public Id ultiAccId; public Id localAccId; public Integer searchContactCount {get;set;} public CustomContactLookupController() { // get the current search string searchString = System.currentPageReference().getParameters().get('lksrch'); ultiAccId = System.currentPageReference().getParameters().get('ultimateAccId'); localAccId= System.currentPageReference().getParameters().get('localAccId'); runSearch(); } // performs the keyword search public PageReference search() { searchContactCount = 0; runSearch(); return null; } // prepare the query and issue the search command private void runSearch() { // TODO prepare query string for complex serarches & prevent injections results = performSearch(searchString); } // run the search and return the records found. private List<Contact> performSearch(string searchString) { //String[] tokens; //String accIds; List<Account> SudsidaryAccounts = [select Id from Account where Ultimate_Parent_Client__c =:ultiAccId and id!=null limit 10000]; List<String> accIds = new List<String>(); accIds.add(ultiAccId); for(Account acc : SudsidaryAccounts) { accIds.add(acc.Id); } List<contact> conts = [select id, name,AccountId,Email,Phone,Account.Name from Contact where Name LIKE: '%'+searchString +'%' and AccountId IN: accIds]; searchContactCount = conts.size(); return conts; } // save the new Contact record public PageReference saveContact() { insert Contact; // reset the Contact Contact = new Contact(); return null; } // used by the visualforce page to send the link to the right dom element public string getFormTag() { return System.currentPageReference().getParameters().get('frm'); } // used by the visualforce page to send the link to the right dom element for the text box public string getTextBox() { return System.currentPageReference().getParameters().get('txt'); } }
- SF7
- March 16, 2015
- Like
- 0
Need help in Writing a test Class for a Wrapper Class
hi ,
I have a Visual force for Creating a One Parent (Client_Discovery__c)and multiple Child (Client Site__c) records at a time . I am using a Standard Controller. I have a Wrapper class and need some help on the Test class.
Account - Opportunity - Client Discovery - Client Site
I have a Visual force for Creating a One Parent (Client_Discovery__c)and multiple Child (Client Site__c) records at a time . I am using a Standard Controller. I have a Wrapper class and need some help on the Test class.
Account - Opportunity - Client Discovery - Client Site
public class AddClientSite { ApexPages.StandardController sc; public Client_Discovery__c acct{get;set;} public Integer marker=2; public Integer selectedClientSite{get;set;} public List<WrapperClass> lClientSites{get;set;} public AddClientSite(ApexPages.StandardController controller) { this.acct = (Client_Discovery__c)controller.getRecord(); sc=controller; lClientSites=new List<WrapperClass>(); Client_Site__c c=new Client_Site__c(); lClientSites.add(new WrapperClass(c,1)); } public PageReference deleteClientSite(){ Integer x=-1; for(WrapperClass wc:lClientSites){ x++; if(wc.counter==selectedClientSite){ System.debug('-->selected ClientSite:'+selectedClientSite+' position:'+x); break; } } lClientSites.remove(x); return null; } public PageReference saveClientDiscovery(){ Database.SaveResult sr = Database.insert(acct, false); Id idey=sr.getId(); List<Client_Site__c> ClientSiteList=new List<Client_Site__c>(); for(WrapperClass wc:lClientSites){ Client_Site__c c=new Client_Site__c(); c.Client_Site_Name__c=wc.c.Client_Site_Name__c; c.City__c=wc.c.City__c; c.State__c=wc.c.State__c; c.Head_count__c=wc.c.Head_count__c; c.Number_of_Shifts__c=wc.c.Number_of_Shifts__c; c.Job_Titles__c=wc.c.Job_Titles__c; c.Number_of_On_Site_Managers__c=wc.c.Number_of_On_Site_Managers__c; c.Union_or_Non_Union__c=wc.c.Union_or_Non_Union__c; c.Number_of_Team_Leads__c=wc.c.Number_of_Team_Leads__c; c.Supplier_Name__c=wc.c.Supplier_Name__c; c.Skill_Type__c=wc.c.Skill_Type__c; c.Will_Manpower_Manage_This_Supplier_del__c=wc.c.Will_Manpower_Manage_This_Supplier_del__c; c.Is_This_a_New_or_Incumbent_Supplier__c=wc.c.Is_This_a_New_or_Incumbent_Supplier__c; c.Client_Discovery__c=idey; ClientSiteList.add(c); } insert ClientSiteList; return(new PageReference('/'+sr.id).setRedirect(True)); // return new PageReference('/' + Schema.getGlobalDescribe().get('Client_Discovery__c').getDescribe().getKeyPrefix() + '/o'); } public PageReference addAClientSite(){ Client_Site__c c=new Client_Site__c(); lClientSites.add(new WrapperClass(c,marker)); marker=marker+1; return null; } public class WrapperClass{ public Integer counter{get;set;} public Client_Site__c c{get;set;} public WrapperClass(Client_Site__c cntc,Integer i){ this.c=cntc; this.counter=i; } } }Right now its 0% Covered .
@isTest private class AddClientSiteTest { public static testMethod void AddClientSite() { Account a = new Account(name='TestOverrideClient one',BillingStreet='TestOverrideStone', Client_Short_Name__c ='ulttiCL', Phone='123454321',BillingState='ca', BillingPostalCode='95444', BillingCountry='US', BillingCity='TestOverrideOneCity', Ultimate_Parent__c = true); insert a; Opportunity o = new Opportunity(AccountId=a.Id,Name='testoppfornamechange',Solution_Type__c='sol1', Opportunity_Short_Description__c='test desc',Opportunity_Type__c='Parent', StageName='Plan & Engage', CloseDate=System.today()+2); Insert o; Client_Discovery__c CD = new Client_Discovery__c (Opportunity__c=o.id) ; Insert CD; Client_Site__c CS = new Client_Site__c(Client_Discovery__c = CD.id); Insert CS; } }
- SF7
- March 04, 2015
- Like
- 0
Cretae Parent and Child Records using 2 VF Pages
Hi ,
I have 2 obkects called Client Discovery and Client Site. I am using VF pages for both these objects . And user needs to fill in the first page and then click save and then he has to be redirected to the second VF page. And when user is in 2nd Vf page the Lookup field has to be filled with Parent Name(ID). [ Like we have account name pre filled while creating contacts ]
I have not written a Controller yet for this page and currently using Satndard controller only . I need to have a controller to get the Save and then redirect to the 2nd Vf page .
I have 2 obkects called Client Discovery and Client Site. I am using VF pages for both these objects . And user needs to fill in the first page and then click save and then he has to be redirected to the second VF page. And when user is in 2nd Vf page the Lookup field has to be filled with Parent Name(ID). [ Like we have account name pre filled while creating contacts ]
VISUALFORCE PAGE # 1 <apex:page standardController="Client_Discovery__c" standardStylesheets="true" > <apex:sectionHeader title="Client Discovery " subtitle="{!Client_Discovery__c.name}"/> <apex:form > <apex:pageBlock title="Large Client Sales Questions" mode="edit"> <apex:pageBlockButtons location="top"> <apex:commandButton value="Save" action="{!save}"/> <apex:commandButton value="Save & New" action="{!save}" /> <apex:commandButton value="Cancel" action="{!cancel}"/> </apex:pageBlockButtons> <apex:pageBlockButtons location="bottom"> <apex:commandButton value="Save" action="{!save}"/> <apex:commandButton value="Save & New" action="{!save}" /> <apex:commandButton value="Cancel" action="{!cancel}"/> </apex:pageBlockButtons> <apex:pageBlockSection title="Client Needs" columns="1"> <apex:panelGrid columns="2" style="white-space:nowrap;" > <Apex:outputlabel Value="What are the Client's pain points?" for="Question1" style="font-size:13px;font-family:arial;"/> <apex:inputField value="{!Client_Discovery__c.What_are_the_client_s_pain_points__c}" id="Question1" required="false" /> <Apex:outputlabel Value="List Other Client needs here" for="Question1-1" style="font-size:13px;font-family:arial;"/> <apex:inputField value="{!Client_Discovery__c.List_Other_client_needs_here__c}" id="Question1-1" required="false" /> </apex:panelGrid> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
I have not written a Controller yet for this page and currently using Satndard controller only . I need to have a controller to get the Save and then redirect to the 2nd Vf page .
Visual Force Page 2 <apex:page controller="ManageListController2" sidebar="false"> <apex:form > <apex:pageBlock title="Client Sites for Client Discovery"> <apex:pageBlockSection title="Client Site Details"> <apex:pageblockSectionItem > <apex:outputLabel value="Number of Client Sites" for="noofSites"></apex:outputLabel> <apex:inputText id="noofSites" value="{!noOfDays}"/> </apex:pageblockSectionItem> <apex:pageBlockSectionItem > <apex:commandButton value="Add Rows" action="{!addRows}" rerender="wtable"> <apex:param name="addCount" value="{!noOfDays}" assignTo="{!addCount}"/> </apex:commandButton> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockSection > <apex:pageBlockTable value="{!wrappers}" var="wrapper" id="wtable" columns="11" rows="20"> <tr> <apex:column headerValue="Ident"> <apex:outputText value="{!wrapper.ident}"/> </apex:column> <apex:column headerValue="Client Site Name"> <apex:inputField value="{!wrapper.acc.Client_Site_Name__c}"/> </apex:column> <apex:column headerValue="City"> <apex:inputField value="{!wrapper.acc.City__c}"/> </apex:column> <apex:column headerValue="State"> <apex:inputField value="{!wrapper.acc.State__c}"/> </apex:column> </tr> <apex:column headerValue="Headcount"> <apex:inputField value="{!wrapper.acc.Head_count__c}"/> </apex:column> <apex:column headerValue="Number of Shifts"> <apex:inputField value="{!wrapper.acc.Number_of_Shifts__c}"/> </apex:column> <apex:column headerValue="Job Titles"> <apex:inputField value="{!wrapper.acc.Job_Titles__c}"/> </apex:column> <apex:column headerValue="Number of On-Site Managers"> <apex:inputField value="{!wrapper.acc.Number_of_On_Site_Managers__c}"/> </apex:column> <apex:column headerValue="Union or Non union"> <apex:inputField value="{!wrapper.acc.Union_or_Non_Union__c}"/> </apex:column> <apex:column headerValue="Number of suppliers to manage"> <apex:inputField value="{!wrapper.acc.Number_of_Team_Leads__c}"/> </apex:column> <apex:column headerValue="Questionnaire"> <apex:inputField value="{!wrapper.acc.Client_Discovery__c}"/> </apex:column> <apex:column headerValue="Action"> <apex:commandButton value="Delete" action="{!delWrapper}" rerender="wtable"> <apex:param name="toDelIdent" value="{!wrapper.ident}" assignTo="{!toDelIdent}"/> </apex:commandButton> </apex:column> </apex:pageBlockTable> </apex:pageBlockSection> <!-- <apex:commandButton value="Add Row" action="{!addRows}" rerender="wtable"> <apex:param name="addCount" value="1" assignTo="{!addCount}"/> </apex:commandButton> --> <apex:commandButton value="Save" action="{!save}"/> </apex:pageBlock> </apex:form> </apex:page>
public class ManageListController2 { public String noOfDays { get; set; } public List<AccountWrapper> wrappers {get; set;} public static Integer toDelIdent {get; set;} public static Integer addCount {get; set;} private Integer nextIdent=1; public Client_Discovery__C opp{get; set;} public ManageListController2() { wrappers=new List<AccountWrapper>(); for (Integer idx=0; idx<0; idx++) { wrappers.add(new AccountWrapper(nextIdent++)); } } public void delWrapper() { Integer toDelPos=-1; for (Integer idx=0; idx<wrappers.size(); idx++) { if (wrappers[idx].ident==toDelIdent) { toDelPos=idx; } } if (-1!=toDelPos) { wrappers.remove(toDelPos); } } public void addRows() { addCount = Integer.valueOf(noOfDays); System.Debug('addCount ::: '+addCount); for (Integer idx=1; idx<=addCount; idx++) { wrappers.add(new AccountWrapper(nextIdent++)); } } public PageReference save() { List<Client_Site__C> accs=new List<Client_Site__C>( ); for (AccountWrapper wrap : wrappers) { accs.add(wrap.acc); } insert accs; return new PageReference('/' + Schema.getGlobalDescribe().get('Client_Site__c').getDescribe().getKeyPrefix() + '/o'); } public class AccountWrapper { public Client_Site__c acc {get; private set;} public Integer ident {get; private set;} public AccountWrapper(Integer inIdent) { ident=inIdent; acc=new Client_Site__C(); } } }
- SF7
- February 11, 2015
- Like
- 0
Render Related list only if the logged in user is the owner of the record
Hi ,
I am trying to have a VF page for the Contracts . Org wide everyone has view all Permissions and every one can create contracts but everyone cannot edit it . so i am trying to limit the view of Notes and attchmnets for 3 profiles and the owner of the record. I am succesful with the first part however i am not able to do the second part.So my question is
1. How can i use th render tag to check if the logged in user is the Owne rof the record.
2. Can i use rerender or If statement for the Edit button to check if the same conditions as above.
Thanks
Akhil
I am trying to have a VF page for the Contracts . Org wide everyone has view all Permissions and every one can create contracts but everyone cannot edit it . so i am trying to limit the view of Notes and attchmnets for 3 profiles and the owner of the record. I am succesful with the first part however i am not able to do the second part.So my question is
1. How can i use th render tag to check if the logged in user is the Owne rof the record.
2. Can i use rerender or If statement for the Edit button to check if the same conditions as above.
<apex:page standardController="Contract" extensions="ContractDetailExtensionController" id="thePage"> <apex:form > <apex:sectionHeader title="Contract" subtitle="{!Contract.name}"/> <apex:pageBlock title="Contract"> <apex:pageBlockButtons > <apex:commandButton value="{!$Label.conDetail_Edit}" action="{!edit}" /> <apex:commandButton value="{!$Label.conDetail_Delete}" action="{!delete}" /> </apex:pageBlockButtons> <apex:pageBlockSection title="Contract Information" columns="2"> <apex:outputField title="Contract Owner" value="{!Contract.OwnerId}"/> <apex:outputField title="Status" value="{!Contract.Status}"/> <apex:outputField title="Contract Number" value="{!Contract.ContractNumber}"/> <apex:outputField title="Contract Start Date" value="{!Contract.StartDate}"/> <apex:outputField title="Account Name" value="{!Contract.AccountId}"/> <apex:outputField title="Contract Term (months)" value="{!Contract.ContractTerm}"/> <apex:outputField title="Customer Signed By" value="{!Contract.CustomerSignedId}"/> <apex:outputField title="Owner Expiration Notice" value="{!Contract.OwnerExpirationNotice}"/> <apex:outputField title="Customer Signed Title" value="{!Contract.CustomerSignedTitle}"/> <apex:outputField title="Company Signed By" value="{!Contract.CompanySignedId}"/> <apex:outputField title="Customer Signed Date" value="{!Contract.CustomerSignedDate}"/> <apex:outputField title="Company Signed Date" value="{!Contract.CompanySignedDate}"/> </apex:pageBlockSection> <apex:pageBlockSection title="Address Information" columns="2"> <apex:outputField title="Billing Street" value="{!Contract.BillingStreet}"/> <apex:outputField title="Billing City" value="{!Contract.BillingCity}"/> <apex:outputField title="Billing State/Province" value="{!Contract.BillingState}"/> <apex:outputField title="Billing Zip/Postal Code" value="{!Contract.BillingPostalCode}"/> <apex:outputField title="Billing Country" value="{!Contract.BillingCountry}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> <apex:relatedList list="CombinedAttachments" rendered="{!Checkprofiles}"/> <apex:relatedList list="OpenActivities" /> <apex:relatedList list="ActivityHistories" /> </apex:page>
public with sharing class ContractDetailExtensionController { private final Contract contract; public ContractDetailExtensionController(ApexPages.StandardController stdController) { this.contract = (Contract)stdController.getRecord(); } public Boolean getCheckprofiles() { List<Profile> Prof; Prof = [Select id from Profile where Name = 'System Administrator' or Name = 'L2 Support' or Name='Sales Manager - RM']; for(Profile p :Prof) { if (UserInfo.getProfileId()== p.Id) return true; } return false; } }
Thanks
Akhil
- SF7
- January 29, 2015
- Like
- 0
Parent Look Up Field In Visual Force page
I have two Objects , Client Discovery and Client Site . Client Site is having a Master Detail RelationShip with Client Discovery. Client discovery can have many Sites. So i created a visual force page to insert Client Discovery and on the same page using Add row functionality gave option to Create Client Sites. And when i hit save there is an error saying required fields are missing As by that Client Discovery is not yet created .
<apex:page StandardController="Client_Discovery__c" extensions="MultiAdd1" id="thePage" sidebar="false"> <apex:sectionHeader title="Client Discovery " subtitle="{!Client_Discovery__c.name}"/> <apex:form > <apex:pageblock id="pb" title="Large Client Sales Questions"> <apex:pageBlockButtons > <apex:commandbutton value="Add Client Site" action="{!Add}" rerender="pb1"/> <apex:commandbutton value="Save " action="{!Save}"/> <apex:commandButton value="Cancel" action="{!cancel}"/> </apex:pageBlockButtons> <apex:pageBlockSection title="Client Needs" columns="1"> <apex:panelGrid columns="2" style="white-space:nowrap;" > <Apex:outputlabel Value="What are the client's pain points?" for="Question1" style="font-size:11px;font-family:arial;"/> <apex:inputField value="{!Client_Discovery__c.What_are_the_client_s_pain_points__c}" id="Question1" required="false" /> </apex:panelGrid> </apex:pageBlockSection> <apex:pageblock id="pb1" title="Client Site"> <apex:repeat value="{!lstInner}" var="e1" id="therepeat"> <apex:panelGrid columns="7"> <apex:panelGrid headerClass="Name"> <apex:facet name="header">Del</apex:facet> <apex:commandButton value="X" action="{!Del}" rerender="pb1"> <apex:param name="rowToBeDeleted" value="{!e1.recCount}" assignTo="{!selectedRowIndex}"></apex:param> </apex:commandButton> </apex:panelGrid> <apex:panelGrid title="SPD" > <apex:facet name="header">Client Site Name</apex:facet> <apex:inputfield value="{!e1.acct.Client_Site_Name__c}"/> </apex:panelGrid> <apex:panelGrid > <apex:facet name="header">City</apex:facet> <apex:inputfield value="{!e1.acct.City__c}"/> </apex:panelGrid> <apex:panelGrid > <apex:facet name="header">State</apex:facet> <apex:inputfield value="{!e1.acct.State__c}"/> </apex:panelGrid> <apex:panelGrid title="SPD" > <apex:facet name="header">Headcount</apex:facet> <apex:inputfield value="{!e1.acct.Head_count__c}"/> </apex:panelGrid> <apex:panelGrid > <apex:facet name="header">Number of Shifts</apex:facet> <apex:inputfield value="{!e1.acct.Number_of_Shifts__c}"/> </apex:panelGrid> <apex:panelGrid > <apex:facet name="header">Job Titles</apex:facet> <apex:inputfield value="{!e1.acct.Job_Titles__c}"/> </apex:panelGrid> </apex:panelgrid> </apex:repeat> </apex:pageBlock> </apex:pageblock> </apex:form> </apex:page>
public class MultiAdd1 { //will hold the account records to be saved public List<Client_Site__c>lstAcct = new List<Client_Site__c>(); //list of the inner class public List<innerClass> lstInner { get;set; } //will indicate the row to be deleted public String selectedRowIndex {get;set;} //no. of rows added/records in the inner class list public Integer count = 1; //{get;set;} ////save the records by adding the elements in the inner class list to lstAcct,return to the same page public PageReference Save() { PageReference pr = new PageReference('/apex/MultiAdd'); for(Integer j = 0;j<lstInner.size();j++) { lstAcct.add(lstInner[j].acct); } insert lstAcct; pr.setRedirect(True); return pr; } //add one more row public void Add() { count = count+1; addMore(); } /*Begin addMore*/ public void addMore() { //call to the iner class constructor innerClass objInnerClass = new innerClass(count); //add the record to the inner class list lstInner.add(objInnerClass); system.debug('lstInner---->'+lstInner); }/* end addMore*/ /* begin delete */ public void Del() { system.debug('selected row index---->'+selectedRowIndex); lstInner.remove(Integer.valueOf(selectedRowIndex)-1); count = count - 1; }/*End del*/ /*Constructor*/ public MultiAdd1(ApexPages.StandardController ctlr) { lstInner = new List<innerClass>(); addMore(); selectedRowIndex = '0'; }/*End Constructor*/ /*Inner Class*/ public class innerClass { /*recCount acts as a index for a row. This will be helpful to identify the row to be deleted */ public String recCount {get;set;} public Client_Site__c acct {get;set;} /*Inner Class Constructor*/ public innerClass(Integer intCount) { recCount = String.valueOf(intCount); /*create a new account*/ acct = new Client_Site__c(); }/*End Inner class Constructor*/ }/*End inner Class*/ }/*End Class*/
- SF7
- January 26, 2015
- Like
- 0
Trigger to Get the latest Created Date on a Parent Object from the child object
Hi ,
I have a trigger to get the fields from Child object to parent object and i was able to succesfullt get all the information i need . Only part i was missing is when i try to get the recently created record created date it gives me the oldest (first created record ) .
Akhil
I have a trigger to get the fields from Child object to parent object and i was able to succesfullt get all the information i need . Only part i was missing is when i try to get the recently created record created date it gives me the oldest (first created record ) .
trigger ContactAlerts on ET4AE__IndividualEmailResult__c (after insert, after update) { Map<ID, Contact> ConToUpdate = new Map<ID, Contact>(); List<Id> listIds = new List<Id>(); Boolean isExists = false; list<ET4AE__IndividualEmailResult__c> EmailList = new list<ET4AE__IndividualEmailResult__c>(); for (ET4AE__IndividualEmailResult__c childObj : Trigger.new){ listIds.add(childObj.ET4AE__Contact__c); } ConToUpdate = new Map<Id, Contact>([SELECT id, ET_Clicked_Atleat_Once__c ,ET_Hard_bounce__c,ET_Unsubscribed__c,(SELECT ID,CreatedDate,ET4AE__DateUnsubscribed__c, ET4AE__HardBounce__c,ET4AE__NumberOfTotalClicks__c FROM ET4AE__IndividualEmailResults__r) FROM Contact WHERE ID IN :listIds]); for (Contact Con: ConToUpdate.values()){ isExists = false; for(ET4AE__IndividualEmailResult__c IER :Con.ET4AE__IndividualEmailResults__r){ if(IER.ET4AE__NumberOfTotalClicks__c == 1){ Con.ET_Clicked_Atleat_Once__c = 1; isExists = true; } if(isExists == false) { Con.ET_Clicked_Atleat_Once__c = 0; } if(IER.ET4AE__HardBounce__c == True){ Con.ET_Hard_bounce__c = true; } if(IER.ET4AE__DateUnsubscribed__c != null){ Con.ET_Unsubscribed__c = true; } if(IER.CreatedDate != null){ Con.ET_Last_Email_Sent_date__c = IER.CreatedDate; } } }Thanks,
Akhil
- SF7
- December 11, 2014
- Like
- 0
Redirect to a Standard new page From a visual force page
HI ,
I have a VF page on OpportunityContactRole and when user click AddContactRole Button from Opportunity a new page opens and users can search and add the contacts to the opportunity. However if the contact they are searching for is not found then i would like them to add the contact from there itself and then add that contact to the Opportunity.
So i would need to open a new page (window) when they click the button New Contact from the VF page and they should create a contact and save it and when done they should be back on the VF page and contunie adding the contact they cretaed to the Opportunity.
So i cretaed a new button on the VF page and it redirects to the contact but problem is it is not opening in the new window . Do i need to add Java Script for that .
Here is the code i added
<apex:commandButton value="Save" action="{!Save}" id="quickSavebutton"/>
<apex:commandButton value="Cancel" action="{!cancel}"/>
<apex:CommandButton action="{!NewContact}" value="New Contact" />
public PageReference NewContact() {
PageReference OpenPage = new PageReference ('/003/e');
OpenPage.setRedirect(true);
return OpenPage;
}
Thanks
I have a VF page on OpportunityContactRole and when user click AddContactRole Button from Opportunity a new page opens and users can search and add the contacts to the opportunity. However if the contact they are searching for is not found then i would like them to add the contact from there itself and then add that contact to the Opportunity.
So i would need to open a new page (window) when they click the button New Contact from the VF page and they should create a contact and save it and when done they should be back on the VF page and contunie adding the contact they cretaed to the Opportunity.
So i cretaed a new button on the VF page and it redirects to the contact but problem is it is not opening in the new window . Do i need to add Java Script for that .
Here is the code i added
<apex:commandButton value="Save" action="{!Save}" id="quickSavebutton"/>
<apex:commandButton value="Cancel" action="{!cancel}"/>
<apex:CommandButton action="{!NewContact}" value="New Contact" />
public PageReference NewContact() {
PageReference OpenPage = new PageReference ('/003/e');
OpenPage.setRedirect(true);
return OpenPage;
}
Thanks
- SF7
- October 15, 2014
- Like
- 0
Trigger to Update Manager Filed 4 users without Manage Users
I have added a custom lookup field on user object and if users update that field then it update Standard Manger field ( which is not accessible to them without Manage user permission) . And my trigger works great and the problem is when we need to deactivate the user it throws me a error saying the user is a manager for other users. and i need to go and remove them . But in Standard functionlity it doesnt happen that way. And if i try to remove the manager info from custom field then it even remove the info from standard field and i am ultimately losing all the information. Any suggestions please
trigger UserManagerUpdate on User(before insert, before update) {
if (trigger.isInsert || trigger.isUpdate) {
for (User myUser: Trigger.New) {
myUser.ManagerId = myUser.Manager__c;
}
}
}
Thanks
Akhil
trigger UserManagerUpdate on User(before insert, before update) {
if (trigger.isInsert || trigger.isUpdate) {
for (User myUser: Trigger.New) {
myUser.ManagerId = myUser.Manager__c;
}
}
}
Thanks
Akhil
- SF7
- October 14, 2014
- Like
- 0
Test Class Coverage issue
trigger ConversionRate on OpportunityLineItem (before insert, before update) { List<String> LineofBusiness = new List<String>(); for (OpportunityLineItem a:Trigger.new) { LineofBusiness.add(a.Hidden_Name__c); } List <Win_Rate__c> WinRateList = [Select ID,Name, Line_of_Business__c,Country__C from Win_Rate__c where Name in :LineofBusiness]; for (Integer i = 0; i <Trigger.new.size(); i++){ if (WinRateList.size() > 0 && Trigger.new[i].Hidden_Name__c !=null) { for (Win_Rate__c W:WinRateList){ if (Trigger.new[i].Hidden_Name__c == W.name){ Trigger.new[i].WinRate__c= W.ID; } } } else{ Trigger.new[i].WinRate__c = null; } } }
@isTest(seeAllData=true) private class TestConversionRate { @isTest static void MyUnitTest() { // Set up some local variables String opportunityName = 'My Opportunity'; String standardPriceBookId = ''; PriceBook2 pb2Standard = [select Id from Pricebook2 where isStandard=true]; standardPriceBookId = pb2Standard.Id; Account a = new Account(Name = 'Berlington'); Insert a; // set up opp and Verify that the results are as expected. Opportunity o = new Opportunity(AccountId = a.id, Name=opportunityName, StageName='Discovery', CloseDate=Date.today()); insert o; Opportunity opp = [SELECT Name FROM Opportunity WHERE Id = :o.Id]; //System.assertEquals(opportunityName, 'Berlington - 0 -'); // set up product2 and Verify that the results are as expected. Product2 p2 = new Product2(Name='Test Product',isActive=true); insert p2; Product2 p2ex = [SELECT Name FROM Product2 WHERE Id = :p2.Id]; //System.assertEquals('Test Product', p2ex.Name); // set up PricebookEntry and Verify that the results are as expected. PricebookEntry pbe = new PricebookEntry(Pricebook2Id=standardPriceBookId, Product2Id=p2.Id, UnitPrice=99, isActive=true); insert pbe; PricebookEntry pbeex = [SELECT Pricebook2Id FROM PricebookEntry WHERE Id = :pbe.Id]; //System.assertEquals(standardPriceBookId, pbeex.Pricebook2Id); Win_Rate__c w = new Win_Rate__c(Name = 'Manpower - Brazil - 121-180',Win_rate__c = 90 ); Insert W; // set up OpportunityLineItem and Verify that the results are as expected. OpportunityLineItem oli = new OpportunityLineItem(PriceBookEntryId=pbe.Id, OpportunityId=o.Id,WinRate__c = w.id, Quantity=1, TotalPrice=99); insert oli; OpportunityLineItem oliex = [SELECT PriceBookEntryId FROM OpportunityLineItem WHERE Id = :oli.Id]; System.assertEquals(pbe.Id, oliex.PriceBookEntryId); opportunityLineItem Oppl = [Select Id,Name ,WinRate__c from OpportunityLineItem where id =:oli.id]; system.assertnotEquals(oppl.WinRate__c ,''); }
Only Getting 70% and any insight what i am missing?
- SF7
- July 09, 2014
- Like
- 0
Trigger to create multiple child records when a parent is created
Hi ,
i am tryinng to create multiple child records when a parent record is created . The records in child object should be coming from an another relaetd object . Here is my data model
Data model 1: Account (Parent)<<<<<< Invoices (Child)
Date Model 2 : Account (Master Parent)<<<<<<Payment(Parent)<<<<<<Payment Line Items (Child) <<<<<< Invoices
Example Salesforce is my account and it has 20 Invoices , now i am creating a Payment ( notthing related to invoice at this time ) record and when i save this payment record 20 payment line items should be created. One record for each invoice salesforce account has .
I can create a child to a parent automatically but not sure how to create mutiple child records based on the Invoices object .
Here is the start with able to create single child record
Thanks,
Akhil
i am tryinng to create multiple child records when a parent record is created . The records in child object should be coming from an another relaetd object . Here is my data model
Data model 1: Account (Parent)<<<<<< Invoices (Child)
Date Model 2 : Account (Master Parent)<<<<<<Payment(Parent)<<<<<<Payment Line Items (Child) <<<<<< Invoices
Example Salesforce is my account and it has 20 Invoices , now i am creating a Payment ( notthing related to invoice at this time ) record and when i save this payment record 20 payment line items should be created. One record for each invoice salesforce account has .
I can create a child to a parent automatically but not sure how to create mutiple child records based on the Invoices object .
Here is the start with able to create single child record
trigger CreatePaymentLineItems on Payment__c (after insert) { List<Payment_Item__c> PItem = new List<Payment_Item__c>(); for (Payment__c Pay : trigger.new) { Payment_Item__c PBI = new Payment_Item__c(); PBI.Payment__c = Pay.Id; // PBI.Financial__c = Pay.; PItem.add(PBI); } insert PItem; }
Thanks,
Akhil
- SF7
- April 05, 2016
- Like
- 1
Help with Trigger on Attachments
I am trying to get the latest attachment id on to the case object fields based on the Name of the document . I have 2 fields on cases ( A,X)and If an attachement is added to case with the name ABC then its Id should be filled in Filed A on case and if Attachment is added with Name XYZ then Field X on the case should be filled with the ID of XYZ. If there are mutiple attachments with the same name then we should take the latest attachment.
I am trying this below way and it is able to bring in Att.Name or Att. ParentID but for some reason it could not bring in the Att.id field . And i still have to include by date condition
I am trying this below way and it is able to bring in Att.Name or Att. ParentID but for some reason it could not bring in the Att.id field . And i still have to include by date condition
trigger CaseAttachment on Attachment (before insert) { Boolean isCaseAttachment = FALSE; List<Case> Cases = new List<Case>(); Set<Id> accIds = new Set<Id>(); for(Attachment att : trigger.New){ /*Check if uploaded attachment is related to Case Attachment and same Case is already added*/ if(att.ParentId.getSobjectType() == Case.SobjectType && (!accIds.contains(att.ParentId)) && att.Name.contains('XYZ')){ //prepare a Case object for update Cases.add( new Case( Id=att.ParentId, A__c= att.ID ) ); //add the Caseid in set to eliminate dupe updates accIds.add(att.ParentId); } if(att.ParentId.getSobjectType() == Case.SobjectType && (!accIds.contains(att.ParentId)) && att.Name.contains('ABC')){ //prepare a Case object for update Cases.add( new Case( Id=att.ParentId, X__c = att.ID ) ); //add the Caseid in set to eliminate dupe updates accIds.add(att.ParentId); } } //finally update Cases update Cases; }
- SF7
- July 29, 2016
- Like
- 0
Auto Clone and create 2 new orders when an existing order is updated with a different status
<apex:commandButton value="Submit Order" action="{!submitOrder}" rendered="{!isOrderSubmitable}" reRender="pgBlock" onclick="if ( !confirm('{!$Label.CCMTY_Submit_Msg}') ){return false;}" status="status" /> public PageReference submitOrder(){ PageReference pr = null; try{ // Calculate the time Difference between Qoute Submition to uptil now Order ordTemp = [select Quote_Created_Date__c from Order where id =:orderRecord.ID]; Double qouteSubmitTimeDiff = double.valueOf(((System.now().getTime())/1000/60/60) - ((ordTemp.Quote_Created_Date__c.getTime())/1000/60/60)); // Don't process the order with 24hrs older qoutes. if(qouteSubmitTimeDiff > 24){ addErrorMessage(Label.ErrorMsg_QuoteExpired); return pr; } eiJcCreateOrderServices.createOrderRequestType cor = new eiJcCreateOrderServices.createOrderRequestType(); cor.orderNumber = CCMTY_StringUtil.stripRegionFromId(this.orderRecord.Order_Quote_Number__c); eiJcCreateOrderServices.PSCreateOrderSOAP osp = new eiJcCreateOrderServices.PSCreateOrderSOAP(); osp.inputHttpHeaders_x = new Map<String, String>{'apikey' => CCMTY_Settings__c.getInstance().EI_API_Key__c}; osp.timeout_x = 60000; eiJcCreateOrderServices.createOrderResponseType restp;// = osp.createOrder(cor.orderNumber); restp = osp.createOrder(cor.orderNumber); System.debug(restp); System.debug('restp.orderNumber: ' + restp.orderNumber); if( !String.isBlank(restp.orderNumber) ) { this.orderRecord.Order_External_Key__c = this.orderRecord.Order_Region__c + '-' + restp.orderNumber; this.orderRecord.Status = 'Submitted'; this.orderRecord.Order_Submit_Date__c = System.today(); System.debug('order rebate total:'+orderRecord.Order_Total_Rebate__c+' status:'+orderRecord.Status); update this.orderRecord; List<OrderItem> orderItems = [select Order_Products_Line_Number__c from OrderItem where OrderId = :this.orderRecord.Id]; for ( OrderItem oi : orderItems ) { oi.Order_Products_External_Key__c = this.orderRecord.Order_External_Key__c + '-' + oi.Order_Products_Line_Number__c; } update orderItems; if(test.isRunningTest()) { orderRecord = [Select accountId, Order_Total_Rebate__c,Status,OrderNumber, (Select id,name, Order_Discount_Value__c,Order_Discount_Type__c from Order_Discounts__r ) from order where id=: ordTemp.Id limit 1 ]; } System.debug('order rebate total:'+orderRecord.Order_Total_Rebate__c+' status:'+orderRecord.Status+' this.orderRecord.Order_Discounts__r:'+this.orderRecord.Order_Discounts__r); if(orderRecord.Order_Total_Rebate__c > 0 && orderRecord.Status.equals('Submitted')) { List<Rebate_Transaction__c> rebateTransactions = new List<Rebate_Transaction__c>(); System.debug('this.orderRecord.Order_Discounts__r: ' + this.orderRecord.Order_Discounts__r); for ( Order_Discount__c od : this.orderRecord.Order_Discounts__r ) { if ( od.Order_Discount_Type__c == 'Rebate' ) { Decimal startingBal = (rebateTypesAvailableAmtMap.get(od.Name) != null)? rebateTypesAvailableAmtMap.get(od.Name) : 0 ; rebateTransactions.add(getRebateConsumedRecord(od.Name, od.Order_Discount_Value__c,startingBal, (startingBal - od.Order_Discount_Value__c))); } } insert rebateTransactions; } pr = new PageReference( '/' + this.getOrderKeyPrefix() ); pr.getParameters().put('feedback', 'OrderSubmitted'); pr.getParameters().put('orderNumber', this.orderRecord.OrderNumber); pr.getParameters().put('selectedFilterId', CCMTY_Settings__c.getInstance().Orders_Default_List_View_ID__c); } }catch( DmlException e){ this.orderRecord.Order_Submit_Date__c = null; this.addGenericErrorMessage(); } return pr; }
// This is another class which Auto Clones the Order when a clone button is clicked on the Front end maully by the user . <apex:page standardController="Order" extensions="OrderCloneWithItemsController" action="{!cloneWithItems}"> <apex:pageMessages /> </apex:page> public class OrderCloneWithItemsController { //added an instance varaible for the standard controller private ApexPages.StandardController controller {get; set;} // add the instance for the variables being passed by id on the url private Order po {get;set;} // set the id of the record that is created -- ONLY USED BY THE TEST CLASS public ID newRecordId {get;set;} // initialize the controller public OrderCloneWithItemsController(ApexPages.StandardController controller) { //initialize the stanrdard controller this.controller = controller; // load the current record po = (Order)controller.getRecord(); } // method called from the VF's action attribute to clone the po public PageReference cloneWithItems() { // setup the save point for rollback Savepoint sp = Database.setSavepoint(); Order newPO; try { //copy the purchase order - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE po = [select Id, Name, accountId, Order_Total_Rebate__c,EffectiveDate,Status,Order_Region__c,OrderNumber,Order_ShipTo_Address__c,CurrencyIsoCode , PoNumber, Order_Requested_Delivery_Date__c ,Order_Comments__c, Pricebook2Id from Order where id = :po.id]; newPO = po.clone(false); insert newPO; // set the id of the new po created for testing newRecordId = newPO.id; // copy over the line items - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE List<OrderItem> items = new List<OrderItem>(); for (OrderItem pi : [Select p.Id, p.UnitPrice,p.Price_Book_External_Key__C, p.Quantity,p.Order_Products_Line_Number__c,p.Description,p.Brand__c,p.PricebookEntryId From OrderItem p where OrderId = :po.id]) { OrderItem newPI = pi.clone(false); newPI.OrderId = newPO.id; items.add(newPI); } insert items; } catch (Exception e){ // roll everything back in case of error Database.rollback(sp); ApexPages.addMessages(e); return null; } return new PageReference('/'+newPO.id+'/e?retURL=%2F'+newPO.id); } }I want to auto clone and create 2 new orders from an existing order when the Order is submitted (Status on order is changed to Submitted ).
I was able to cretae a button from the front end and clone the records but i want this clone called from the first class and create the records without manul intervention like clicking the clone button.
Thanks
- SF7
- April 12, 2016
- Like
- 0
Trigger to create multiple child records when a parent is created
Hi ,
i am tryinng to create multiple child records when a parent record is created . The records in child object should be coming from an another relaetd object . Here is my data model
Data model 1: Account (Parent)<<<<<< Invoices (Child)
Date Model 2 : Account (Master Parent)<<<<<<Payment(Parent)<<<<<<Payment Line Items (Child) <<<<<< Invoices
Example Salesforce is my account and it has 20 Invoices , now i am creating a Payment ( notthing related to invoice at this time ) record and when i save this payment record 20 payment line items should be created. One record for each invoice salesforce account has .
I can create a child to a parent automatically but not sure how to create mutiple child records based on the Invoices object .
Here is the start with able to create single child record
Thanks,
Akhil
i am tryinng to create multiple child records when a parent record is created . The records in child object should be coming from an another relaetd object . Here is my data model
Data model 1: Account (Parent)<<<<<< Invoices (Child)
Date Model 2 : Account (Master Parent)<<<<<<Payment(Parent)<<<<<<Payment Line Items (Child) <<<<<< Invoices
Example Salesforce is my account and it has 20 Invoices , now i am creating a Payment ( notthing related to invoice at this time ) record and when i save this payment record 20 payment line items should be created. One record for each invoice salesforce account has .
I can create a child to a parent automatically but not sure how to create mutiple child records based on the Invoices object .
Here is the start with able to create single child record
trigger CreatePaymentLineItems on Payment__c (after insert) { List<Payment_Item__c> PItem = new List<Payment_Item__c>(); for (Payment__c Pay : trigger.new) { Payment_Item__c PBI = new Payment_Item__c(); PBI.Payment__c = Pay.Id; // PBI.Financial__c = Pay.; PItem.add(PBI); } insert PItem; }
Thanks,
Akhil
- SF7
- April 05, 2016
- Like
- 1
Save and New- Need to redirect to Same VF Page with parent ID
Hi ,
I have a Visual force page and Need a Custom Save and New Functionality,
Opportunity (Parent Object) ------- Client_Discovery__C (Child Object) ,
Client_Discovery__C (Parent Object) ----- Client_Site__C (Child Object)
Client_Site__C (Parent Object) ------ Client Supplier (Child Object)
What i am trying to achive with my visual force page is , On Opportunity related list i have New Client Disovery Button withich is Standard Visual Page.
When user Clicks New Client Disocvery and enters data
and hits save page is Redirected to new Visual Force page where users can create Client Site and Multipole Supplier at the Same time .
Here when user finishes enetring data He needs to hit Save & New and again go to the same VF page where he just hit save & new . I am able to redirect to that page but missing the Parent ID.
First Vf Page Standard page ClientQuestionarrie with Custom Save method in Client Questionarrie Controller.
Missing Client Disovery ID
Thanks
Akhil
I have a Visual force page and Need a Custom Save and New Functionality,
Opportunity (Parent Object) ------- Client_Discovery__C (Child Object) ,
Client_Discovery__C (Parent Object) ----- Client_Site__C (Child Object)
Client_Site__C (Parent Object) ------ Client Supplier (Child Object)
What i am trying to achive with my visual force page is , On Opportunity related list i have New Client Disovery Button withich is Standard Visual Page.
When user Clicks New Client Disocvery and enters data
and hits save page is Redirected to new Visual Force page where users can create Client Site and Multipole Supplier at the Same time .
Here when user finishes enetring data He needs to hit Save & New and again go to the same VF page where he just hit save & new . I am able to redirect to that page but missing the Parent ID.
First Vf Page Standard page ClientQuestionarrie with Custom Save method in Client Questionarrie Controller.
public with sharing class ClientQuestionarrie { Apexpages.StandardController controller; public Client_Discovery__c myCustomObject; public ClientQuestionarrie(ApexPages.StandardController sc) { this.controller = sc; myCustomObject = (Client_Discovery__c) sc.getRecord(); } public PageReference SaveQuestionarrie() { upsert myCustomObject; Pagereference ref = new Pagereference('/Apex/ClientSite'); ref.getParameters().put('Client_Discovery__c', myCustomObject.Id); ref.setRedirect(true); return ref; } }
public with sharing class ClientSiteExt { public ClientSiteExt(ApexPages.StandardController controller) { Client_Site__c c = (Client_Site__c) controller.getRecord(); c.Client_Discovery__c = ApexPages.currentPage().getParameters().get('Client_Discovery__c'); } }
<apex:page standardController="Client_Site__c" extensions="AddClientSupplier,ClientSiteExt" tabStyle="Client_Site__c"> <apex:form id="myForm" > <apex:sectionHeader title="New Client Site" /> <apex:pageBlock title=" Client Site Edit" mode="edit"> <apex:pageBlockButtons location="top" > <apex:commandButton value="Save" action="{!saveClientSite}" /> <apex:commandButton value="Save & New" action="{!SaveAndNew}"/> <apex:commandButton value="Cancel" action="{!Cancel}"/> </apex:pageBlockButtons> <apex:pageBlockSection title="Information" columns="2"> <apex:inputField value="{!Client_Site__c.Client_Site_Name__c}" taborderhint="1"/> <apex:inputField value="{!Client_Site__c.Client_Discovery__c}" taborderhint="6"/> <apex:inputField value="{!Client_Site__c.City__c}" taborderhint="2"/> <apex:inputField value="{!Client_Site__c.Number_of_Shifts__c}" taborderhint="7"/> <apex:inputField value="{!Client_Site__c.State__c}" taborderhint="3"/> <apex:inputField value="{!Client_Site__c.Number_of_Team_Leads__c}" taborderhint="8"/> <apex:inputField value="{!Client_Site__c.Head_count__c}" taborderhint="4"/> <apex:inputField value="{!Client_Site__c.Number_of_On_Site_Managers__c}" taborderhint="9"/> <apex:inputField value="{!Client_Site__c.Job_Titles__c}" taborderhint="5"/> <apex:inputField value="{!Client_Site__c.Union_or_Non_Union__c}" taborderhint="10"/> </apex:pageBlockSection> <apex:pageBlockSection title="Client Suppliers" columns="4"> </apex:pageBlockSection> <apex:repeat value="{!lClientSuppliers}" var="x"> <apex:panelGrid columns="6"> <apex:panelGrid > <apex:facet name="header">Client Supplier Name</apex:facet> <apex:inputField value="{!x.c.Supplier_Name__c}" style="width:200px" /> </apex:panelGrid> <apex:panelGrid > <apex:facet name="header">Is This a New or Incumbent Supplier?y</apex:facet> <apex:inputField value="{!x.c.Is_This_a_New_or_Incumbent_Supplier__c}" style="width:200px" /> </apex:panelGrid> <apex:panelGrid > <apex:facet name="header">Skill Type</apex:facet> <apex:inputField value="{!x.c.Skill_Type__c}" style="width:200px"/> </apex:panelGrid> <apex:panelGrid > <apex:facet name="header"> Will Manpower manage this supplier?</apex:facet> <apex:inputField value="{!x.c.Will_Manpower_Manage_This_Supplier__c}" style="width:200px" /> </apex:panelGrid> <apex:panelGrid > </apex:panelGrid> <apex:commandButton action="{!deleteClientSupplier}" style="Button" value="Delete ClientSite" reRender="myForm" immediate="true"> <apex:param value="{!x.counter}" name="selected" assignTo="{!selectedContact}"/> </apex:commandButton> </apex:panelGrid> </apex:repeat> <apex:pageBlockButtons location="bottom"> <apex:panelGrid ></apex:panelGrid> <apex:commandButton value="Add Client Supplier" action="{!addAClientSupplier}" reRender="myForm" immediate="true" /> <apex:commandButton value="Save" action="{!saveClientSite}" /> <apex:commandButton value="Cancel" action="{!cancel}"/> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page>
public class AddClientSupplier { ApexPages.StandardController sc; public Client_Site__c acct{get;set;} public Client_Discovery__c cDiscovery; public Integer marker=2; public Integer selectedClientSupplier{get;set;} public List<WrapperClass> lClientSuppliers{get;set;} public String queryString {get;set;} public AddClientSupplier(ApexPages.StandardController controller) { sc=controller; this.acct = (Client_Site__c)controller.getRecord(); lClientSuppliers=new List<WrapperClass>(); Client_Supplier__c c=new Client_Supplier__c(); lClientSuppliers.add(new WrapperClass(c,1)); } public PageReference deleteClientSupplier(){ Integer x=-1; for(WrapperClass wc:lClientSuppliers){ x++; if(wc.counter==selectedClientSupplier){ System.debug('-->selected ClientSupplier:'+selectedClientSupplier+' position:'+x); break; } } lClientSuppliers.remove(x); return null; } public PageReference saveClientSite(){ Database.SaveResult sr = Database.insert(acct, false); Id idey=sr.getId(); List<Client_Supplier__c> ClientSupplierList=new List<Client_Supplier__c>(); for(WrapperClass wc:lClientSuppliers){ if(!string.isblank(wc.c.Supplier_Name__c) ){ Client_Supplier__c c=new Client_Supplier__c(); c.Is_This_a_New_or_Incumbent_Supplier__c=wc.c.Is_This_a_New_or_Incumbent_Supplier__c; c.Skill_Type__c=wc.c.Skill_Type__c; c.Supplier_Name__c=wc.c.Supplier_Name__c; c.Will_Manpower_Manage_This_Supplier__c=wc.c.Will_Manpower_Manage_This_Supplier__c; c.Client_Site__c=idey; ClientSupplierList.add(c); } } insert ClientSupplierList; return(new PageReference('/'+sr.id).setRedirect(True)); // return new PageReference('/' + Schema.getGlobalDescribe().get('Client_Discovery__c').getDescribe().getKeyPrefix() + '/o'); } public PageReference addAClientSupplier(){ Client_Supplier__c c=new Client_Supplier__c(); lClientSuppliers.add(new WrapperClass(c,marker)); marker=marker+1; return null; } public class WrapperClass{ public Integer counter{get;set;} public Client_Supplier__c c{get;set;} public WrapperClass(Client_Supplier__c cntc,Integer i){ this.c=cntc; this.counter=i; } } public PageReference saveAndNew() { sc.save(); PageReference pRef = Page.ClientSite; pRef.setRedirect(true); //pRef.getParameters().put('Client_Discovery__c', cDiscovery.id); return pRef; } }When i Hit Save and New
Missing Client Disovery ID
Thanks
Akhil
- SF7
- October 02, 2015
- Like
- 0
Save and New - redirect to a VF along with Parent ID in Visual force page
<apex:page standardController="Client_Site__c" extensions="AddClientSupplier,ClientSiteExt" tabStyle="Client_Site__c"> <apex:form id="myForm" > <apex:sectionHeader title="New Client Site" /> <apex:pageBlock title=" Client Site Edit" mode="edit"> <apex:pageBlockButtons location="top" > <apex:commandButton value="Save" action="{!saveClientSite}" /> <!-- <apex:commandButton value="Save & New" action="{!saveandnew1}" /> --> <apex:commandButton value="Cancel" action="{!Cancel}"/> </apex:pageBlockButtons> </Apex:Page>
public class AddClientSupplier { ApexPages.StandardController sc; public Client_Discovery__c myCustomObject; public Client_Site__c acct{get;set;} public Integer marker=2; public Integer selectedClientSupplier{get;set;} public List<WrapperClass> lClientSuppliers{get;set;} public String queryString {get;set;} public AddClientSupplier(ApexPages.StandardController controller) { this.acct = (Client_Site__c)controller.getRecord(); sc=controller; lClientSuppliers=new List<WrapperClass>(); Client_Supplier__c c=new Client_Supplier__c(); lClientSuppliers.add(new WrapperClass(c,1)); } public PageReference deleteClientSupplier(){ Integer x=-1; for(WrapperClass wc:lClientSuppliers){ x++; if(wc.counter==selectedClientSupplier){ System.debug('-->selected ClientSupplier:'+selectedClientSupplier+' position:'+x); break; } } lClientSuppliers.remove(x); return null; } public PageReference saveClientSite(){ Database.SaveResult sr = Database.insert(acct, false); Id idey=sr.getId(); List<Client_Supplier__c> ClientSupplierList=new List<Client_Supplier__c>(); for(WrapperClass wc:lClientSuppliers){ if(!string.isblank(wc.c.Supplier_Name__c) ){ Client_Supplier__c c=new Client_Supplier__c(); c.Is_This_a_New_or_Incumbent_Supplier__c=wc.c.Is_This_a_New_or_Incumbent_Supplier__c; c.Skill_Type__c=wc.c.Skill_Type__c; c.Supplier_Name__c=wc.c.Supplier_Name__c; c.Will_Manpower_Manage_This_Supplier__c=wc.c.Will_Manpower_Manage_This_Supplier__c; c.Client_Site__c=idey; ClientSupplierList.add(c); } } insert ClientSupplierList; return(new PageReference('/'+sr.id).setRedirect(True)); // return new PageReference('/' + Schema.getGlobalDescribe().get('Client_Discovery__c').getDescribe().getKeyPrefix() + '/o'); } public PageReference addAClientSupplier(){ Client_Supplier__c c=new Client_Supplier__c(); lClientSuppliers.add(new WrapperClass(c,marker)); marker=marker+1; return null; } public class WrapperClass{ public Integer counter{get;set;} public Client_Supplier__c c{get;set;} public WrapperClass(Client_Supplier__c cntc,Integer i){ this.c=cntc; this.counter=i; } } /* public PageReference saveandnew(){ try { sc.save(); Schema.DescribeSObjectResult describeResult = sc.getRecord().getSObjectType().getDescribe(); PageReference pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e?' + queryString); pr.setRedirect(true); return pr; } catch(System.DMLException e) { // Note: not spitting out any error messages, as SF seems to be handling the errors fine, at least for my simple object; your mileage my vary. return null; } }*/ }
public with sharing class ClientSiteExt { public ClientSiteExt(ApexPages.StandardController controller) { Client_Site__c c = (Client_Site__c) controller.getRecord(); c.Client_Discovery__c = ApexPages.currentPage().getParameters().get('Client_Discovery__c'); } }Hi ,
I need a Custom Save and New button which when hit need to direct me to the same VF page which i just created the record on . pb is i am unable have the parent ID for the LookUp field.
- SF7
- October 01, 2015
- Like
- 0