• @ M Coder
  • NEWBIE
  • 70 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 26
    Questions
  • 20
    Replies
How to write a soql query to get All the records in Open Activites which are related list to a account.

User-added image 

 
Hello Guys , 
Basically i need to pass email ids present in my custom metadattype to CC in mailing logic when ever my label is IND .
in simple i need to emails  cc (those email id.) to users.

i just kept my piece of code whether i am getting the below error 

My custom metadatype contains two values 
1) label: Ind  2) Email_Address__c = ram@gmail.com sam@gmail.com hello@gmail.com
 
My piece of code  
  //calling custom metadata type
   map<string,string> emailmap = new map<string,string>();
   for(Email__mdt ce : [SELECT Label,Email_Address__c FROM Email__mdt])
   {  
   emailmap.put(ce.Label , ce.Email_Address__c);
   system.debug('emailmap====='+emailmap);
   }
    
   //Splitting CC email addresses and adding in array
     String[] ccAddresses = new String[]{};
    if(!emailmap.isEmpty())
    {
    system.debug('Map has values....');
    for(string ev:emailmap.Values())
      {
        system.debug('ev======'+ev);
        list<string> emailid = ev.split(',');
           ccAddresses.addAll(emailid);
        system.debug('ccAddresses======'+ccAddresses);
      }
    }
    
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(sendTo);
        mail.setTargetObjectId(Userinfo.getUserId());
        mail.setCCAddresses(ccAddresses);
        mail.setSaveAsActivity(false);
        mail.setWhatId(leadRecId );
       Messaging.SendEmailResult [] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

Error I am getting: 
System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Invalid to address : ram2929@gmail.com sam@gmail.com hello@gmail.com 

My analysis: i think split string is not working fine in my logic , can anyone please modify the piece of code.

 
Hello Guys , 

my scenario : 

On click of button (quick action) on account layout in lightning , based on the account id  as input , my dashboard data has to be seen in a new window  . 
basically i need to pass record id dynamicaly to dashboard
for example: account has 3 opportunities and 3 assets

User-added image
Hello All , 
How to write trigger ??

Under Account we have open activities, where we create Task and events. 
Scenario: i need to take Duedate value which is comming nearby from the below ones into a customfield Named NearbyDate__c. 

I need to write Trigger logic insuch away that for N number of Activities if i either Add or delete the activities it should sort and  gimme the result. 

for example: 

My output  should be from below example
NearbyDate__c = 9/15/2020 

User-added image

can anyone show some insights on this please. 

@thanks in adv
Hello Folks , 

Is there any soql query to retrieve all my Pagelayout Names under a recordtype in salesforce . 

or whats is the easiest way to find them . 

 
I want my workflow rule to fire based on below criteria. 
Scenario : User on  creation of case with type "Mechanical" and created time should NOT be in between  10 AM to 6 PM.  in other than above mentioned hrs i have a wf field update which will fire. I am stuck with rule how to fire .

My formula: 
ISPICKVAL( Type ,'Mechanical') && (VALUE(MID(TEXT(CreatedDate+ 0.2208),12,2))  <10.00 && VALUE(MID(TEXT(CreatedDate+ 0.2208),12,2)) < 22.00)

if i create a case at 11pm , we get VALUE(MID(TEXT(CreatedDate+ 0.2208),12,2) = 23. 

can you please correct my formuale
Hello Folks , 

I have a requirement where i need to write a formula field in workflow based on below scenario. 

part 1:My office hours are from 9AM to 6PM .
part2:  apart from these hours any New  lead  created , i want to assign alead owner to a queue (This we can do via a field update).

solution i need is for part 1 , how to write a formula for creating a new lead other than office hours and weekends to trigger my wf rule . 
can any one please help.
My formula criteria should be like :

AND (ISPICKVAL(Status, "New"), time should not be in between 9 AM to 6PM)
Hello Friends , 

I am getting the below issue in Vscode after new version update . 

"The JAVA_HOME environment variable points to a missing folder. For information on how to setup the Salesforce Apex extension, see Set Your Java Version."

I have my java version in below path :
User-added image

i have installed again ,  vscode cli , extention pack . 

can you please tell the highlighted one is corect ?
User-added image
do i need to put anything in workspace as well ???

please help me .... if any one wanted i can screen share you in gmail , my id is salesforceseekar@gmail.com .... please feel free to ping as i wanted to resolve this issue .

 
Hello Folks , 

if anyone has any idea please send me an email to salesforceseekar@gmail.com will screenshare show you the error , not understanding how to reolve.


I am getting Vscode  performance issue , i am unable to do any work due to this , i have installed the steps given below .
https://github.com/forcedotcom/salesforcedx-vscode/issues/2110 . 

please find the below error screen shots
User-added imageUser-added imageUser-added image
how to a display lookupfield and picklist values in Lightning datatable - LWC??? 

Any sample code please
Hi folks any one facing  " Extension causes high cpu load " when i updated the vs ocde to new version. 

I have copied the files to c:/user/admin as said in below 
https://github.com//forcedotcom/salesforcedx-vscode/issues?utf8=%E2%9C%93&q=is:issue+state:open+%22Extension+causes+high+cpu+load%22

my main issue is : if i  deploy anything to the server , it keeps on running ,  but in backend code is getting deployed but in front end it will not show that operation completed.
 
how to send list<strings> from parent component  to child component  using aura attribute in lightning
 (note : I dont want aura methods or events ) 
Hello folks , 
I want to show a custom message or toast message if no contacts are found for an account . could you please correct my code . 

please tell how to check the size or length of the  returned contacts .  

below code displays Contacts if present under an account . 

html code:
<template>
<lightning-card title="Apex Method With Parameters">
<lightning-layout>
<lightning-layout-item flexibility="auto" padding="around-small">
<lightning-layout-item flexibility="grow">
<lightning-input label="Enter Account Name" type="search" onchange={searchContact} value={searchKey}> </lightning-input>
</lightning-layout-item>
                <lightning-layout-item class="slds-p-left_xx-small">
<lightning-button label="Search" onclick={doSearch} ></lightning-button> </lightning-layout-item>
<lightning-layout-item class="slds-m-bottom_small">
<template if:true={contacts}>
<template for:each={contacts} for:item="contact">
<p key={contact.Id}> {contact.Name} </p>
</template>
</template>
<template if:false={contacts}>
<p> No Contacts found for this Account </p>
</template>
<template if:true={error}>
{error}>
</template>
</lightning-layout-item>
         </lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>

js code: 

import { LightningElement, track } from 'lwc';
import SearchContactList from '@salesforce/apex/ApexMethodWithParameters.SearchContactList';
export default class ShowContactsIMP extends LightningElement {
/* eslint-disable no-console */
/* eslint-disable no-alert */
@track contacts;
@track error;
searchContact(event){
this.searchKey = event.target.value;
}
doSearch() {
SearchContactList({ accountName: this.searchKey })
.then(
result => {
this.contacts = result;
console.log('contacts => ', JSON.stringify(this.contacts));
alert('contacts => ', JSON.stringify(this.contacts));
this.error = undefined;
}
)
.catch(error => {
this.error = error;
this.contacts = undefined;
});
}
}
 
Hello Folks , 
Thanks in Adv .
Can anyone help me to modify the trigger using this frame work please . i didnt understand this so want to see it in an example how to implement. please copy paste the below URL to see the framework .

framework:  https://github.com/kevinohara80/sfdc-trigger-framework

can you please modify below trigger with above frame work

//to update child records when parent record is updated in Salesforce
trigger ContactUpdate on Account (after update) 
{
    set<id> acctid = new set<id>();
  map<Id, Account> mapAccount = new map<Id, Account>();
    list<Contact> listContact = new list<Contact>();
 //adding all id to set<id>
    for(Account  act :trigger.new)
     {
     acctid.add(act.id);
     mapAccount.put(act.id,act);
      }
     listContact = [select id ,MailingStreet, MailingCity, AccountId FROM  contact where Accountid IN : acctid];
         if( listContact.size()>0  )
             {
         for(Contact con : listContact) 
                {
                    con.MailingStreet = mapAccount.get(con.AccountId).BillingStreet;
                    con.MailingCity = mapAccount.get(con.AccountId).BillingCity;
                }
                update listContact;
            }
 }
 

Hi Friends i need to call these 3 fields on Account object .  i heard that there is an approach where we give the object and field name and it will give desired picklist value result using map . 

my picklist fields are 
1)Account.Rating__c and values = {'High','low','Medium' }
2)Account.Locality__c and values = {'Local','global','international' }
3)Account.generic__c and values = {'A','B','C','d','e' }
can anyone please modify my code . 

Under an account , there should be only one contact with name phone . if i create one more contact with same name then the error shoulp appear . my code :
trigger PreventDuplicateContactMap on Contact (before insert,before update) {
    
    if(trigger.isInsert || trigger.isUpdate)
    {
        Map<Id,List<Contact>> accMap = new Map<Id,List<Contact>>();
        List<Contact> contactList;
        
        for(Contact c: [Select Id,LastName,phone,Email,accountId from Contact where AccountId !=Null ]){
            if(accMap.containsKey(c.accountId)){   
                accMap.get(c.accountId).add(c);
                  system.debug('If loop ===');
            }
            else{
            system.debug('else loop ===');
                contactList = new List<Contact>();
                contactList.add(c);
                accMap.put(c.accountId,contactList);
            }       
        }
        
        for (Contact c : Trigger.new) 
        {
        if(accMap.containsKey(c.accountId))
            {
                for(Contact con : accMap.get(c.accountId))
                {
                if( (c.Phone== con.Phone) || ( c.LastName == con.LastName ) )
                    {
                        c.addError('Duplicate Contact.......... ');
                    }
                }
            }
        }
    }
}
hi folks,  Very Urgent requirement 
on Account object , i have a custom button " contact form" . 
On click of that button opens a Modal window which has  contact form (basically fields from contact object) , i have few fields  Name ,  phone number , className etc . in the bottom i have Save and Save & New buttons,

i want custom functionality of Save
and Save & New buttons 
Requirement 1:
On click of save button on contact form , i need to save all the parameter (Name ,  phone number , className )  custom way , i need to store the contact form data as Record in contact object and in  related list of Account record. .
I have basically 3 dates startdate , enddate and userdate .  

Question : i have a batch which should pick the records  where the Userdate SHOULD NOT fall in between the Range of startdate and enddate .
can anyone please modify my snippet of code.

my code snippet: 
Date userDate =Date.newInstance(2018, 11, 31); 
Date startdate =Date.newInstance(2017, 1, 31); 
Date enddate =Date.newInstance(2017, 12, 31); 
if(userDate < startDate  &&   endDate  > userDate  )
{   
system.debug('True');
}else
 {
 system.debug('false');
 }
Hello Folks, 

On contact object , i have a look up to account object , and let us suppose the lookup field name is AccountID__c , 
When ever i edit a record on contact object  using force:recordEdit  , if i change the lookup field value from A to B , i need to get a popup showing lookup got changed while hitting save button . 

Basically i want to capture/Alert  old value and New value of the lookup field of the record while hitting save.


can anyone please help me with snippet of code. 
 
Hello Folks , 

Need help in implementing using maps ,  Not understanding how to do it . Can anyone please help me with code

If I have Account1 and Contact1 and Contact2 are related to Account1. Then, in account object detail page, i have a text box named Account.ContactName__c =  Contact1, Contact2  etc . i need to diaplay the related contact names on Account .  i did it in list but not able to do it in maps . 

Using  List : 
for(Account  a:acclist )
      {
          String contactName = '';
          for(contact  c :a.contacts )  
           {
           contactName = c.name+',' ;
           }
       a.ContactName__c = contactName;
       
      }
      update acclist; 
How to write a soql query to get All the records in Open Activites which are related list to a account.

User-added image 

 
Hello All , 
How to write trigger ??

Under Account we have open activities, where we create Task and events. 
Scenario: i need to take Duedate value which is comming nearby from the below ones into a customfield Named NearbyDate__c. 

I need to write Trigger logic insuch away that for N number of Activities if i either Add or delete the activities it should sort and  gimme the result. 

for example: 

My output  should be from below example
NearbyDate__c = 9/15/2020 

User-added image

can anyone show some insights on this please. 

@thanks in adv
Hello Folks , 

Is there any soql query to retrieve all my Pagelayout Names under a recordtype in salesforce . 

or whats is the easiest way to find them . 

 
how to a display lookupfield and picklist values in Lightning datatable - LWC??? 

Any sample code please
Hi,

I am trying to update records using data loader but not update,but when i do on single record its been updating.

I am written an trigger on task.
public class UpdateActivityHistoryCallCount {
    
    
    //To update the Count of Activity History in Lead object
    
    public static void countActivityHistoryOnLead(list<Task> newTaskList,list<Task> oldTaskList){
        system.debug('<<<<<test>>>>>');
        set<Id> LeadIds=new set<Id>();
        list<Lead> leadList=new list<Lead>();
        // Map<Id, String> error = new Map<Id, String>();
        
        if(trigger.isInsert || trigger.isUnDelete ){
            for(Task tsk:newTaskList){
                if(tsk.WhoId!=null){
                    if(string.valueOf(tsk.WhoId).startsWith('00Q'))
                        LeadIds.add(tsk.WhoId);
                    
                    
                }
                system.debug('Lead Ids' +LeadIds);
            }
        }
        if(trigger.isDelete || trigger.isUpdate){
            for(Task tk:oldTaskList){
                if(tk.WhoId!=null){
                    if(string.valueOf(tk.WhoId).startsWith('00Q'))
                        LeadIds.add(tk.whoId);
                    
                }
            }
            system.Debug('Test LeadIds' +LeadIds);
        }
        if(LeadIds.size()>0){
            for(Lead l:[select id,(select id,subject,Due_Date__c,CreatedDate
                                   from tasks where (subject='Call' and status='Completed'
                                                     and  Due_Date__c < Today) or (subject='Call' and status='Completed' and Due_Date__c =  null)  ) 
                        from lead where id in :LeadIds ])
                leadList.add(new lead(id=l.Id,Call_count__c=l.tasks.size()));
             update leadList;
            
            system.debug('Test');
        }
       
        
    }
    
    
Hi Everyone,

I am trying to reproduce the scenario as below link. Created a user as Salesforce Platform licence, trigger and when I logged in as Salesforce Platform User licence and created contact and updated not able to get the error.

https://www.sundoginteractive.com/blog/triggers-updating-restricted-records

Can anyone suggest me on this?

Thanks,
Sirisha
Hello,

First time to post so apologies if this is not in the correct area.

I am working on some code executed in anonymous that will insert some records in a charity's org.   The charity has job records, on those jobs exist shifts, and those shifts can have hours, for context.

The problem at the moment is that several jobs exist in the org which have shifts, but the hours were not correctly added, so I created the script below which can create those hour records and successfully copy over all the information that is needed from the shift/job record.  However, when I attempt to run this in the live version on a single record (which has 21 shifts)  I am getting Error:System.LimitException: Too many SOQL queries:101.

Below is my script:
List<GW_Volunteers__Volunteer_Job__c> badJobs = new list<GW_Volunteers__Volunteer_Job__c>();
badJobs=[SELECT Id FROM GW_Volunteers__Volunteer_Job__c WHERE GW_Volunteers__First_Shift__c!=NULL AND GW_Volunteers__Number_of_Completed_Hours__c=0]; //jobs that have shift with no hr
    
List<GW_Volunteers__Volunteer_Shift__c> needsHr = new list <GW_Volunteers__Volunteer_Shift__c>();
needsHr=[SELECT Id, GW_Volunteers__Start_Date_Time__c,GW_Volunteers__Duration__c, GW_Volunteers__Volunteer_Job__r.Volunteer__c FROM GW_Volunteers__Volunteer_Shift__c WHERE GW_Volunteers__Volunteer_Job__c in :badJobs]; //shift records with no hrs
for (GW_Volunteers__Volunteer_Shift__c s :needsHr){
    DateTime dT = s.GW_Volunteers__Start_Date_Time__c;
    Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
    GW_Volunteers__Volunteer_Hours__c hour = new GW_Volunteers__Volunteer_Hours__c(
        GW_Volunteers__Contact__c=s.GW_Volunteers__Volunteer_Job__r.Volunteer__c,
    	GW_Volunteers__Status__c='Completed',
    	GW_Volunteers__Hours_Worked__c=s.GW_Volunteers__Duration__c,
    	GW_Volunteers__Volunteer_Job__c=s.GW_Volunteers__Volunteer_Job__c,
        GW_Volunteers__Volunteer_Shift__c=s.Id,
    	GW_Volunteers__Start_Date__c=myDate,
        GW_Volunteers__End_Date__c=myDate
        
        
    
    );
    insert hour;
}

I believe I need to adjust this so that it is calling fewer queries, but I am not entirely sure what I can do other than put a LIMIT which won't really work for me as I need to run through all of the shifts on a given job record in one go.
When I change the shift query to the following, the script will run fine and insert hours corresponding to the correct shift records:
needsHr=[SELECT Id, GW_Volunteers__Start_Date_Time__c,GW_Volunteers__Duration__c, GW_Volunteers__Volunteer_Job__r.Volunteer__c FROM GW_Volunteers__Volunteer_Shift__c WHERE GW_Volunteers__Volunteer_Job__c ='a0T3Y00000SLivnUAD' LIMIT 10];

I am grateful for any assistance on this.

Thank you.
El
 
  • March 03, 2020
  • Like
  • 0
Hi,
I have an apex trigger to count the total Opportunities related to an Account and Sum of Opportunity Amount related to Account. I am trying to implement "after undelete" in my trigger. But it isn't working. Can someone help to do this?
Below is my Trigger

trigger OpportunityCount on Opportunity (after insert, after delete, after update, after Undelete) {
    Map<Id, List<Opportunity>> acctIdOpptyListMap = new Map<Id, List<Opportunity>>();
    Set<Id> acctIds = new Set<Id>();
    List<Opportunity> opptyList = new List<Opportunity>();
    if(trigger.isUpdate && trigger.isInsert){
        for(Opportunity oppty : trigger.New){
            if(oppty.AccountId != null){
                acctIds.add(oppty.AccountId);
            }
        }    
    }
    if(trigger.isDelete){
        for(Opportunity oppty : trigger.old){
            if(oppty.AccountId != null){
                acctIds.add(oppty.AccountId);
            }
        }    
    }
    if(acctIds.size() > 0){
        opptyList = [SELECT Amount, AccountId 
                     FROM Opportunity 
                     WHERE AccountId IN : acctIds];
        for(Opportunity oppty : opptyList){
            if(!acctIdOpptyListMap.containsKey(oppty.AccountId)){
                acctIdOpptyListMap.put(oppty.AccountId, new List<Opportunity>());
            }
            acctIdOpptyListMap.get(oppty.AccountId).add(oppty); 
        }
       
        List<AggregateResult> lstResult = [SELECT AccountId, COUNT(Id) countId 
                                           FROM Opportunity 
                                           WHERE AccountId IN:acctIds
                                           GROUP BY AccountId];
        
        List<Account> lstAccount = new List<Account>();
        for(AggregateResult result:lstResult){
            Account acct = new Account (Id=(Id)result.get('AccountId'), Total_Opportunities__c = (Integer)result.get('countId'));
            lstAccount.add(acct);
        }
        update lstAccount;  
        
        List<Account> acctList = new List<Account>();
        acctList = [SELECT Total_Amount__c 
                    FROM Account 
                    WHERE Id IN: acctIds];
        for(Account acct : acctList){
            List<Opportunity> tempOpptyList = new List<Opportunity>();
            tempOpptyList = acctIdOpptyListMap.get(acct.Id);
            Double totalOpptyAmount = 0;
            for(Opportunity oppty : tempOpptyList){
                if(oppty.Amount != null){
                    totalOpptyAmount += oppty.Amount;
                }
            }
            acct.Total_Amount__c = totalOpptyAmount;
        }
        update acctList;
    }
}
Hello folks , 
I want to show a custom message or toast message if no contacts are found for an account . could you please correct my code . 

please tell how to check the size or length of the  returned contacts .  

below code displays Contacts if present under an account . 

html code:
<template>
<lightning-card title="Apex Method With Parameters">
<lightning-layout>
<lightning-layout-item flexibility="auto" padding="around-small">
<lightning-layout-item flexibility="grow">
<lightning-input label="Enter Account Name" type="search" onchange={searchContact} value={searchKey}> </lightning-input>
</lightning-layout-item>
                <lightning-layout-item class="slds-p-left_xx-small">
<lightning-button label="Search" onclick={doSearch} ></lightning-button> </lightning-layout-item>
<lightning-layout-item class="slds-m-bottom_small">
<template if:true={contacts}>
<template for:each={contacts} for:item="contact">
<p key={contact.Id}> {contact.Name} </p>
</template>
</template>
<template if:false={contacts}>
<p> No Contacts found for this Account </p>
</template>
<template if:true={error}>
{error}>
</template>
</lightning-layout-item>
         </lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>

js code: 

import { LightningElement, track } from 'lwc';
import SearchContactList from '@salesforce/apex/ApexMethodWithParameters.SearchContactList';
export default class ShowContactsIMP extends LightningElement {
/* eslint-disable no-console */
/* eslint-disable no-alert */
@track contacts;
@track error;
searchContact(event){
this.searchKey = event.target.value;
}
doSearch() {
SearchContactList({ accountName: this.searchKey })
.then(
result => {
this.contacts = result;
console.log('contacts => ', JSON.stringify(this.contacts));
alert('contacts => ', JSON.stringify(this.contacts));
this.error = undefined;
}
)
.catch(error => {
this.error = error;
this.contacts = undefined;
});
}
}
 
hi folks,  Very Urgent requirement 
on Account object , i have a custom button " contact form" . 
On click of that button opens a Modal window which has  contact form (basically fields from contact object) , i have few fields  Name ,  phone number , className etc . in the bottom i have Save and Save & New buttons,

i want custom functionality of Save
and Save & New buttons 
Requirement 1:
On click of save button on contact form , i need to save all the parameter (Name ,  phone number , className )  custom way , i need to store the contact form data as Record in contact object and in  related list of Account record. .
Hello Folks , 

Need help in implementing using maps ,  Not understanding how to do it . Can anyone please help me with code

If I have Account1 and Contact1 and Contact2 are related to Account1. Then, in account object detail page, i have a text box named Account.ContactName__c =  Contact1, Contact2  etc . i need to diaplay the related contact names on Account .  i did it in list but not able to do it in maps . 

Using  List : 
for(Account  a:acclist )
      {
          String contactName = '';
          for(contact  c :a.contacts )  
           {
           contactName = c.name+',' ;
           }
       a.ContactName__c = contactName;
       
      }
      update acclist; 
HI All , 
can any one help me with this requirement ,
1)  where when i click on parent checkbox , need to select all child checkbox
2) when i unselect parent checkbox , need to unselect all childs 
3) let us suppose i click on parent checkbox that selects all child checkbox , when i unselect one checkbox in child , the parent checkbox has to get deselected.




User-added image


 

User-added image
Hi All, 
on click of the checkbox by the user need the total to be displayed like below DYNAMICALLY. if i unselect the checkbox the sum needs to get reduced from the actual. for example: if i select two checkboxes above the sum of cost_price__c = 30 . if user select one more need to add to the total , if user unselect the checkbox it should reduce to the total.

I need to display the values below . Any help is highly appreciated
Total cost_price__c = 
Total market_price__c = 
 
Hi, How to display case records based on picklist slection using visualforce LIghting
I have 4 Picklist fields in case object, i have to display these 4 picklist fields in  visulaforce page and based on thsese picklist fileds selection need to display case records on page .this should be done  in visulaforce lighting.Please help me to complete it.i am new to salesforce :( help
If the return type in aura enabled method is returning and error and not able to solve. Is there any options apart from adding new class to enable aura to select option class?
@AuraEnabled
    public List<SelectOption> getObjDetails() {
    //do something
}
  • December 05, 2016
  • Like
  • 0
Hi Friends,

I need help in completing below trigger.
I have a requirement, Two custom objects Obj A and Obj B which Obj A is Parent and Obj B is child. I am creating a child record based on daysbetween two dates Start Date and End Date in Parent object. This is working fine.
Now, If I edit the end date 
Eg: Start Date = 20/03/2020 and End Date = 22/03/2020. Daysbetween = 3. I will create 3 records in child Obj.
I am editing End Date = 25/03/2020.
Now Daysbetween = 6.
I want to create 3 more records. 
If I delete a date. Eg: End Date = 21/03/2020. Daysbetween = 2. I want to delete 1 record in child obj.
 
trigger insertDailyPractices on Study_Plan__c (after insert) 
{
    System.debug('--- Inside Trigger ---');
    List<Daily_Practice__c> dplist = new List<Daily_Practice__c>();    
    
    for(Study_Plan__c sp : Trigger.New)
    {
        if(String.isNotBlank(sp.Phase_Start_Date__c) && String.isNotBlank(sp.Phase_End_Date__c) {

            Integer daycount = sp.Phase_Start_Date__c.daysBetween(sp.Phase_End_Date__c);
            
            System.debug('--- Inside For Loop ---' + sp.Phase_Start_Date__c);
            System.debug('--- Day Count ---' + daycount);
     
            for(integer i=0; i<=daycount; i++)
            {
                Daily_Practice__c dps = new Daily_Practice__c();
                dps.Due_Date__c = sp.Phase_Start_Date__c.addDays(i) + 1;
                dps.StudyPlan__c = sp.Id;
                dps.Status__c = 'Assigned';
                dplist.add(dps);
            }    
        }
    }
    
    if(dplist.size() > 0)
    {
        insert dplist;
    }    
    system.debug('--- Inserted Daily Practice ---'+ dplist.size());
}

Let me know your suggestions to complete this requirement.

Thanks in advance.
Hello all

i am trying to Design a Trigger where it should throw an error upon duplicate record creation, i know this can be achived with Duplicate management, but i have Custom Lookup field(User) which is not showing in the matching rules, Hence i am trying to write trigger, basically i have 3 Custom fields User(Assignedto__c ) which is 
Lookup(User) and other fields are 
Quater_Year__c which is picklist and Month (
Month__c) which is picklist field, 

Please Help with the trigger
trigger contactDuplicatePreventer on Contact(before insert, before update) 
{
	Set<String> setEmailID = new set<String>();
	Set<Id> setContID = new set<ID>();
    for (Contact Contact : System.Trigger.new) 
	{
        if ((Contact.Email != null) &&  (System.Trigger.isInsert ||  (Contact.Email != System.Trigger.oldMap.get(Contact.Id).Email))) 
		{
			setEmailID.add(Contact.Email);
			setContID.add(Contact.id);
		}
    }

	List<Contact> lstCOntact = [select id ,email from contact where email in :setEmailID and id not in :setContID ];
    Map<String, Contact> contactMap = new Map<String, Contact>();

	for(Contact cont : lstCOntact)
	{
		contactMap.put(cont.email, cont);
	}	

    for (Contact Contact : System.Trigger.new) 
	{
        if ((Contact.Email != null) &&  (System.Trigger.isInsert ||  (Contact.Email != System.Trigger.oldMap.get(Contact.Id).Email))) 
		{
			if(contactMap.containsKey(Contact.Email))
			{
				Contact.Email.addError('A Contact with this email address already exists.');
			}
		}	
	}	
}