• Nirdesh_Bhatt
  • NEWBIE
  • 47 Points
  • Member since 2016
  • SFDC Developer
  • Incapsulate


  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 35
    Replies
Hi all,

I got a requirement like delete records based on criteria( to give the criteria i should take values from vf page), and I have to delete the records using batch class. And want to run this batch class once per month. How can i schedule this batch class. and i want get records list from batch class to controller class. Please anybody can help me.
//Controller class

public with sharing class DeleteSelectedRecords{
public List<Sobject> reclist {get;set;}
public List<SelectOption> options{get;set;}
public String Recname{get;set;}
public String selectedOpt{get;set;}
public boolean criteriaRend{get;set;}

public DeleteSelectedRecords(){
    reclist = new List<Sobject>();
    options = new List<SelectOption>();
    Map<String,Schema.sobjectType> objNames = Schema.getglobalDescribe();
    
    options.add(new SelectOption('--None--','--None--'));
    for(String s: objNames.keyset())
    {
        if(objNames.get(s).getDescribe().isAccessible()==True && objNames.get(s).getDescribe().isUpdateable()==True){
        options.add(new SelectOption(objNames.get(s).getDescribe().getLabel(),s));
        }
    }     
}

public void showpb(){
    if(selectedOpt!='--None--'){
        criteriaRend= true;
    }
}

public void getRecords(){
    //reclist = new List<Sobject>();
    String query = 'select id, name from '+selectedOpt+' where name='+'\''+Recname+'\'';
    deleteSubscribers ds = new deleteSubscribers(query);
    Id batchpid = Database.executeBatch(ds);
    System.debug('batchpid @@@'+batchpid );
    
    System.debug('ds.accountMap @@@'+ds.accountMap );
    reclist =ds.listrecord;
    System.debug('reclist @@@'+reclist );
    
}
}


 
//Batch class

global with sharing class deleteSubscribers implements Database.Batchable<sObject>,Database.Stateful{
    global final String Query;
    global List<Sobject> listrecord{get;set;}
    global Map<Id, sObject> accountmap;

    
    global deleteSubscribers(String q){
    accountmap = new Map<Id, Account> ();
    listrecord = new List<Sobject>();
    System.debug('query @@@'+q);
        Query=q;
    }

    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC,List<Sobject> scope){
       // listrecord = new List<Sobject>();
        listrecord = scope;
        System.debug('BatchableContext@@@'+BC);
        System.debug('sCOPE listrecord  @@@'+listrecord );
        for(Sobject s:scope){
            accountmap.put(s.id,s);
        }
        System.debug('accountmap @@@'+accountmap);
        delete scope;
        System.debug('accountmap @@@'+accountmap);
        
    }

    global void finish(Database.BatchableContext BC){}
}
 
//VF page
<apex:page controller="DeleteSelectedRecords">
<apex:pagemessages ></apex:pagemessages>
<apex:form >
<apex:pageblock >

    <apex:pageBlockSection Title="Select Object" >
        <apex:selectList size="1" value="{!selectedOpt}"  label="Select the object">
            <apex:selectOptions value="{!options}"  />
            <apex:actionSupport event="onchange"  rerender="crsh" action="{!showpb}"/>
        </apex:selectList>  
    </apex:pageBlockSection>
    <apex:pageBlockSection Title="Enter criteria"  id="crsh">
        Enter criteria to delete records!
        <apex:inputText label="Record name is equalto" value="{!recName}"  rendered="{!criteriaRend}" />
       <center> <apex:commandButton action="{!getRecords}" value="Get Records"  rendered="{!criteriaRend}"/></center>
    </apex:pageBlockSection>
    <apex:pageblocksection title="Selected Records to be Deleted" rendered="{!criteriaRend}" columns="1">
       <apex:pageBlockTable value="{!reclist}" var="rec" rendered="{!if(reclist.size==0,false,true)}">
            <apex:column headerValue="Id"><apex:outputText value="{!rec.id}"/></apex:column>
        </apex:pageBlockTable>

    </apex:pageblocksection>
</apex:pageblock>
</apex:form>
</apex:page>

 
Hi Community,

How to insert/update bulk records of Managed Package Objects? 
I have 2 custom object customobjt1__c and customobjt2__c, both have product lookup fields. 
If both product lookup field is the same then in customobjt1__c  we need to insert the record name of customobjt2__c that is also a lookup in customobjt1__c. so how to achieve that? 
 
I am trying to display cases based on the Account selection 
.html

<template>
  <h6> Showing Cases based on Account Selected on this Value Plan</h6>
  <lightning-datatable data={data} columns={columns} key-field="Id">
  </lightning-datatable>
</template>
--------------------------------------------------------
.js
import { LightningElement ,api,wire,track} from 'lwc';
import getAllCase from '@salesforce/apex/GetAllCases.getAllCase';


export default class DatatableEx12 extends LightningElement {
    @track columns = [{
            label: 'Case Number',
            fieldName: 'CaseNumber',
            type: 'Auto Number',
            sortable: true
        },
        {
            label: 'Subject',
            fieldName: 'Subject',
            type: 'Text(255)'
        }, {
            label: 'Status',
            fieldName: 'Status',
            type: 'Picklist'
        }, {
            label: 'Case Type',
            fieldName: 'Type',
            type: 'Picklist'
        }
    ];
    @track error;
    @track data ;
    @api recordId;
    @wire(getAllCase)
    wiredOpps({error,data}) {
        if (data) {
            this.data = data;
            console.log(data);
            console.log(JSON.stringify(data, null, '\t'));
        } else if (error) {
            this.error = error;
        }
    }
    
    
}
--------------------------------------------------------
public with sharing class GetAllCases {   

    @AuraEnabled(cacheable=true)
    public static List<Case> getAllCase(String accountId) {
    this.acnt= (Account)controller.getRecord();

     Account acc = [Select id FROM Account where id = :acnt.id];
}
}

 
I have to Insert a Contact but before inserting a contact I have to check that related account is
there or not if the related account is there then insert a Contact with that account ID only else
insert an account and then insert a contact with that related account ID.     


Thanks,
Nirdesh Bhatt

 
Hi Community,

How to insert/update bulk records of Managed Package Objects? 
I have 2 custom object customobjt1__c and customobjt2__c, both have product lookup fields. 
If both product lookup field is the same then in customobjt1__c  we need to insert the record name of customobjt2__c that is also a lookup in customobjt1__c. so how to achieve that? 
 
I want to set record type while creating record in lightning component through e.force:createRecord. But I am not able to do so.
I tried using custom label and even I tried hardcoding still It is not showing correct record type and it is showing default record type for record creation.
Please find below code for javascript controller:
({
    doInit: function (component, event, helper) {
        var recId = component.get("v.recordId");
        console.log(recId);

        var action = component.get("c.getdetails");
        action.setParams({
            "sId": recId
        });
        action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                $A.get("e.force:closeQuickAction").fire();
                console.log("Success" + JSON.stringify(response.getReturnValue()));
                component.set("v.sampleRequest", response.getReturnValue());
                var sampProd = component.get("v.sampleRequest");
                
                 if(sampProd.Lead__c === sampProd.Contact__c){
                    var Name = sampProd.Contact__r.Name;
                }
                else
                {
                   var Name = sampProd.Lead__r.Name; 
                }
                


                var createSampleProduct = $A.get("e.force:createRecord");
                var staticRecordLabel = $A.get("$Label.c.UsCanSampleProductRecordType");
                createSampleProduct.setParams({
                    "entityApiName": "Sample_Product__c",
                    "RecordTypeId": '0121b0000004aeSAAQ',
                    "defaultFieldValues": {
                        'Sample_Request__c' : component.get("v.recordId"),
                        'Name__c': Name,                    
                    }
                });
                createSampleProduct.fire();
            } else {
                console.log("Fail");
            }
        });
        $A.enqueueAction(action);
    }
})

I tried hardcoding:
              var staticRecordLabel = $A.get("$Label.c.UsCanSampleProductRecordType");
                createSampleProduct.setParams({
                    "entityApiName": "Sample_Product__c",
                    "RecordTypeId": '0121b0000004aeSAAQ',

I have tried using:

            var staticRecordLabel = $A.get("$Label.c.UsCanSampleProductRecordType");
                createSampleProduct.setParams({
                    "entityApiName": "Sample_Product__c",
                    "RecordTypeId": staticRecordLabel ,

it is just showing for 1 sec 
UsCanSampleProductRecordType and then it is taking me to record creation page with default record type.

Please help. 
Hello,

I started this new superbadge yesterday and I am wondering if there is an issue with step 7: Set up reporting for sales managers in Lightning Experience.

I believed to have done everything right () report was created, added to Account, Dashboard was created. But I received the following error: 
   
ERROR: The Opportunities Pipeline report must: 
        1. Display data for all time, 
        2. Show opportunities by stage, 
        3. Contain a funnel chart, 
        4. Provide the information required by the dashboard.
I am trying to understand it, but the requirements and point 4 in the error message makes it a little unspecific (I can dismiss error 1,2,3 easily)... What information do they want to show on the Dashboard? I created all 3 charts but I guess I am not displaying the correct metrics...    
  • September 06, 2017
  • Like
  • 0
How can I make a visualforce page readonly?
How Approval Process Works in SFDC?
What the the various types of Approval process and what the the steps to create it.
I have inherited some code and I am getting a SOQL error for below:

for(Contract c:contractListToCreate){ if(c.RecordTypeId == INITIAL_CONTRACT_RT){ contractLineItemsToCreate.addAll(CreateLineItemsForContract(c,c.Related_Opportunity__c,oppToLineItemMap.get(c.Related_Opportunity__c))); } else { contractLineItemsToCreate.addAll(CreateRenewalLineItemsForContract(c,c.Related_Opportunity__c,renewalProductList,initialSubscriptionPrice,initialSubscriptionListPrice)); } }

Can anybody help resolve this?

Thanks
Whats is the advantage of flow over workflow rules ?
I want to send bulk emails (like 10000) using batch apex .

Is there an limitation while sending mails using Messaging.SingleEmailMessage.
If it is not, then tel me which is the the way to achieve this?
Hi All,
 could anyone please help on this...
At what time use workflow rule and At what time use validation rule,explain with a example?

Thanks in Advance...
Basha
I've finally completed step 4. Test automation logic. 

It took me long, because of incorrect requirement in spec. 
The requirement is: 
When an existing maintenance request of type Repair or Routine Maintenance is Closed, you create a new maintenance request for a future routine checkup. [...] The Subject should not be null and [...]

Unfortunatelly test checks something completelly different. See below line from error log:  
Execute Anonymous: System.assertEquals(402, [select count() from Case where subject like '%AMC Spirit%']);
Moreover, the error information from within Trailhead page suggests, that this is a problem with bulk processing. 

<joke> So, if you want to finish step 4 of those badge you need to set the subject to AMC Spirit in case created by your trigger </joke>


 
I want to display cases related to loggedin user account. It is displaying empty list(it is not returning any values). When tried in query editor the query is working I am not understanding where i am making mistake can anyone pls help me with this ?
here is my code:
Controller:
public class CaseInformation{

        @AuraEnabled
        public static List<Case> getCases() {

        ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
        if(contactId == null)
        {
            return NULL;            
        }
        ID AccID  = [Select AccountID from Contact where id =: contactid ].AccountId;
            if(AccID == null){
                return NULL;
            }
            System.debug('AccountId :' + AccID + 'ContactId:' + contactId);
            List<Account> allAssocaiatedAccounts = [Select Id, name, industry from Account where Id =: AccID];
            if(allAssocaiatedAccounts.size() != 0){
            return [Select CaseNumber,Status,Priority,Type,Subject,AccountID from Case where AccountID IN: allAssocaiatedAccounts];
            }
            else {
                return NULL;
            }
    }  

}
Lightning Component:
 
<aura:component controller="CaseInformation">
<aura:attribute name="caseRows" type="Object[]"/>

    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:iteration var="cas" items="{!v.caseRows.Cases}">
                    <tr class="border_bottom">
                        <td > {!cas.CaseNumber} </td>
                        <td > {!cas.Subject}  </td>
                        <td >{!cas.Status}</td>
                        <td> <ui:outputDate format="MMM dd yyyy" value="{!cas.CreatedDate}"/> </td>
                        <td >{!cas.Account.Name}</td>
                    </tr><hr class="hrcolclass" />
                </aura:iteration>
</aura:component>

Component Controller:
 
({
    doInit : function(component, event, helper){
        helper.getAllCases(component);
     }
})
Helper:
({
    getAllCases : function(component, event, helper) {
        var action = component.get("c.getCases");

        action.setCallback(this, function(a){
            component.set("v.caseRows", a.getReturnValue());
        });
        $A.enqueueAction(action);
    }
})