-
ChatterFeed
-
0Best Answers
-
2Likes Received
-
0Likes Given
-
46Questions
-
31Replies
Case Trigger help
I'm trying to create a trigger that updates my campaign members status after a lead or a contact fills a web to case form, my web to case is working fine is getting the id through a javascript,but my trigger isn't working. Someone could help me?
Here is my code:
trigger bi_WebToCaseLead on Case (before insert) { Set<String> setCampaignMail = new Set<String>(); //List<CampaignMember> listCm = [SELECT Id,Lead.Email,LeadId,ContactId,Contact.Name,Contact.Email,CampaignId FROM CampaignMember WHERE Campaign.IsActive = true]; List<CampaignMember> listAg = [SELECT Id,Lead.Email,LeadId,ContactId,Contact.Name,Contact.Email,CampaignId FROM CampaignMember WHERE Campaign.IsActive = true AND (Lead.Email IN :setCampaignMail OR Contact.Email IN :setCampaignMail)]; for(CampaignMember cm : listAg){ for(Case caso : Trigger.new){ if(!setCampaignMail.contains(caso.SuppliedEmail)){ setCampaignMail.add(caso.SuppliedEmail); } if(caso.ChaveCampanha__c != null && cm.CampaignId.equals(caso.ChaveCampanha__c)){ cm.Status = 'Respondido'; caso.RelacionamentoLead__c = cm.LeadId; } } } update listAg; }
- SolidLucas
- October 15, 2015
- Like
- 0
Trigger Help Update Contact and Lead
I've build a trigger that updates a status of a campaign member when he answers a web-to-case form,when the user is a lead or a contact,so far so good, my problem is when a lead has a same e-mail as a contact my trigger ignores the contact e-mail and only updates the status of the lead. When this scenario happen i want to both to be updated if both have the same e-mail.
This is my code :
trigger bi_WebToCaseLead on Case (before insert) { List<CampaignMember> listCm = [SELECT Id,Lead.Email,LeadId,ContactId,Contact.Name,Contact.Email,CampaignId FROM CampaignMember WHERE Campaign.IsActive = true]; Map<String, CampaignMember> mapCm = new Map<String, CampaignMember>(); for(CampaignMember cm : listCm){ mapCm.put(cm.Lead.Email, cm); mapCm.put(cm.Contact.Email, cm); } for(Case caso : Trigger.new){ Case tempCase = caso; CampaignMember tempCampaign = mapCm.get(caso.SuppliedEmail); if(tempCampaign != null && caso.ChaveCampanha__c !=null){ tempCampaign.Status = 'Respondido'; caso.RelacionamentoLead__c = tempCampaign.LeadId; update tempCampaign; } } }
Regards,
Lucas
- SolidLucas
- October 09, 2015
- Like
- 0
Trigger help before insert
this is my code!
trigger bi_WebToCaseLead on Case (before insert) { List<CampaignMember> listCm = [SELECT Id,Lead.Email,LeadId,CampaignId FROM CampaignMember WHERE CampaignId = '701190000001F5l']; Map<String, CampaignMember> mapCm = new Map<String, CampaignMember>(); for(CampaignMember cm : listCm){ mapCm.put(cm.Lead.Email, cm); } for(Case caso : Trigger.new){ Case tempCase = caso; CampaignMember tempCampaign = mapCm.get(caso.SuppliedEmail); if(tempCampaign != null && caso.ChaveCampanha__c == '701190000001F5l'){ tempCampaign.Status = 'Respondido'; caso.RelacionamentoLead__c = tempCampaign.LeadId; update tempCampaign; } } }
- SolidLucas
- September 29, 2015
- Like
- 0
Class test help
My class
global class btn_EnviarCampanha { webservice static String btn_EnviarCampanha(Id mId) { String msg = ''; try{ List<CampaignMember> listMember = [SELECT Id,CampaignId,Status FROM CampaignMember WHERE Status = 'Aguardando Envio' AND CampaignId =:mId]; List<CampaignMember> listMemberUpdated = new List<CampaignMember>(); for(CampaignMember cm :listMember){ cm.Status = 'Enviado'; listMemberUpdated.add(cm); } update listMemberUpdated; msg = 'Email enviado com sucesso!'; }catch(Exception ex){ msg = 'Erro ao enviar mensagem!'; } return msg; } }My test class
@isTest private class tst_btn_EnviarCampanha { @isTest static void test_method_one() { Lead lead = new Lead( FirstName = 'Lucas', LastName = 'ze' ); insert lead; Campaign cam = new Campaign( Name = 'Venda de Seminovos' ); insert cam; CampaignMember membroCampanha = new CampaignMember( //Status = 'Aguardando Envio', CampaignId = cam.Id, LeadId = lead.Id ); insert membroCampanha; update membroCampanha; btn_EnviarCampanha.btn_EnviarCampanha(membroCampanha.Id); } }
- SolidLucas
- September 28, 2015
- Like
- 0
Trigger help,Campaign Member Status
trigger ai_WebToCaseLead on Case (after insert) { List<CampaignMember> listCm = [SELECT Id,Lead.Email,CampaignId FROM CampaignMember WHERE CampaignId = '701190000001F5l']; for(Case caso : Trigger.new){ System.debug('caso'); for(CampaignMember cm : listCm){ System.debug('caso'); if(cm.Lead.Email == caso.SuppliedEmail && caso.ChaveCampanha__c == '701190000001F5l'){ cm.Status = 'Respondido'; caso.ParentId = cm.Lead.Id; update cm; update caso; System.debug(cm); System.debug(caso); } } } }
Regards!
Lucas
- SolidLucas
- June 30, 2015
- Like
- 0
NullPoiter Exception help
My class
public with sharing class ErrorMessage_ctl { /**************** *Public Variables *****************/ private String msg; private String retURL; public boolean showButton {get;set;} /****************** *Constructor ******************/ public ErrorMessage_ctl(){ msg = System.currentPageReference().getParameters().get('msg'); retURL = System.currentPageReference().getParameters().get('retURL'); if(functions.isNotEmptyOrNull(msg)){ ApexPages.addmessage(new ApexPages.message( ApexPages.severity.ERROR, msg )); }else{ ApexPages.addmessage(new ApexPages.message( ApexPages.severity.ERROR, 'Ocorreu um erro inesperado!')); } if(functions.isNotEmptyOrNull(retURL)){ showButton = true; }else{ showButton = false; } } //retorna a página principal public PageReference errorReturn(){ PageReference page = new PageReference(retURL); page.setRedirect(true); return page; } }
my test class
@isTest private class ErrorMessage_tst_ctl { static testMethod void myUnitTest() { ErrorMessage_ctl controlador = new ErrorMessage_ctl(); Test.setCurrentPageReference(new PageReference('msg')); System.currentPageReference().getParameters().get('msg'); //retURL = System.currentPageReference().getParameters().get('retURL'); controlador.showButton = true; controlador.showButton = false; controlador.errorReturn(); } }
- SolidLucas
- January 13, 2015
- Like
- 0
test class help
hi someone could help me to create a test unity for my class? i'm kinda in trouble to test the both scenarios, i only got 19% from the first constructor.
my class.
public with sharing class VLookupListBusiness { /** * Private variables **/ private list<VLookupList__c> allLookups; private list<SelectOption> parametros; /** * Construtor **/ public VLookupListBusiness(String[] contexts) { construtorLocal(contexts); } /** * Construtor **/ public VLookupListBusiness() { construtorLocal( new String[]{'ClassificacaoCliente', 'ClassificacaoIntercias', 'TipoCliente', 'SegmentoGerencial', 'CanalVenda', 'Segmento', 'MetodoEntrega', 'TipoOrdem', 'ClasseContribuinte', 'ClasseContribuinteIN68', 'UtilizacaoGas', 'TipoCobranca', 'AtividadeEconomica', 'Organization', 'Almoxarifado', 'Parametros'}); parametros = getListOptions('Parametros', 'Chave__c', true); } private list<SelectOption> getListOptions(String pContext, String pKey, boolean hasNothing){ list<SelectOption> result = new list<SelectOption>(); if (hasNothing) result.add(new SelectOption('', '-- Nenhum --')); for (VLookupList__c vlook: allLookups){ if (vlook.Contexto__c == pContext) result.add(new SelectOption(String.valueOf(vlook.get(pKey)), String.valueOf(vlook.get('Name')))); } return result; } private void construtorLocal(String[] contexts) { allLookups = new list<VLookupList__c>(); allLookups = [ Select Id, Contexto__c, Name , Chave__c, FkChave__c, Attribute1__c from VLookupList__c where Contexto__c in :contexts order by Contexto__c, Name ]; } /** * Private methods **/ private String getValueFromKey(list<SelectOption> pList, String pChave){ String result = ''; for (SelectOption item: pList) { if (item.getValue() == pChave) { result = item.getLabel(); break; } } return result; } /** * Public methods **/ public String getVLookupId(String pKey, String pContext){ String result = null; for (VLookupList__c vlook: allLookups){ if (vlook.Contexto__c == pContext) if (vlook.Chave__c == pKey) result = vlook.Id; } return result; } public String getVLookupKey(Id pId){ String result = ''; for (VLookupList__c vlook: allLookups){ if (vlook.Id == pId) result = vlook.Chave__c; } return result; } public list<SelectOption> getListOptionsFiltered(String pContext, String pKey, String pFkKey) { list<SelectOption> result = new list<SelectOption>(); result.add(new SelectOption('', '-- Nenhum --')); for (VLookupList__c vlook: allLookups){ if (vlook.Contexto__c == pContext) if (vlook.FkChave__c == pFkKey) result.add(new SelectOption(String.valueOf(vlook.get(pKey)), String.valueOf(vlook.get('Name')))); } return result; } public String getParameterValue(String pContext, String pParameter) { String result = null; String valueFromKey = getValueFromKey(parametros, pParameter); if (Functions.isNotEmptyOrNull(valueFromKey)){ result = getVLookupId(valueFromKey, pContext); } return result; } public list<SelectOption> getListOptions(String pContext){ return getListOptions( pContext, 'Id', true); } public String getValueById(String pId) { String result = null; for (VLookupList__c vlook: allLookups) { if (vlook.Id.equals(pId)) { result = vlook.Name; break; } } return result; } public String getAttributeValueById(String pId) { String result = null; for (VLookupList__c vlook: allLookups) { if (vlook.Id.equals(pId)) { result = vlook.Attribute1__c; break; } } return result; } public list<SelectOption> getListOptionsNameKey(String pContext, boolean hasNothing){ list<SelectOption> result = new list<SelectOption>(); if (hasNothing) result.add(new SelectOption('', '-- Nenhum --')); for (VLookupList__c vlook: allLookups){ if (vlook.Contexto__c == pContext) result.add(new SelectOption(String.valueOf(vlook.get('Name')), String.valueOf(vlook.get('Chave__c')))); } return result; } }
my test class
@isTest private class vLookupListBusiness_tst { static testMethod void myUnitTest() { //Istancia do controlador VLookupListBusiness testList = new VLookupListBusiness(); testPrimeiroCenario(); } private static void testPrimeiroCenario(){ VLookupListBusiness testList = new VLookupListBusiness(VLookupList__c); VLookupList__c testLookupList = getLookupList(); VlookupList__c vlookupList = new VlookupList__c( Chave__c = 'VlookupList__c', Contexto__c = 'CustomSearchPage', Name = 'Chave__c, Contexto__c' ); insert vlookupList; VlookupList__c vls = new VlookupList__c(); List<SelectOption> so = new List<SelectOption>(); so.add(new SelectOption('', '-- Nenhum --')); insert vls; } }
- SolidLucas
- January 09, 2015
- Like
- 0
Test Class Help
My apexClass
public with sharing class PaymentManager { /* * PRIVATE VARIABLES */ private Map<Id, MetodoPagamentoEndereco__c> mapPaymentsOriginal; /* * PUBLIC VARIABLES */ public String title {get;set;} public Payment_cls paymentAux {get;set;} public List<Payment_cls> listPaymentsAddress {get;set;} public Integer selectedPrincipalId {get;set;} public Integer paymentIdSelected {get;set;} /* * SUBCLASSES */ private class Payment_cls { public Integer id {get;set;} public MetodoPagamentoEndereco__c payment {get;set;} public boolean isDeleted {get;set;} public Payment_cls() { payment = new MetodoPagamentoEndereco__c(); } } /* * CONSTRUCTOR */ public PaymentManager(){ title = 'Métodos de Pagamento'; paymentAux = new Payment_cls(); } /* * PRIVATE METHODS */ /* * este método identifica se já exsite um método de pagamento cadastrado para o endereço. */ private boolean hasMethod(String pMethodId){ boolean result = false; for (Payment_cls iPayment: listPaymentsAddress){ if (iPayment.payment.MetodoPagamento__c == pMethodId) { result = true; break; } } return result; } private boolean isEmpty(list<Payment_cls> pList){ boolean result = false; if (pList.isEmpty()) { ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR,'É necessårio informar ao menos um método de pagamento para prosseguir.')); result = true; } return result; } private boolean existingPaymentIsValid(MetodoPagamentoEndereco__c pMetodo){ boolean result = true; MetodoPagamentoEndereco__c old = mapPaymentsOriginal.get(pMetodo.Id); if (pMetodo.Inicio__c < old.Inicio__c) { pMetodo.Inicio__c.addError('Não é permitido alterar a data de início para uma data anterior a previamente cadastrada: ' + old.Inicio__c.format()); result = false; } else result = finalDateIsMajor(pMetodo); return result; } private boolean newerPaymentIsValid(MetodoPagamentoEndereco__c pMetodo){ boolean result = true; if (pMetodo.Inicio__c < Date.Today()) { pMetodo.Inicio__c.addError('Não é permitido o cadastramento de um novo método de pagamento com data retroativa.'); result = false; } else result = finalDateIsMajor(pMetodo); return result; } private boolean finalDateIsMajor(MetodoPagamentoEndereco__c pMetodo){ boolean result = true; if ( pMetodo.Fim__c != null){ if (pMetodo.Inicio__c > pMetodo.Fim__c) { pMetodo.Inicio__c.addError('A data de início não pode ser maior que a data final.'); result = false; } } return result; } private Integer getMajorId() { Integer retorno = 0; for (Payment_cls icPayment : listPaymentsAddress) { if (icPayment.id > retorno) { retorno = icPayment.id; } } return retorno + 1; } /* * PUBLIC METHODS */ public void loadPaymentsByAddress(Endere_o_Relacionado__c pEndereco) { if (listPaymentsAddress == null) { listPaymentsAddress = new List<Payment_cls>(); if (Functions.isNotEmptyOrNull(pEndereco.Id)) { list<MetodoPagamentoEndereco__c> listPaymentsOriginal = [ SELECT Id, Name, Inicio__c, Fim__c, Principal__c, MetodoPagamento__c FROM MetodoPagamentoEndereco__c WHERE Endereco__c = :pEndereco.Id ORDER BY Name ]; if (!listPaymentsOriginal.isEmpty()) { Integer i = 1; mapPaymentsOriginal = new Map<Id,MetodoPagamentoEndereco__c >(); for (MetodoPagamentoEndereco__c iPayment : listPaymentsOriginal) { mapPaymentsOriginal.put(iPayment.Id, iPayment.clone(true, true, true, true)); Payment_cls cPayment = new Payment_cls(); cPayment.payment = iPayment;//.clone(true, true, true, true); cPayment.id = i; cPayment.isDeleted = false; listPaymentsAddress.add(cPayment); //setando o Id do método pagamento selecionado como principal. if (cPayment.payment.Principal__c) { selectedPrincipalId = cPayment.Id; } i++; } } } } } public PageReference deletePayment() { for (Payment_cls icPayment : listPaymentsAddress) { if (icPayment.id == paymentIdSelected) { icPayment.isDeleted = !icPayment.isDeleted; break; } } return null; } public PageReference savePaymentInList() { paymentAux = new Payment_cls(); String methodPaymentId = Apexpages.currentPage().getParameters().get('methodPaymentId'); String methodPaymentName = Apexpages.currentPage().getParameters().get('methodPaymentName'); if (hasMethod(methodPaymentId)) { ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR,'O método de pagamento "' + methodPaymentName + '" já está cadastrado.')); } else { paymentAux.payment = new MetodoPagamentoEndereco__c( Inicio__c = Date.today(), Principal__c = true, MetodoPagamento__c = methodPaymentId, Name = methodPaymentName ); Payment_cls cPayment = new Payment_cls(); cPayment = paymentAux; //cPayment.payment.Principal__c = listPaymentsAddress.isEmpty(); cPayment.id = getMajorId(); cPayment.isDeleted = false; listPaymentsAddress.add(cPayment); selectedPrincipalId = cPayment.id ; } return null; } public void doSelectPrincipal() { for (Payment_cls icPayment : listPaymentsAddress) { boolean isPrincipal = icPayment.id == selectedPrincipalId; icPayment.payment.Principal__c = isPrincipal; } } public boolean isValid(){ boolean result = true; result = !isEmpty(listPaymentsAddress); if (result) { list<Payment_cls> listWithoutDelete = new list<Payment_cls>(); for (Payment_cls iPayment :listPaymentsAddress){ if (!iPayment.isDeleted) { listWithoutDelete.add(iPayment); if (Functions.IsNotEmptyOrNull(iPayment.payment.Id)){ if (!existingPaymentIsValid(iPayment.payment)) result = false; } else { if (!newerPaymentIsValid(iPayment.payment)) result = false; } } } if (result ) result = !isEmpty(listWithoutDelete); } return result; } public void doSave(Endere_o_Relacionado__c pEndereco) { if (pEndereco != null && Functions.isNotEmptyOrNull(pEndereco.Id)) { List<MetodoPagamentoEndereco__c> auxListInsertPayment = new List<MetodoPagamentoEndereco__c>(); List<MetodoPagamentoEndereco__c> auxListUpdatePayment = new List<MetodoPagamentoEndereco__c>(); List<MetodoPagamentoEndereco__c> auxListDeletePayment = new List<MetodoPagamentoEndereco__c>(); for (Payment_cls cPayment : listPaymentsAddress) { if (!Functions.isNotEmptyOrNull(cPayment.payment.Id)) { if (!cPayment.isDeleted) { cPayment.payment.Endereco__c = pEndereco.Id; auxListInsertPayment.add(cPayment.payment); } } else { if (cPayment.isDeleted) { auxListDeletePayment.add(cPayment.payment); } else { auxListUpdatePayment.add(cPayment.payment); } } } if (!auxListDeletePayment.isEmpty()) { delete auxListDeletePayment; } if (!auxListUpdatePayment.isEmpty()) { update auxListUpdatePayment; } if (!auxListInsertPayment.isEmpty()) { insert auxListInsertPayment; } } } }My testClass
private class PaymentManager_tst { static testMethod void myUnitTest() { //istancia do construtor PaymentManager payment = new PaymentManager(); List<MetodoPagamentoEndereco__c> MetodoPagamentoEnderecoVazio = new List<MetodoPagamentoEndereco__c>(); Endere_o_Relacionado__c endereco = new Endere_o_Relacionado__c( Name = 'teste' ); insert endereco; MetodoPagamento__c metodoPagamento = new MetodoPagamento__c( Codigo__c = 'teste', Fim__c = Date.valueOf(Datetime.now().addDays(-10)), Inicio__c = Date.valueOf(Datetime.now().addDays(-9)), Observacao__c = 'teste de Observação' ); insert metodoPagamento; MetodoPagamentoEndereco__c metodoPagamentoEndereco = new MetodoPagamentoEndereco__c( Name = 'Teste', Endereco__c = endereco.Id, Fim__c = Date.valueOf(Datetime.now().addDays(-10)), Inicio__c = date.today(), Principal__c = true, MetodoPagamento__c = metodoPagamento.Id ); insert metodoPagamentoEndereco; //Métodos publicos do construtor payment.loadPaymentsByAddress(endereco); payment.doSave(endereco); payment.savePaymentInList(); payment.savePaymentInList(); payment.isValid(); payment.doSelectPrincipal(); payment.deletePayment(); } }
- SolidLucas
- January 08, 2015
- Like
- 1
test class help
Someone could help me with my test class is givin me NullPointerException
public with sharing class ContactManager { public Contact_cls contactAux {get;set;} public List<Contact_cls> listContacts {get;set;} public String title {get;set;} public Integer contactIdSelected {get;set;} public boolean isEditMode {get;set;} private class Contact_cls { public Integer id {get;set;} public Contact contato {get;set;} public boolean isNew {get;set;} public boolean isEdited {get;set;} public boolean isDeleted {get;set;} public Contact_cls() { contato = new Contact(); } } /* * CONSTRUCTOR */ public ContactManager(){ title = 'Contato'; isEditMode = false; contactAux = new Contact_cls(); } /* * PRIVATE METHODS */ /* * verifica se uma lista de pagamentos(controle interno) está vazia e gera uma mensagem de erro. */ private boolean isEmpty(list<Contact_cls> pList){ boolean result = false; if (pList.isEmpty()) { ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR,'É necessårio informar ao menos um contato.')); result = true; } return result; } /* * PUBLIC METHODS */ public void loadContactsByAccount(Account pAccount) { if (listContacts == null) { listContacts = new List<Contact_cls>(); List<Contact> auxListContacts = [SELECT Id, Salutation, FirstName, LastName, Tipo_de_Telefone__c, DDI__c, DDD__c, Phone, Ramal__c, Email FROM Contact WHERE AccountId = :pAccount.Id ORDER BY LastName]; if (!auxListContacts.isEmpty()) { Integer i = 1; for (Contact iContato : auxListContacts) { Contact_cls cContact = new Contact_cls(); cContact.contato = iContato.clone(true, true, true, true); cContact.id = i; cContact.isNew = false; cContact.isEdited = false; cContact.isDeleted = false; listContacts.add(cContact); i++; } } } } public PageReference newContact() { title = 'Contato'; isEditMode = false; contactAux = new Contact_cls(); return null; } public PageReference editContact() { for (Contact_cls icContato : listContacts) { if (icContato.id == contactIdSelected) { contactAux = icContato; title = 'Contato [Modo de Edição]'; isEditMode = true; break; } } return null; } public PageReference deleteContact() { for (Contact_cls icContato : listContacts) { if (icContato.id == contactIdSelected) { icContato.isDeleted = !icContato.isDeleted; break; } } return null; } public PageReference saveContactInList() { Contact_cls cContato = new Contact_cls(); cContato = contactAux; if (!isEditMode) { cContato.id = getMajorId(); cContato.isDeleted = false; cContato.isEdited = false; cContato.isNew = true; listContacts.add(cContato); } else { cContato.isDeleted = false; cContato.isEdited = true; //setContactInList(cContato); } newContact(); return null; } private Integer getMajorId() { Integer retorno = 0; for (Contact_cls iContato : listContacts) { if (iContato.id > retorno) { retorno = iContato.id; } } return retorno + 1; } public boolean isValid(){ boolean result = true; //for (Contact_cls cContact : listContacts) { result = !isEmpty(listContacts); if (result) { list<Contact_cls> listWithoutDelete = new list<Contact_cls>(); for (Contact_cls iContact :listContacts){ if (!iContact.isDeleted) { listWithoutDelete.add(iContact); } } . if (result ) result = !isEmpty(listWithoutDelete); } return result; } public void doSave(Account pAccount) { if (pAccount != null && Functions.isNotEmptyOrNull(pAccount.Id)) { List<Contact> auxListInsertContact = new List<Contact>(); List<Contact> auxListUpdateContact = new List<Contact>(); List<Contact> auxListDeleteContact = new List<Contact>(); for (Contact_cls cContact : listContacts) { cContact.contato.AccountId = pAccount.Id; if (!cContact.isNew && cContact.isDeleted) { auxListDeleteContact.add(cContact.contato); } else if (!cContact.isNew && cContact.isEdited) { auxListUpdateContact.add(cContact.contato); } else if (cContact.isNew) { auxListInsertContact.add(cContact.contato); } } if (!auxListDeleteContact.isEmpty()) { delete auxListDeleteContact; } if (!auxListUpdateContact.isEmpty()) { update auxListUpdateContact; } if (!auxListInsertContact.isEmpty()) { insert auxListInsertContact; } } } }
class test 20%
@isTest private class ContactManager_tst { static testMethod void myUnitTest() { //instanciando o controlador; ContactManager contact = new ContactManager(); //chamando métodos do controlador contact.newContact(); contact.isValid(); /*contact.editContact(); contact.deleteContact(); contact.saveContactInList(); contact.doSave();**/ //instanciando objeto List<Contact> products = loadContacts(); } // Carregando a Massa de dados para teste private void loadData(){ Account acc = new Account( name = 'Teste' ); insert acc; } private static List<Contact> loadContacts(){ Contact cot = new Contact( Salutation = 'Sr', FirstName = 'Joaquim', LastName = 'Lima', DDD__c = 13, DDI__c = 55, Tipo_de_Telefone__c = '', Phone = '33778899', Ramal__c = '231', Email = 'joaquim.lima@gmail.com' ); Contact cot2 = new Contact(); List<Contact> contacts = new List<Contact>(); contacts.add(cot); contacts.add(cot2); insert contacts; return contacts; } }
- SolidLucas
- January 05, 2015
- Like
- 0
test class help
public PageReference addAddress(){ boolean mFound = false; //Identificando se o endereço/produto já existem na lista. for(ItemCredito ic: listItens) { if (ic.solicitacaoCreditoItem.Conta__c == solicitacaoCreditoItem.Conta__c){ if (ic.solicitacaoCreditoItem.Produto__c == solicitacaoCreditoItem.Produto__c){ solicitacaoCreditoItem.Produto__c.addError(msgAddressProductDuplicated); mFound = true; break; } } } if (mFound) { ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, msgAddressProductDuplicated); ApexPages.addmessage(myMsg); } else{ ItemCredito item = new ItemCredito(); item.solicitacaoCreditoItem = solicitacaoCreditoItem; Account mAccount = mapChildAccounts.get(solicitacaoCreditoItem.Conta__c); item.endereco = mAccount.EnderecoEntrega__r.Name; item.documento = mAccount.N_mero_do_Documento__c; item.tipoDocumento = mAccount.Tipo_de_Documento__c; item.isDeleted = false; index = index + 1; item.index = index; listItens.add(item); displayPopup = false; } return null; }
my test class is 66%
private class SolicitacaoCredito_ctl_tst { static testMethod void myUnitTest() { //instanciando o objeto SolicitacaoCredito__c solicitacaoCredito = loadValues(); //criando um standardController e passando o objeto criado no construtor. ApexPages.StandardController standardController = new ApexPages.StandardController(solicitacaoCredito); //criando uma instancia do controlador que sera testado passando o standardController como parametro SolicitacaoCredito_ctl controlador = new SolicitacaoCredito_ctl(standardController); controlador.cancelAddress(); controlador.deleteItem(); controlador.doSave(); controlador.doSaveAndSend(); controlador.addAddress(); controlador.newAdddress(); controlador.displayPopup = false; } /* * resposavel por gerar massa de dados para a classe de teste */ private static SolicitacaoCredito__c loadValues(){ Account acc = new Account( name = 'João', PerfilRisco__c = 'Teste perfil', TipoLimite__c = 'Teste tipo limite', ToleranciaInadimplencia__c = 'teste', Tolerancia__c = 3, GarantiaRenegociacao__c = true, GarantiaCreditoRotativo__c = false, TipoGarantia__c = 'teste do tipo de garantia', ValorGarantia__c = 150 ); insert acc; SolicitacaoCredito__c solicitacaoCredito = new SolicitacaoCredito__c( Conta__c = acc.Id, GarantiaCreditoRotativo__c = true, GarantiaRenegociacao__c = true, Justificativa__c = 'Teste justificativa', LimiteConcedido__c = 10, LimiteSolicitado__c = 20, LimiteSugerido__c = 15, ParecerAnalista__c = 'teste parecer analista', ParecerSerasa__c = 'teste parecer serasa', PerfilRisco__c = 'teste de perfil de risco', PrecoSugerido__c = 50.5, Status__c = 'Rascunho', TipoGarantia__c = 'teste tipo de garantia', TipoLimite__c = 'teste tipo de limite', Tolerancia__c = 3, ToleranciaInadimplencia__c = 'teste', ValorGarantia__c = 15, VolumeKg__c = 50 ); insert solicitacaoCredito; Product2 prod = new Product2( name = 'teste de produto' ); insert prod; SolicitacaoCreditoItem__c solicitacaoCreditoItem = new SolicitacaoCreditoItem__c( Conta__c = acc.Id, Inadimplente__c = false, //PrazoConcedido__c = solicitacaoCredito.Id, //PrazoSolicitado__c = , //PrazoSugerido__c = solicitacaoCredito.Id, Preco__c = 10, SolicitacaoCredito__c = solicitacaoCredito.Id, VolumeKg__c = 20 ); insert solicitacaoCreditoItem; Preco__c preco = new Preco__c( Endereco__c = acc.Id, ObservacaoHistorico__c = 'teste', PrecoListaAnterior__c = 15, PrecoListaVigente__c = 14, PrecoUltimaVenda__c = 10.2, PrecoUltimaVendaAno__c = 20, Produto__c = prod.Id ); insert preco; return solicitacaoCredito; } }
- SolidLucas
- December 31, 2015
- Like
- 0
test class help!
Somenone could help me to do a class test for this method?
private void loadBase(){ listBase = [ SELECT Id, Name, QtdePontos__c, QtdeUnidadesConsumidoras__c, QtdeSaloesFestas__c, QtdeZeladorias__c, InvestimentoUG__c, InvestimentoCliente__c, InicioObra__c, InicioConsumo__c, Comentarios__c, IndexController__c, AnaliseInvestimento__c, (SELECT Id, Name, Quantidade__c, AiInstalacao__c, ValorOrcado__c, Servico__c, IndexController__c FROM InstalacoesServicos__r), (Select Id, Name, Atividade__c, Instalacao__c, Responsabilidade__c, Valor__c From Itens_de_Obras__r), (Select Id, Name, Quantidade__c, Kit__c, Kit__r.Valor__c, Kit__r.Descricao__c, Instalacao__c From KitsInstalacoes__r), (Select Id, Name, Comodato__c, Quantidade__c, ValorOrcado__c, Instalacao__c, EquipamentoMaterial__c, EquipamentoMaterial__r.Tipo__c, EquipamentoMaterial__r.Name From EquipamentosMateriaisInstalacoes__r), (Select Id, Name, ConsumoPrevistoMensal__c, FatorIncremento__c, FilialAbastecedora__c, IcmsOrigem__c, IcmsDestino__c, PrecoVenda__c, Produto__c, ExRefinaria__c From InstalacoesProdutos__r) FROM AiInstalacao__c WHERE AnaliseInvestimento__c = :analiseInvestimento.Id ]; mapService = new Map<Id, list<InstalacaoServico__c>>(); mapObras = new Map<Id, list<AiItemObra__c>>(); mapKits = new Map<Id, list<AiKitInstalacao__c>>(); mapMateriais = new Map<Id, list<AiEquipamentoMaterialInstalacao__c>>(); mapConsumo = new Map<Id, list<AiConsumoInstalacao__c>>(); Set<Id> setBaseId = new Set<Id>(); for (AiInstalacao__c mBase: listBase){ mapService.put(mBase.Id, mBase.InstalacoesServicos__r); mapObras.put(mBase.Id, mBase.Itens_de_Obras__r); mapKits.put(mBase.Id, mBase.KitsInstalacoes__r); mapMateriais.put(mBase.Id, mBase.EquipamentosMateriaisInstalacoes__r); mapConsumo.put(mBase.Id, mBase.InstalacoesProdutos__r); //colecionando lista de Id das Instacões do projeto setBaseId.Add(mBase.Id); } loadConsumo(setBaseId); selectFirstBase(); }
/** * Constructor **/ public AnaliseInvestimentoConsulta_ctl(ApexPages.StandardController con){ analiseInvestimento = (AnaliseInvestimento__c) con.getRecord(); loadBase(); subTabIndexActive = '0'; }
- SolidLucas
- December 29, 2015
- Like
- 0
test class help
I want to create a test class for those methods someone could help me?
public void getAccounts(){ String stringComplemento = ''; string searchquery='SELECT name,id,Tipo_de_Documento__c,Temp_Cod_ERP__c,Raz_o_Social_SCC__c,'+ 'Nome_fantasia_SCC__c,N_mero_do_Documento__c,Temp_Cod_Cliente__c, Cia__c,Ativo__c,CEP_SCC__c,Logradouro__c,Bairro_SCC__c,'+ 'Cidade_SCC__c,UF_SCC__c,SituacaoCliente__c FROM Account '; if(PesquisaString != '' && PesquisaString!=null){ stringComplemento = ' WHERE name LIKE '+ '\'%' +PesquisaString+'%\''; } if(NomeFantasia != '' && NomeFantasia!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' Nome_fantasia_SCC__c LIKE '+ '\'%' +NomeFantasia+'%\''; } searchquery = searchquery + stringComplemento; Temp=searchquery + stringComplemento ; listAccPesquisa = Database.query(searchquery);
public void doSearch(){ if(!verificarCampoValido(RazaoSocial) || !verificarCampoValido(NomeFantasia)|| !verificarCampoValido(PesquisaCodCliente) || !verificarCampoValido(PesquisaCodEndereco)|| !verificarCampoValido(NumeroDocumento)|| !verificarCampoValido(Cep)|| !verificarCampoValido(Logradouro)|| !verificarCampoValido(Bairro)|| !verificarCampoValido(Cidade)|| !verificarCampoValido(Uf)|| !verificarCampoValido(cia)|| !verificarCampoValido(tipoDocumento)){ getAccounts(); getCiaOptions(); }else{ ApexPages.Message msg = new Apexpages.Message(ApexPages.Severity.Warning, (msg!= null && msg != '')? msg : 'Necessario Preencher ao menos um campo'); ApexPages.addmessage(msg); } } private boolean verificarCampoValido(String campo){ boolean retorno = campo == null || campo == '' || campo = true; if(!retorno){ if(campo.length() < 3){ msg = 'Necessario informar no minimo 3 caracteres para consulta'; retorno = true; } } return retorno; } /***************************************************** *Metodo para fazer a selecao do tipo da cia no picklist *Method to include selecting the cia type into the picklist ******************************************************/ public List<SelectOption> getCiaOptions() { List<SelectOption> CiaOptions = parameters.getListOptions('Organization'); return CiaOptions; } }
- SolidLucas
- December 08, 2014
- Like
- 0
setting limits into fields visualforce
thanks!
- SolidLucas
- December 05, 2014
- Like
- 0
query parameters
Hello! i want to do a query into a custom "Cia__c" field using the <apex:selectList> well i've created a method like this
public List<SelectOption> getCiaOptions() { List<SelectOption> CiaOptions = new List<SelectOption>(); CiaOptions.add(new SelectOption('','--Nenhum--')); CiaOptions.add(new SelectOption('a07o0000002Quf3AAC','Test1')); CiaOptions.add(new SelectOption('a07o0000002Quf8AAC','Test2')); return CiaOptions; } }VisualForce!
<apex:selectList value="{!Cia}" multiselect="false" size="1" label="Cia"> <apex:selectOptions value="{!CiaOptions}" /> </apex:selectList>
Someone could help me i've been trying but without success.
Thanks!
- SolidLucas
- December 02, 2014
- Like
- 0
query help
well guys i have a doubt about how to query parameters fields, those fields that we select they parameters value. i want a field that is a parameter search type, but i don't know who return his value on my visualForce page i've did it a select to see if my query is right and only return my field id.
someone could give me a example how to do those queies?
Thanks,Lucas!
- SolidLucas
- December 01, 2014
- Like
- 0
how to query a parameter on a search field type?
guys i would like to know how can i pass a query into a field of search type(parameter) beacuse when i do a query its returning this error
[object Object]: Cia__c, Ativo__c FROM Account where Cia__c ='Test' ^ ERROR at Row:1:Column:167 invalid ID field: Test
my visualforce is like that
<apex:selectList value="{!cia}" multiselect="false" size="1" label="Cia"> <apex:selectOption itemValue="" itemLabel="--Nenhum--"/> <apex:selectOption itemValue="Test" itemLabel="Test"/> <apex:selectOption itemValue="Test2" itemLabel="Test2"/> </apex:selectList>
i really appreciate the help!
- SolidLucas
- November 27, 2014
- Like
- 0
Checkbox query problem
public void getAccounts(){ String stringComplemento = ''; string searchquery='SELECT name, id, Tipo_de_Documento__c, SiteNumber__c, RazaoSocial__c, NomeFantasia__c, '+ 'N_mero_do_Documento__c, CustomerNumber__c, Cia__c,Ativo__c FROM Account '; if(PesquisaString != '' && PesquisaString!=null){ stringComplemento = ' WHERE name LIKE '+ '\'%' +PesquisaString+'%\''; } if(NomeFantasia != '' && NomeFantasia!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' NomeFantasia__c LIKE '+ '\'' +NomeFantasia+'\''; } if(PesquisaCodCliente!= '' && PesquisaCodCliente!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' CustomerNumber__c LIKE '+ '\'' +PesquisaCodCliente+'\''; } if(PesquisaCodEndereco!= '' && PesquisaCodEndereco!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' SiteNumber__c LIKE '+ '\'' +PesquisaCodEndereco+'\''; } if(cia!= '' && cia!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' Cia__c LIKE '+ '\'' +cia+'\''; } if(tipoDocumento!= '' && tipoDocumento!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' Tipo_de_Documento__c LIKE '+ '\'' +tipoDocumento+'\''; } if(RazaoSocial!= '' && RazaoSocial!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' RazaoSocial__c LIKE '+ '\'' +RazaoSocial+'\''; } if(NumeroDocumento!= '' && NumeroDocumento!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' N_mero_do_Documento__c LIKE '+ '\'' +NumeroDocumento+'\''; } \********************* HERE IS WHERE I'M HAVING TROUBLE if(ClienteAtivo){ stringComplemento += 'WHERE Ativo__c = true '; } searchquery = searchquery + stringComplemento; Temp=searchquery ; listAccPesquisa = Database.query(searchquery); }
f is not.
- SolidLucas
- November 27, 2014
- Like
- 0
query is not returning value visualforce
Well i'm developing a visualforce page where have a query that returns the value of the fields of my account object, but is not returning nothing on my search. someone could help me?
visualforce page
<apex:page standardController="account" extensions="AccountSearch_clt"> <apex:sectionHeader title="Pesquisa de Cliente" /> <apex:form id="theform"> <apex:pagemessages escape="false" id="messages" /> <apex:pageBlock title="Pesquisa de Cliente ERP" > <apex:pageBlockSection columns="2" > <apex:pageBlockSection columns="1" > <apex:inputText value="{!PesquisaCodCliente}" label="Codigo Cliente/Endereco"> <apex:inputText value="{!PesquisaCodEndereco}" /> - </apex:inputText> <apex:inputText value="{!cia}" label="Cia/Documento"> <apex:inputText value="{!tipoDocumento}" html-autocomplete="off" /> - </apex:inputText> <apex:inputText value="{!NumeroDocumento}" label="Numero Documento/ Razao Social"> <apex:inputText value="{!RazaoSocial}" html-autocomplete="off" /> - </apex:inputText> <apex:inputText value="{!NomeFantasia}" label="Nome Fantasia/ CEP"> <apex:inputText value="{!RazaoSocial}" html-autocomplete="off" /> - </apex:inputText> </apex:pageBlockSection> </apex:pageBlockSection> <apex:pageBlockButtons location="top"> <apex:commandButton value="Pesquisar" action="{!doSearch}" rerender="theform" /> <apex:commandButton value="Cancelar" action="{!cancel}" style="color:red;" /> </apex:pageBlockButtons> </apex:pageBlock> <c:PageBlockTableEnhancerADV targetPbTableIds="pbt" pageSizeOptions="5,10,15,30" defaultPageSize="5" enableExport="false" /> <apex:pageBlock mode="maindetail" id="pb"> <apex:pageblockTable value="{!listAccPesquisa}" var="item" id="pbt"> <apex:column value="{!item.CustomerNumber__c}" /> <apex:column value="{!item['Name']}"/> <apex:column value="{!item.Id}" /> <apex:column value="{!item .Tipo_de_Documento__c}" /> </apex:pageblockTable> </apex:pageBlock> </apex:form> </apex:page>
public with sharing class AccountSearch_clt { public string NomeFantasia {get;set;} public string Pesquisastring {get;set;} public string PesquisaCodCliente {get;set;} public string PesquisaCodEndereco {get;set;} public string cia {get;set;} public string tipoDocumento {get;set;} public string RazaoSocial {get;set;} public string NumeroDocumento {get;set;} public string Temp {get;set;} public list <Account> listAccPesquisa{get;set;} /********** construtor contructor ***********/ public AccountSearch_clt(ApexPages.StandardController controller) { } public void getAccounts(){ String stringComplemento = ''; string searchquery='SELECT name, id, Tipo_de_Documento__c, SiteNumber__c, RazaoSocial__c, NomeFantasia__c, '+ 'N_mero_do_Documento__c, CustomerNumber__c, Cia__c FROM Account '; if(PesquisaString != ''){ stringComplemento = ' WHERE name LIKE '+ '\'%' +PesquisaString+'%\''; } if(NomeFantasia != '' && NomeFantasia!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' NomeFantasia__c LIKE '+ '\'' +NomeFantasia+'\''; } if(PesquisaCodCliente!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' CustomerNumber__c LIKE '+ '\'' +PesquisaCodCliente+'\''; } if(PesquisaCodEndereco!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' SiteNumber__c LIKE '+ '\'' +PesquisaCodEndereco+'\''; } if(cia!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' Cia__c LIKE '+ '\'' +cia+'\''; } if(tipoDocumento!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' Tipo_de_Documento__c LIKE '+ '\'' +tipoDocumento+'\''; } if(RazaoSocial!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' RazaoSocial__c LIKE '+ '\'' +RazaoSocial+'\''; } if(NumeroDocumento!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' N_mero_do_Documento__c LIKE '+ '\'' +NumeroDocumento+'\''; } searchquery = searchquery + stringComplemento; Temp=searchquery ; listAccPesquisa = Database.query(searchquery); } public void doSearch(){ getAccounts(); } }
- SolidLucas
- November 25, 2014
- Like
- 1
Query search help
that is my controller
public with sharing class AccountSearch_clt { public list <account> acc {get;set;} public string PesquisaCliente {get;set;} public string Pesquisastring {get;set;} public string PesquisaCodCliente {get;set;} public string PesquisaCodEndereco {get;set;} /********** construtor contructor ***********/ public AccountSearch_clt(ApexPages.StandardController controller) { } /********** Metodo que realiza faz a filtragem dos campos a serem pesquisados Method that performs the filtering of the fields to be searched ***********/ public void search(){ String stringComplemento = ''; string searchquery='SELECT name,id,Tipo_de_Documento__c,SiteNumber__c,RazaoSocial__c,NomeFantasia__c,'+ 'N_mero_do_Documento__c,CustomerNumber__c,Cia__c FROM account'; if(PesquisaString!= ''){ stringComplemento = 'WHERE name LIKE \'%+PesquisaString+%\''; } if(PesquisaCliente!= ''){ stringComplemento = 'WHERE NomeFantasia__c LIKE \'%+PesquisaCliente+%\''; } if(PesquisaCodCliente!= ''){ stringComplemento = 'WHERE CustomerNumber__c LIKE \'%+PesquisaCodCliente+%\''; } if(PesquisaCodEndereco!= ''){ stringComplemento = 'WHERE SiteNumber__c LIKE \'%+PesquisaCodEndereco+%\''; } acc= Database.query(searchquery); } public void clear(){ acc.clear(); } }My visualforce Page
<apex:page standardController="account" extensions="AccountSearch_clt"> <apex:sectionHeader title="{!$ObjectType.Account.Label}" subtitle="Teste" /> <apex:form > <apex:inputText value="{!PesquisaString}" label="código Erp" html-autocomplete="off"/> <apex:inputText value="{!PesquisaCliente}" label="Cliente" html-autocomplete="off"/> <apex:commandButton value="Pesquisar" action="{!search}"/> <apex:pageBlock title="Resultado da Pesquisa"> <apex:pageblockTable value="{!acc}" var="a" border="0"> <apex:column headerValue="Conta" > <apex:outputlink value="https://ap1.salesforce.com/{!a.id}" >{!a.Name}</apex:outputlink> <apex:outputlink value="https://ap1.salesforce.com/{!a.Tipo_de_Documento__c}"></apex:outputlink> <apex:outputlink value="https://ap1.salesforce.com/{!a.SiteNumber__c}"></apex:outputlink> <apex:outputlink value="https://ap1.salesforce.com/{!a.SiteNumber__c}"></apex:outputlink> <apex:outputlink value="https://ap1.salesforce.com/{!a.NomeFantasia__c}"></apex:outputlink> <apex:outputlink value="https://ap1.salesforce.com/{!a.N_mero_do_Documento__c}"></apex:outputlink> </apex:column> <apex:column value="{!a.id}"/> <apex:column value ="{!a.Tipo_de_Documento__c}"/> <apex:column value ="{!a.SiteNumber__c}"/> <apex:column value ="{!a.RazaoSocial__c}"/> <apex:column value ="{!a.NomeFantasia__c}"/> <apex:column value ="{!a.N_mero_do_Documento__c}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:form> </apex:page>
- SolidLucas
- November 24, 2014
- Like
- 0
List has no rows for assignment to SObject VisualForce
Hello guys, i'm trying to create a visualforce that returns the account and contacts, of the logged user but its returning this error List has no rows for assignment to SObject.
this is my controller
public with sharing class AnalyticsRevendaController { public Account contas {get;set;} public Contact contato {get;set;} public User usuario {get;set;} public String userId {get;set;} // Detecta os valores do usuário ativo public User activeUser = [SELECT AccountId,ContactId FROM User WHERE Id = :userId LIMIT 1]; public String userAccount = activeUser.AccountId; public String userContact = activeUser.ContactId; public AnalyticsRevendaController(){ //Retorna os dados do usuário Logado contas = new Account(); userId = UserInfo.getUserId(); if(userId != null && ''.equals(userId)) getAccount(); } //retorna os valores da conta do usuário ativo. public Account getAccount(){ //Set<Id> setConta = new Set<Id>(); List<Account> listContas = [SELECT Id,Name,OwnerId FROM Account WHERE Id = :userAccount]; if(listContas.size()> 0) contas = listContas[0]; return contas; } //retorna os valores do contato ativo. public Contact getContact(){ contato = [Select c.LastName, c.FirstName, c.AccountId,c.Email From Contact c WHERE Id=:userContact]; return contato; } }
my visualforce
<apex:page controller="AnalyticsRevendaController"> <apex:form> <apex:pageBlock> <apex:pageBlockSection title="Conta"> <apex:outputtext value ="{!contas.Name}" /> <apex:outputtext value ="{!contas.OwnerId}" /> </apex:pageBlockSection> <apex:pageBlockSection title="Contato"> <apex:outputtext value ="{!Contact.FirstName}" /> <apex:outputtext value ="{!Contact.LastName}" /> <apex:outputtext value ="{!Contact.Email}" /> </apex:pageBlockSection> <apex:pageBlockSection title="Usuario"> <apex:outputtext value ="{!$User.FirstName}" /> <apex:outputtext value ="{!$User.LastName}" /> <apex:outputtext value ="{!$User.Email}" /> <apex:outputtext value ="{!userId}" /> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
- SolidLucas
- November 19, 2014
- Like
- 0
Test Class Help
My apexClass
public with sharing class PaymentManager { /* * PRIVATE VARIABLES */ private Map<Id, MetodoPagamentoEndereco__c> mapPaymentsOriginal; /* * PUBLIC VARIABLES */ public String title {get;set;} public Payment_cls paymentAux {get;set;} public List<Payment_cls> listPaymentsAddress {get;set;} public Integer selectedPrincipalId {get;set;} public Integer paymentIdSelected {get;set;} /* * SUBCLASSES */ private class Payment_cls { public Integer id {get;set;} public MetodoPagamentoEndereco__c payment {get;set;} public boolean isDeleted {get;set;} public Payment_cls() { payment = new MetodoPagamentoEndereco__c(); } } /* * CONSTRUCTOR */ public PaymentManager(){ title = 'Métodos de Pagamento'; paymentAux = new Payment_cls(); } /* * PRIVATE METHODS */ /* * este método identifica se já exsite um método de pagamento cadastrado para o endereço. */ private boolean hasMethod(String pMethodId){ boolean result = false; for (Payment_cls iPayment: listPaymentsAddress){ if (iPayment.payment.MetodoPagamento__c == pMethodId) { result = true; break; } } return result; } private boolean isEmpty(list<Payment_cls> pList){ boolean result = false; if (pList.isEmpty()) { ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR,'É necessårio informar ao menos um método de pagamento para prosseguir.')); result = true; } return result; } private boolean existingPaymentIsValid(MetodoPagamentoEndereco__c pMetodo){ boolean result = true; MetodoPagamentoEndereco__c old = mapPaymentsOriginal.get(pMetodo.Id); if (pMetodo.Inicio__c < old.Inicio__c) { pMetodo.Inicio__c.addError('Não é permitido alterar a data de início para uma data anterior a previamente cadastrada: ' + old.Inicio__c.format()); result = false; } else result = finalDateIsMajor(pMetodo); return result; } private boolean newerPaymentIsValid(MetodoPagamentoEndereco__c pMetodo){ boolean result = true; if (pMetodo.Inicio__c < Date.Today()) { pMetodo.Inicio__c.addError('Não é permitido o cadastramento de um novo método de pagamento com data retroativa.'); result = false; } else result = finalDateIsMajor(pMetodo); return result; } private boolean finalDateIsMajor(MetodoPagamentoEndereco__c pMetodo){ boolean result = true; if ( pMetodo.Fim__c != null){ if (pMetodo.Inicio__c > pMetodo.Fim__c) { pMetodo.Inicio__c.addError('A data de início não pode ser maior que a data final.'); result = false; } } return result; } private Integer getMajorId() { Integer retorno = 0; for (Payment_cls icPayment : listPaymentsAddress) { if (icPayment.id > retorno) { retorno = icPayment.id; } } return retorno + 1; } /* * PUBLIC METHODS */ public void loadPaymentsByAddress(Endere_o_Relacionado__c pEndereco) { if (listPaymentsAddress == null) { listPaymentsAddress = new List<Payment_cls>(); if (Functions.isNotEmptyOrNull(pEndereco.Id)) { list<MetodoPagamentoEndereco__c> listPaymentsOriginal = [ SELECT Id, Name, Inicio__c, Fim__c, Principal__c, MetodoPagamento__c FROM MetodoPagamentoEndereco__c WHERE Endereco__c = :pEndereco.Id ORDER BY Name ]; if (!listPaymentsOriginal.isEmpty()) { Integer i = 1; mapPaymentsOriginal = new Map<Id,MetodoPagamentoEndereco__c >(); for (MetodoPagamentoEndereco__c iPayment : listPaymentsOriginal) { mapPaymentsOriginal.put(iPayment.Id, iPayment.clone(true, true, true, true)); Payment_cls cPayment = new Payment_cls(); cPayment.payment = iPayment;//.clone(true, true, true, true); cPayment.id = i; cPayment.isDeleted = false; listPaymentsAddress.add(cPayment); //setando o Id do método pagamento selecionado como principal. if (cPayment.payment.Principal__c) { selectedPrincipalId = cPayment.Id; } i++; } } } } } public PageReference deletePayment() { for (Payment_cls icPayment : listPaymentsAddress) { if (icPayment.id == paymentIdSelected) { icPayment.isDeleted = !icPayment.isDeleted; break; } } return null; } public PageReference savePaymentInList() { paymentAux = new Payment_cls(); String methodPaymentId = Apexpages.currentPage().getParameters().get('methodPaymentId'); String methodPaymentName = Apexpages.currentPage().getParameters().get('methodPaymentName'); if (hasMethod(methodPaymentId)) { ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR,'O método de pagamento "' + methodPaymentName + '" já está cadastrado.')); } else { paymentAux.payment = new MetodoPagamentoEndereco__c( Inicio__c = Date.today(), Principal__c = true, MetodoPagamento__c = methodPaymentId, Name = methodPaymentName ); Payment_cls cPayment = new Payment_cls(); cPayment = paymentAux; //cPayment.payment.Principal__c = listPaymentsAddress.isEmpty(); cPayment.id = getMajorId(); cPayment.isDeleted = false; listPaymentsAddress.add(cPayment); selectedPrincipalId = cPayment.id ; } return null; } public void doSelectPrincipal() { for (Payment_cls icPayment : listPaymentsAddress) { boolean isPrincipal = icPayment.id == selectedPrincipalId; icPayment.payment.Principal__c = isPrincipal; } } public boolean isValid(){ boolean result = true; result = !isEmpty(listPaymentsAddress); if (result) { list<Payment_cls> listWithoutDelete = new list<Payment_cls>(); for (Payment_cls iPayment :listPaymentsAddress){ if (!iPayment.isDeleted) { listWithoutDelete.add(iPayment); if (Functions.IsNotEmptyOrNull(iPayment.payment.Id)){ if (!existingPaymentIsValid(iPayment.payment)) result = false; } else { if (!newerPaymentIsValid(iPayment.payment)) result = false; } } } if (result ) result = !isEmpty(listWithoutDelete); } return result; } public void doSave(Endere_o_Relacionado__c pEndereco) { if (pEndereco != null && Functions.isNotEmptyOrNull(pEndereco.Id)) { List<MetodoPagamentoEndereco__c> auxListInsertPayment = new List<MetodoPagamentoEndereco__c>(); List<MetodoPagamentoEndereco__c> auxListUpdatePayment = new List<MetodoPagamentoEndereco__c>(); List<MetodoPagamentoEndereco__c> auxListDeletePayment = new List<MetodoPagamentoEndereco__c>(); for (Payment_cls cPayment : listPaymentsAddress) { if (!Functions.isNotEmptyOrNull(cPayment.payment.Id)) { if (!cPayment.isDeleted) { cPayment.payment.Endereco__c = pEndereco.Id; auxListInsertPayment.add(cPayment.payment); } } else { if (cPayment.isDeleted) { auxListDeletePayment.add(cPayment.payment); } else { auxListUpdatePayment.add(cPayment.payment); } } } if (!auxListDeletePayment.isEmpty()) { delete auxListDeletePayment; } if (!auxListUpdatePayment.isEmpty()) { update auxListUpdatePayment; } if (!auxListInsertPayment.isEmpty()) { insert auxListInsertPayment; } } } }My testClass
private class PaymentManager_tst { static testMethod void myUnitTest() { //istancia do construtor PaymentManager payment = new PaymentManager(); List<MetodoPagamentoEndereco__c> MetodoPagamentoEnderecoVazio = new List<MetodoPagamentoEndereco__c>(); Endere_o_Relacionado__c endereco = new Endere_o_Relacionado__c( Name = 'teste' ); insert endereco; MetodoPagamento__c metodoPagamento = new MetodoPagamento__c( Codigo__c = 'teste', Fim__c = Date.valueOf(Datetime.now().addDays(-10)), Inicio__c = Date.valueOf(Datetime.now().addDays(-9)), Observacao__c = 'teste de Observação' ); insert metodoPagamento; MetodoPagamentoEndereco__c metodoPagamentoEndereco = new MetodoPagamentoEndereco__c( Name = 'Teste', Endereco__c = endereco.Id, Fim__c = Date.valueOf(Datetime.now().addDays(-10)), Inicio__c = date.today(), Principal__c = true, MetodoPagamento__c = metodoPagamento.Id ); insert metodoPagamentoEndereco; //Métodos publicos do construtor payment.loadPaymentsByAddress(endereco); payment.doSave(endereco); payment.savePaymentInList(); payment.savePaymentInList(); payment.isValid(); payment.doSelectPrincipal(); payment.deletePayment(); } }
- SolidLucas
- January 08, 2015
- Like
- 1
query is not returning value visualforce
Well i'm developing a visualforce page where have a query that returns the value of the fields of my account object, but is not returning nothing on my search. someone could help me?
visualforce page
<apex:page standardController="account" extensions="AccountSearch_clt"> <apex:sectionHeader title="Pesquisa de Cliente" /> <apex:form id="theform"> <apex:pagemessages escape="false" id="messages" /> <apex:pageBlock title="Pesquisa de Cliente ERP" > <apex:pageBlockSection columns="2" > <apex:pageBlockSection columns="1" > <apex:inputText value="{!PesquisaCodCliente}" label="Codigo Cliente/Endereco"> <apex:inputText value="{!PesquisaCodEndereco}" /> - </apex:inputText> <apex:inputText value="{!cia}" label="Cia/Documento"> <apex:inputText value="{!tipoDocumento}" html-autocomplete="off" /> - </apex:inputText> <apex:inputText value="{!NumeroDocumento}" label="Numero Documento/ Razao Social"> <apex:inputText value="{!RazaoSocial}" html-autocomplete="off" /> - </apex:inputText> <apex:inputText value="{!NomeFantasia}" label="Nome Fantasia/ CEP"> <apex:inputText value="{!RazaoSocial}" html-autocomplete="off" /> - </apex:inputText> </apex:pageBlockSection> </apex:pageBlockSection> <apex:pageBlockButtons location="top"> <apex:commandButton value="Pesquisar" action="{!doSearch}" rerender="theform" /> <apex:commandButton value="Cancelar" action="{!cancel}" style="color:red;" /> </apex:pageBlockButtons> </apex:pageBlock> <c:PageBlockTableEnhancerADV targetPbTableIds="pbt" pageSizeOptions="5,10,15,30" defaultPageSize="5" enableExport="false" /> <apex:pageBlock mode="maindetail" id="pb"> <apex:pageblockTable value="{!listAccPesquisa}" var="item" id="pbt"> <apex:column value="{!item.CustomerNumber__c}" /> <apex:column value="{!item['Name']}"/> <apex:column value="{!item.Id}" /> <apex:column value="{!item .Tipo_de_Documento__c}" /> </apex:pageblockTable> </apex:pageBlock> </apex:form> </apex:page>
public with sharing class AccountSearch_clt { public string NomeFantasia {get;set;} public string Pesquisastring {get;set;} public string PesquisaCodCliente {get;set;} public string PesquisaCodEndereco {get;set;} public string cia {get;set;} public string tipoDocumento {get;set;} public string RazaoSocial {get;set;} public string NumeroDocumento {get;set;} public string Temp {get;set;} public list <Account> listAccPesquisa{get;set;} /********** construtor contructor ***********/ public AccountSearch_clt(ApexPages.StandardController controller) { } public void getAccounts(){ String stringComplemento = ''; string searchquery='SELECT name, id, Tipo_de_Documento__c, SiteNumber__c, RazaoSocial__c, NomeFantasia__c, '+ 'N_mero_do_Documento__c, CustomerNumber__c, Cia__c FROM Account '; if(PesquisaString != ''){ stringComplemento = ' WHERE name LIKE '+ '\'%' +PesquisaString+'%\''; } if(NomeFantasia != '' && NomeFantasia!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' NomeFantasia__c LIKE '+ '\'' +NomeFantasia+'\''; } if(PesquisaCodCliente!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' CustomerNumber__c LIKE '+ '\'' +PesquisaCodCliente+'\''; } if(PesquisaCodEndereco!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' SiteNumber__c LIKE '+ '\'' +PesquisaCodEndereco+'\''; } if(cia!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' Cia__c LIKE '+ '\'' +cia+'\''; } if(tipoDocumento!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' Tipo_de_Documento__c LIKE '+ '\'' +tipoDocumento+'\''; } if(RazaoSocial!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' RazaoSocial__c LIKE '+ '\'' +RazaoSocial+'\''; } if(NumeroDocumento!= ''){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' N_mero_do_Documento__c LIKE '+ '\'' +NumeroDocumento+'\''; } searchquery = searchquery + stringComplemento; Temp=searchquery ; listAccPesquisa = Database.query(searchquery); } public void doSearch(){ getAccounts(); } }
- SolidLucas
- November 25, 2014
- Like
- 1
Case Trigger help
I'm trying to create a trigger that updates my campaign members status after a lead or a contact fills a web to case form, my web to case is working fine is getting the id through a javascript,but my trigger isn't working. Someone could help me?
Here is my code:
trigger bi_WebToCaseLead on Case (before insert) { Set<String> setCampaignMail = new Set<String>(); //List<CampaignMember> listCm = [SELECT Id,Lead.Email,LeadId,ContactId,Contact.Name,Contact.Email,CampaignId FROM CampaignMember WHERE Campaign.IsActive = true]; List<CampaignMember> listAg = [SELECT Id,Lead.Email,LeadId,ContactId,Contact.Name,Contact.Email,CampaignId FROM CampaignMember WHERE Campaign.IsActive = true AND (Lead.Email IN :setCampaignMail OR Contact.Email IN :setCampaignMail)]; for(CampaignMember cm : listAg){ for(Case caso : Trigger.new){ if(!setCampaignMail.contains(caso.SuppliedEmail)){ setCampaignMail.add(caso.SuppliedEmail); } if(caso.ChaveCampanha__c != null && cm.CampaignId.equals(caso.ChaveCampanha__c)){ cm.Status = 'Respondido'; caso.RelacionamentoLead__c = cm.LeadId; } } } update listAg; }
- SolidLucas
- October 15, 2015
- Like
- 0
Trigger help before insert
this is my code!
trigger bi_WebToCaseLead on Case (before insert) { List<CampaignMember> listCm = [SELECT Id,Lead.Email,LeadId,CampaignId FROM CampaignMember WHERE CampaignId = '701190000001F5l']; Map<String, CampaignMember> mapCm = new Map<String, CampaignMember>(); for(CampaignMember cm : listCm){ mapCm.put(cm.Lead.Email, cm); } for(Case caso : Trigger.new){ Case tempCase = caso; CampaignMember tempCampaign = mapCm.get(caso.SuppliedEmail); if(tempCampaign != null && caso.ChaveCampanha__c == '701190000001F5l'){ tempCampaign.Status = 'Respondido'; caso.RelacionamentoLead__c = tempCampaign.LeadId; update tempCampaign; } } }
- SolidLucas
- September 29, 2015
- Like
- 0
Class test help
My class
global class btn_EnviarCampanha { webservice static String btn_EnviarCampanha(Id mId) { String msg = ''; try{ List<CampaignMember> listMember = [SELECT Id,CampaignId,Status FROM CampaignMember WHERE Status = 'Aguardando Envio' AND CampaignId =:mId]; List<CampaignMember> listMemberUpdated = new List<CampaignMember>(); for(CampaignMember cm :listMember){ cm.Status = 'Enviado'; listMemberUpdated.add(cm); } update listMemberUpdated; msg = 'Email enviado com sucesso!'; }catch(Exception ex){ msg = 'Erro ao enviar mensagem!'; } return msg; } }My test class
@isTest private class tst_btn_EnviarCampanha { @isTest static void test_method_one() { Lead lead = new Lead( FirstName = 'Lucas', LastName = 'ze' ); insert lead; Campaign cam = new Campaign( Name = 'Venda de Seminovos' ); insert cam; CampaignMember membroCampanha = new CampaignMember( //Status = 'Aguardando Envio', CampaignId = cam.Id, LeadId = lead.Id ); insert membroCampanha; update membroCampanha; btn_EnviarCampanha.btn_EnviarCampanha(membroCampanha.Id); } }
- SolidLucas
- September 28, 2015
- Like
- 0
Trigger help,Campaign Member Status
trigger ai_WebToCaseLead on Case (after insert) { List<CampaignMember> listCm = [SELECT Id,Lead.Email,CampaignId FROM CampaignMember WHERE CampaignId = '701190000001F5l']; for(Case caso : Trigger.new){ System.debug('caso'); for(CampaignMember cm : listCm){ System.debug('caso'); if(cm.Lead.Email == caso.SuppliedEmail && caso.ChaveCampanha__c == '701190000001F5l'){ cm.Status = 'Respondido'; caso.ParentId = cm.Lead.Id; update cm; update caso; System.debug(cm); System.debug(caso); } } } }
Regards!
Lucas
- SolidLucas
- June 30, 2015
- Like
- 0
NullPoiter Exception help
My class
public with sharing class ErrorMessage_ctl { /**************** *Public Variables *****************/ private String msg; private String retURL; public boolean showButton {get;set;} /****************** *Constructor ******************/ public ErrorMessage_ctl(){ msg = System.currentPageReference().getParameters().get('msg'); retURL = System.currentPageReference().getParameters().get('retURL'); if(functions.isNotEmptyOrNull(msg)){ ApexPages.addmessage(new ApexPages.message( ApexPages.severity.ERROR, msg )); }else{ ApexPages.addmessage(new ApexPages.message( ApexPages.severity.ERROR, 'Ocorreu um erro inesperado!')); } if(functions.isNotEmptyOrNull(retURL)){ showButton = true; }else{ showButton = false; } } //retorna a página principal public PageReference errorReturn(){ PageReference page = new PageReference(retURL); page.setRedirect(true); return page; } }
my test class
@isTest private class ErrorMessage_tst_ctl { static testMethod void myUnitTest() { ErrorMessage_ctl controlador = new ErrorMessage_ctl(); Test.setCurrentPageReference(new PageReference('msg')); System.currentPageReference().getParameters().get('msg'); //retURL = System.currentPageReference().getParameters().get('retURL'); controlador.showButton = true; controlador.showButton = false; controlador.errorReturn(); } }
- SolidLucas
- January 13, 2015
- Like
- 0
Test Class Help
My apexClass
public with sharing class PaymentManager { /* * PRIVATE VARIABLES */ private Map<Id, MetodoPagamentoEndereco__c> mapPaymentsOriginal; /* * PUBLIC VARIABLES */ public String title {get;set;} public Payment_cls paymentAux {get;set;} public List<Payment_cls> listPaymentsAddress {get;set;} public Integer selectedPrincipalId {get;set;} public Integer paymentIdSelected {get;set;} /* * SUBCLASSES */ private class Payment_cls { public Integer id {get;set;} public MetodoPagamentoEndereco__c payment {get;set;} public boolean isDeleted {get;set;} public Payment_cls() { payment = new MetodoPagamentoEndereco__c(); } } /* * CONSTRUCTOR */ public PaymentManager(){ title = 'Métodos de Pagamento'; paymentAux = new Payment_cls(); } /* * PRIVATE METHODS */ /* * este método identifica se já exsite um método de pagamento cadastrado para o endereço. */ private boolean hasMethod(String pMethodId){ boolean result = false; for (Payment_cls iPayment: listPaymentsAddress){ if (iPayment.payment.MetodoPagamento__c == pMethodId) { result = true; break; } } return result; } private boolean isEmpty(list<Payment_cls> pList){ boolean result = false; if (pList.isEmpty()) { ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR,'É necessårio informar ao menos um método de pagamento para prosseguir.')); result = true; } return result; } private boolean existingPaymentIsValid(MetodoPagamentoEndereco__c pMetodo){ boolean result = true; MetodoPagamentoEndereco__c old = mapPaymentsOriginal.get(pMetodo.Id); if (pMetodo.Inicio__c < old.Inicio__c) { pMetodo.Inicio__c.addError('Não é permitido alterar a data de início para uma data anterior a previamente cadastrada: ' + old.Inicio__c.format()); result = false; } else result = finalDateIsMajor(pMetodo); return result; } private boolean newerPaymentIsValid(MetodoPagamentoEndereco__c pMetodo){ boolean result = true; if (pMetodo.Inicio__c < Date.Today()) { pMetodo.Inicio__c.addError('Não é permitido o cadastramento de um novo método de pagamento com data retroativa.'); result = false; } else result = finalDateIsMajor(pMetodo); return result; } private boolean finalDateIsMajor(MetodoPagamentoEndereco__c pMetodo){ boolean result = true; if ( pMetodo.Fim__c != null){ if (pMetodo.Inicio__c > pMetodo.Fim__c) { pMetodo.Inicio__c.addError('A data de início não pode ser maior que a data final.'); result = false; } } return result; } private Integer getMajorId() { Integer retorno = 0; for (Payment_cls icPayment : listPaymentsAddress) { if (icPayment.id > retorno) { retorno = icPayment.id; } } return retorno + 1; } /* * PUBLIC METHODS */ public void loadPaymentsByAddress(Endere_o_Relacionado__c pEndereco) { if (listPaymentsAddress == null) { listPaymentsAddress = new List<Payment_cls>(); if (Functions.isNotEmptyOrNull(pEndereco.Id)) { list<MetodoPagamentoEndereco__c> listPaymentsOriginal = [ SELECT Id, Name, Inicio__c, Fim__c, Principal__c, MetodoPagamento__c FROM MetodoPagamentoEndereco__c WHERE Endereco__c = :pEndereco.Id ORDER BY Name ]; if (!listPaymentsOriginal.isEmpty()) { Integer i = 1; mapPaymentsOriginal = new Map<Id,MetodoPagamentoEndereco__c >(); for (MetodoPagamentoEndereco__c iPayment : listPaymentsOriginal) { mapPaymentsOriginal.put(iPayment.Id, iPayment.clone(true, true, true, true)); Payment_cls cPayment = new Payment_cls(); cPayment.payment = iPayment;//.clone(true, true, true, true); cPayment.id = i; cPayment.isDeleted = false; listPaymentsAddress.add(cPayment); //setando o Id do método pagamento selecionado como principal. if (cPayment.payment.Principal__c) { selectedPrincipalId = cPayment.Id; } i++; } } } } } public PageReference deletePayment() { for (Payment_cls icPayment : listPaymentsAddress) { if (icPayment.id == paymentIdSelected) { icPayment.isDeleted = !icPayment.isDeleted; break; } } return null; } public PageReference savePaymentInList() { paymentAux = new Payment_cls(); String methodPaymentId = Apexpages.currentPage().getParameters().get('methodPaymentId'); String methodPaymentName = Apexpages.currentPage().getParameters().get('methodPaymentName'); if (hasMethod(methodPaymentId)) { ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR,'O método de pagamento "' + methodPaymentName + '" já está cadastrado.')); } else { paymentAux.payment = new MetodoPagamentoEndereco__c( Inicio__c = Date.today(), Principal__c = true, MetodoPagamento__c = methodPaymentId, Name = methodPaymentName ); Payment_cls cPayment = new Payment_cls(); cPayment = paymentAux; //cPayment.payment.Principal__c = listPaymentsAddress.isEmpty(); cPayment.id = getMajorId(); cPayment.isDeleted = false; listPaymentsAddress.add(cPayment); selectedPrincipalId = cPayment.id ; } return null; } public void doSelectPrincipal() { for (Payment_cls icPayment : listPaymentsAddress) { boolean isPrincipal = icPayment.id == selectedPrincipalId; icPayment.payment.Principal__c = isPrincipal; } } public boolean isValid(){ boolean result = true; result = !isEmpty(listPaymentsAddress); if (result) { list<Payment_cls> listWithoutDelete = new list<Payment_cls>(); for (Payment_cls iPayment :listPaymentsAddress){ if (!iPayment.isDeleted) { listWithoutDelete.add(iPayment); if (Functions.IsNotEmptyOrNull(iPayment.payment.Id)){ if (!existingPaymentIsValid(iPayment.payment)) result = false; } else { if (!newerPaymentIsValid(iPayment.payment)) result = false; } } } if (result ) result = !isEmpty(listWithoutDelete); } return result; } public void doSave(Endere_o_Relacionado__c pEndereco) { if (pEndereco != null && Functions.isNotEmptyOrNull(pEndereco.Id)) { List<MetodoPagamentoEndereco__c> auxListInsertPayment = new List<MetodoPagamentoEndereco__c>(); List<MetodoPagamentoEndereco__c> auxListUpdatePayment = new List<MetodoPagamentoEndereco__c>(); List<MetodoPagamentoEndereco__c> auxListDeletePayment = new List<MetodoPagamentoEndereco__c>(); for (Payment_cls cPayment : listPaymentsAddress) { if (!Functions.isNotEmptyOrNull(cPayment.payment.Id)) { if (!cPayment.isDeleted) { cPayment.payment.Endereco__c = pEndereco.Id; auxListInsertPayment.add(cPayment.payment); } } else { if (cPayment.isDeleted) { auxListDeletePayment.add(cPayment.payment); } else { auxListUpdatePayment.add(cPayment.payment); } } } if (!auxListDeletePayment.isEmpty()) { delete auxListDeletePayment; } if (!auxListUpdatePayment.isEmpty()) { update auxListUpdatePayment; } if (!auxListInsertPayment.isEmpty()) { insert auxListInsertPayment; } } } }My testClass
private class PaymentManager_tst { static testMethod void myUnitTest() { //istancia do construtor PaymentManager payment = new PaymentManager(); List<MetodoPagamentoEndereco__c> MetodoPagamentoEnderecoVazio = new List<MetodoPagamentoEndereco__c>(); Endere_o_Relacionado__c endereco = new Endere_o_Relacionado__c( Name = 'teste' ); insert endereco; MetodoPagamento__c metodoPagamento = new MetodoPagamento__c( Codigo__c = 'teste', Fim__c = Date.valueOf(Datetime.now().addDays(-10)), Inicio__c = Date.valueOf(Datetime.now().addDays(-9)), Observacao__c = 'teste de Observação' ); insert metodoPagamento; MetodoPagamentoEndereco__c metodoPagamentoEndereco = new MetodoPagamentoEndereco__c( Name = 'Teste', Endereco__c = endereco.Id, Fim__c = Date.valueOf(Datetime.now().addDays(-10)), Inicio__c = date.today(), Principal__c = true, MetodoPagamento__c = metodoPagamento.Id ); insert metodoPagamentoEndereco; //Métodos publicos do construtor payment.loadPaymentsByAddress(endereco); payment.doSave(endereco); payment.savePaymentInList(); payment.savePaymentInList(); payment.isValid(); payment.doSelectPrincipal(); payment.deletePayment(); } }
- SolidLucas
- January 08, 2015
- Like
- 1
Google Map on Custom detail page
- Rony57
- December 30, 2015
- Like
- 0
test class help!
Somenone could help me to do a class test for this method?
private void loadBase(){ listBase = [ SELECT Id, Name, QtdePontos__c, QtdeUnidadesConsumidoras__c, QtdeSaloesFestas__c, QtdeZeladorias__c, InvestimentoUG__c, InvestimentoCliente__c, InicioObra__c, InicioConsumo__c, Comentarios__c, IndexController__c, AnaliseInvestimento__c, (SELECT Id, Name, Quantidade__c, AiInstalacao__c, ValorOrcado__c, Servico__c, IndexController__c FROM InstalacoesServicos__r), (Select Id, Name, Atividade__c, Instalacao__c, Responsabilidade__c, Valor__c From Itens_de_Obras__r), (Select Id, Name, Quantidade__c, Kit__c, Kit__r.Valor__c, Kit__r.Descricao__c, Instalacao__c From KitsInstalacoes__r), (Select Id, Name, Comodato__c, Quantidade__c, ValorOrcado__c, Instalacao__c, EquipamentoMaterial__c, EquipamentoMaterial__r.Tipo__c, EquipamentoMaterial__r.Name From EquipamentosMateriaisInstalacoes__r), (Select Id, Name, ConsumoPrevistoMensal__c, FatorIncremento__c, FilialAbastecedora__c, IcmsOrigem__c, IcmsDestino__c, PrecoVenda__c, Produto__c, ExRefinaria__c From InstalacoesProdutos__r) FROM AiInstalacao__c WHERE AnaliseInvestimento__c = :analiseInvestimento.Id ]; mapService = new Map<Id, list<InstalacaoServico__c>>(); mapObras = new Map<Id, list<AiItemObra__c>>(); mapKits = new Map<Id, list<AiKitInstalacao__c>>(); mapMateriais = new Map<Id, list<AiEquipamentoMaterialInstalacao__c>>(); mapConsumo = new Map<Id, list<AiConsumoInstalacao__c>>(); Set<Id> setBaseId = new Set<Id>(); for (AiInstalacao__c mBase: listBase){ mapService.put(mBase.Id, mBase.InstalacoesServicos__r); mapObras.put(mBase.Id, mBase.Itens_de_Obras__r); mapKits.put(mBase.Id, mBase.KitsInstalacoes__r); mapMateriais.put(mBase.Id, mBase.EquipamentosMateriaisInstalacoes__r); mapConsumo.put(mBase.Id, mBase.InstalacoesProdutos__r); //colecionando lista de Id das Instacões do projeto setBaseId.Add(mBase.Id); } loadConsumo(setBaseId); selectFirstBase(); }
/** * Constructor **/ public AnaliseInvestimentoConsulta_ctl(ApexPages.StandardController con){ analiseInvestimento = (AnaliseInvestimento__c) con.getRecord(); loadBase(); subTabIndexActive = '0'; }
- SolidLucas
- December 29, 2015
- Like
- 0
query parameters
Hello! i want to do a query into a custom "Cia__c" field using the <apex:selectList> well i've created a method like this
public List<SelectOption> getCiaOptions() { List<SelectOption> CiaOptions = new List<SelectOption>(); CiaOptions.add(new SelectOption('','--Nenhum--')); CiaOptions.add(new SelectOption('a07o0000002Quf3AAC','Test1')); CiaOptions.add(new SelectOption('a07o0000002Quf8AAC','Test2')); return CiaOptions; } }VisualForce!
<apex:selectList value="{!Cia}" multiselect="false" size="1" label="Cia"> <apex:selectOptions value="{!CiaOptions}" /> </apex:selectList>
Someone could help me i've been trying but without success.
Thanks!
- SolidLucas
- December 02, 2014
- Like
- 0
Checkbox query problem
public void getAccounts(){ String stringComplemento = ''; string searchquery='SELECT name, id, Tipo_de_Documento__c, SiteNumber__c, RazaoSocial__c, NomeFantasia__c, '+ 'N_mero_do_Documento__c, CustomerNumber__c, Cia__c,Ativo__c FROM Account '; if(PesquisaString != '' && PesquisaString!=null){ stringComplemento = ' WHERE name LIKE '+ '\'%' +PesquisaString+'%\''; } if(NomeFantasia != '' && NomeFantasia!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' NomeFantasia__c LIKE '+ '\'' +NomeFantasia+'\''; } if(PesquisaCodCliente!= '' && PesquisaCodCliente!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' CustomerNumber__c LIKE '+ '\'' +PesquisaCodCliente+'\''; } if(PesquisaCodEndereco!= '' && PesquisaCodEndereco!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' SiteNumber__c LIKE '+ '\'' +PesquisaCodEndereco+'\''; } if(cia!= '' && cia!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' Cia__c LIKE '+ '\'' +cia+'\''; } if(tipoDocumento!= '' && tipoDocumento!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' Tipo_de_Documento__c LIKE '+ '\'' +tipoDocumento+'\''; } if(RazaoSocial!= '' && RazaoSocial!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' RazaoSocial__c LIKE '+ '\'' +RazaoSocial+'\''; } if(NumeroDocumento!= '' && NumeroDocumento!=null){ if(stringComplemento!=''){ stringComplemento += ' and '; }else{ stringComplemento += ' where '; } stringComplemento += ' N_mero_do_Documento__c LIKE '+ '\'' +NumeroDocumento+'\''; } \********************* HERE IS WHERE I'M HAVING TROUBLE if(ClienteAtivo){ stringComplemento += 'WHERE Ativo__c = true '; } searchquery = searchquery + stringComplemento; Temp=searchquery ; listAccPesquisa = Database.query(searchquery); }
f is not.
- SolidLucas
- November 27, 2014
- Like
- 0
List has no rows for assignment to SObject VisualForce
Hello guys, i'm trying to create a visualforce that returns the account and contacts, of the logged user but its returning this error List has no rows for assignment to SObject.
this is my controller
public with sharing class AnalyticsRevendaController { public Account contas {get;set;} public Contact contato {get;set;} public User usuario {get;set;} public String userId {get;set;} // Detecta os valores do usuário ativo public User activeUser = [SELECT AccountId,ContactId FROM User WHERE Id = :userId LIMIT 1]; public String userAccount = activeUser.AccountId; public String userContact = activeUser.ContactId; public AnalyticsRevendaController(){ //Retorna os dados do usuário Logado contas = new Account(); userId = UserInfo.getUserId(); if(userId != null && ''.equals(userId)) getAccount(); } //retorna os valores da conta do usuário ativo. public Account getAccount(){ //Set<Id> setConta = new Set<Id>(); List<Account> listContas = [SELECT Id,Name,OwnerId FROM Account WHERE Id = :userAccount]; if(listContas.size()> 0) contas = listContas[0]; return contas; } //retorna os valores do contato ativo. public Contact getContact(){ contato = [Select c.LastName, c.FirstName, c.AccountId,c.Email From Contact c WHERE Id=:userContact]; return contato; } }
my visualforce
<apex:page controller="AnalyticsRevendaController"> <apex:form> <apex:pageBlock> <apex:pageBlockSection title="Conta"> <apex:outputtext value ="{!contas.Name}" /> <apex:outputtext value ="{!contas.OwnerId}" /> </apex:pageBlockSection> <apex:pageBlockSection title="Contato"> <apex:outputtext value ="{!Contact.FirstName}" /> <apex:outputtext value ="{!Contact.LastName}" /> <apex:outputtext value ="{!Contact.Email}" /> </apex:pageBlockSection> <apex:pageBlockSection title="Usuario"> <apex:outputtext value ="{!$User.FirstName}" /> <apex:outputtext value ="{!$User.LastName}" /> <apex:outputtext value ="{!$User.Email}" /> <apex:outputtext value ="{!userId}" /> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
- SolidLucas
- November 19, 2014
- Like
- 0
How to load data from a logged user
Hello guys, i would like to know how can i load data from contact of the logged user. someone could give some example
Regards,Lucas.
- SolidLucas
- November 17, 2014
- Like
- 0
Trigger to update TeamMemberRole
- SolidLucas
- October 21, 2014
- Like
- 0