• Niknit
  • NEWBIE
  • 50 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 13
    Questions
  • 27
    Replies

Hi,

 

My Requirement is to display two picklist on a VF page, one below the other, the second onee being the dependent one and then upon the selection of second picklist i.e. the dependent picklist, a table should be displayed with related data, and it should change whenever the second option is changed.

 

so when the value from second pickllist is selected , the data of name and mark__c field from the object CIMMAN__c object should be displayed. where the tick__c value is equal to the selected value from the second picklist(selected). I tried but its apparently not working out, actionsupport i tried but i guess i am just not doing it right. Thanks

I have the code till dependent picklist

 

<apex:page sidebar="false"  Controller="TickController" >
    
<apex:form>

    <apex:actionFunction action="{!createDependPick}" name="generateDependPick" reRender="pick2" />
    
    


    Select the Pick1:

    <apex:selectList id="pick1" value="{!Selected1}" size="1" onchange="generateDependPick()">

        <apex:selectOptions value="{!selectoption1}">

        </apex:selectOptions>

    </apex:selectList>

    


    Select the Pick2:

    <apex:selectList id="pick2" value="{!Selected2}" size="1" >

        <apex:selectOptions value="{!selectoption2}">

        </apex:selectOptions>
   

           
    </apex:selectList>        


            </apex:page>


Controller

public class TickController {

 


public List<SelectOption> selectoption1 {get; set;}
public List<SelectOption> selectoption2 {get; set;}
public String Selected1 {get; set;}
public String Selected2 {get; set;}



    public Tickcontroller(){

            

            selectoption1 = new List<SelectOption>();
            selectoption2 = new List<SelectOption>();

            SelectOption option = new SelectOption('--None--', '--None--');

            selectoption1.add(option);
            selectoption2.add(option);
            option = new SelectOption('1', '1');
            selectoption1.add(option);
            option = new SelectOption('2', '2');
            selectoption1.add(option);
                      }

    public void createDependPick(){

           selectoption2.clear();
           selectoption2.add(new SelectOption('--None--', 'None'));

            if(Selected1  == '1'){
                selectoption2.add(new SelectOption('TDK','TDK'));
                selectoption2 .add(new SelectOption('OUTIA','OUTIA'));

                    }
              else if( Selected1 == '2'){
                   selectoption2 .add(new SelectOption('GNR','GNS'));
                   selectoption2 .add(new SelectOption('SOTD','SOTD'));

                    }
}
        
        
          
        
        
        }
  • November 24, 2017
  • Like
  • 0
Okay the requirement is for a visualforce page

The VF page will include two picklist fields from a custom object and then a list of SAYs assigned to it should be displayed.

The first picklist is of 2 values which basically tells which group to selectups - AC1 or second group AC2.

there are some products available for AC1 and Ac2. when first picklist is selected the second picklist of products gets populated accordingly to the group selected in first picklist.

now from the second picklist, when a product is selected then a list is shown of the SAYs assigned to the product selected in the second picklist.

I just want an idea on how to proceed with this.

The custom object is present ALLdatobj, it has the both picklist fields.

I just need to proceed with the VF creation.

Thanks
  • November 16, 2017
  • Like
  • 0

heres the scenario

There is sobject Campaign - > under it is related list for custom object PD.There is two fields under PD - Campaign and Dlr

For pd object record creation there is two fields - Campaign(child) and Dlr field [both are lookup field - campaign to Campaign and Dlr to accounts]

What I want to create is trigger to throw error when user tries to create PD object record with a campaign lookup using the Dlr which is already in use with another campaign that got used for creating another PD before.

But I am not atall able to figure out to put in the relation between all thus finding hard to finish.

 

this is what i came up with, if anyone can, pls show me, thank you

 

 

set<id> CampaignId = new set<id>
for(PD__c i : trigger.old)
    campaignid.add(i.Campaign__c)

List<account> CampaignDlr= [Select id (Select id , Dlr__c from PD__c) from account where id in : CampaigniD]

for(PD__c i : trigger.new){

    for(account p : campaigndealer){

        if(i.dlr__c == p.dlr__c){
        I.adderror('Error');
        }

        }
      }
 

  • November 06, 2017
  • Like
  • 0
VF Page
<apex:page controller="productslistpage" showHeader="false">

  <Apex:form >


  <apex:outputText value="{!usermode}  {!Name}" style="float:right;font-weight:bold;color:black;font-size:16px;text-align:left;" />

        <br/><p style="font-size:19px;font-weight:bold;"> Products available today </p><br/>



            <apex:CommandLink action="{!prod1button}" ><br/>    
  <apex:image url="{!$Resource.Testprod1}" width="100" height="180"/><br/>
            <h3>Logo Shirt (Gray)</h3> 
            </apex:commandlink>
            <p>$20.00</p>

    </apex:form>
</apex:page>

Controller
 
public Class productslistpage{

    public list<inventory__c> prodlist{get; set;} 
    public string PID{get; set;}
    public string name{get; set;}
    public string usermode{get; set;}

public productslistpage(){

    this.name = ApexPages.currentPage().getParameters().get('Name');
    this.usermode = ApexPages.currentPage().getParameters().get('usermode');
    prodlist = [Select ButtonName__c,Name, Price__c, Stocks__c,productid__c from Inventory__c];
}     

      PageReference pg = new PageReference('/apex/testprodpage');
public pagereference prod1button(){


      PID = '10004';    

      pg.getParameters().put('PID', PID);

      return pg; 
     }
}


The Vf page contains commandbutton for productone as well as name and other details of product, button is linked to pagereference prod1button which passes the product id to the other page.

What I need help with is I don't want to write each block of code similar to one eanother in the VF and the controller class.Is there a way I can generalise the code with anything, because i don't know how I can,I thought of Repeat but i don't think it helps with the methods in the class, as each method will be required , If i am not wrong. Please any help is appreciated.

 

Thank you,

Niknit

  • August 09, 2017
  • Like
  • 0
@istest

private class StudentupdatehandlerTestClass {
    
      
      @testSetup
           static void testData(){
        
                list<student_details__c> studlist = new list<student_details__c>();
                list<department__c> deptlist = new list<department__c>();
                for(integer i=0;i<2;i++){
                    Department__c  newdept = new department__c();   
                    newdept.name='dept'+i;
                    newdept.no_of_students__c=0;  
                    deptlist.add(newdept);
                }
            insert deptlist;
                   
                for(integer i=0;i<2;i++){
                   student_details__c newstudent = new Student_details__c();
                   newstudent.Name='Student'+i;   
                   newstudent.department__c = deptlist[i].id;    
                   studlist.add(newstudent);
                  }
            insert studlist;
           
           
           }
    
    
      @istest
           static void validateinsert() {
      
      
                  list<department__c> deptlist = [SELECT Id, no_of_students__c FROM Department__c];
 
                  list<student_details__c> studlist = [SELECT Id, name,department__c FROM student_details__c]; 

                  deptlist = [SELECT Id,name, no_of_students__c FROM Department__c];  
  
                    for(integer i=0;i<2;i++){
                       System.assertEquals('dept'+i , deptlist[i].name);
                       System.assertEquals(1 , deptlist[i].no_of_students__c);
                               }
                  }
     
     
       @istest
           static void validateupdate() {
                  list<department__c> deptlist = [SELECT Id, name,no_of_students__c FROM Department__c];
                  list<student_details__c> studlist = [SELECT Id,name, department__c FROM student_details__c];    
 
                       System.assertEquals(1 , deptlist[0].no_of_students__c);
                       System.assertEquals(1 , deptlist[1].no_of_students__c);
                    
                       studlist[1].department__c = deptlist[0].id;
                      
                       update studlist; 
 
                       deptlist = [SELECT Id, name,no_of_students__c FROM Department__c ];
                       
                       System.assertEquals('dept0' , deptlist[0].name);
                       System.assertEquals(2 , deptlist[0].no_of_students__c);
                       System.assertEquals('dept1' , deptlist[1].name);
                       System.assertEquals(0 , deptlist[1].no_of_students__c);        
                  }
            
            }


iin the last 3 lines,          

System.assertEquals(2 , deptlist[0].no_of_students__c);
  its failing as actual value is showing 1, it should be 2.

I don't understand why.

 

@testSetup
    static void testData()
    {
           Department__c  newdept = new department__c();   
           newdept.name='CSE';
           insert newdept;
    }

    @isTest
    static void validateupdatechange() 
    {

       Department__c newDept = [SELECT Id, no_of_students__c FROM 
       Department__c LIMIT 1];

       student_details__c newstudent = new Student_details__c();

       newstudent.Name='From TestClass';   
       newstudent.department__c = newDept.Id;     

       System.debug('before@@trigger: ' + newDept.no_of_students__c);
       test.startTest();

       insert newstudent;

       test.stopTest();

       newstudent = [SELECT department__c FROM student_details__c WHERE Id 
              =:newstudent.Id];


       newDept = [SELECT no_of_students__c FROM Department__c LIMIT 1];
       System.debug('after@@trigger: ' + newDept.no_of_students__c);


       System.assertEquals(1 , newDept.no_of_students__c);
    }

This code is working, but I don't understand why are we using The LIMIT and WHERE Id =:newstudent.Id. if there is only one record I am inserting then why LIMIT and use where clause with ID.The test fails if I don't use this.
About trigger :There are two objects student_details__c and department__c. department__c - contains name and no_of_students__c; student_details__c contains name, department(lookup to department object).
when a student is inserted in a department, that respective department needs to increment the no_of_students__field,similarly when department is changed of a student from one dept to other then no_of_students__c needs to be incremented in the new department and decremented from the old department field. no_of_student__c is the total count of students in respect to the department the belong to in each department object.

Testclass
@istest

private class StudentupdatehandlerTestClass {

    static testMethod void validateupdatechange() {

       Department__c  newdept = new department__c();   
       newdept.name='CSE';
       insert newdept;

       student_details__c newstudent = new Student_details__c();

       newstudent.Name='From TestClass';   
       newstudent.department__c = newdept.id;    



       System.debug('before@@trigger: ' + newdept.no_of_students__c);

       insert newstudent;

       newstudent = [SELECT department__c FROM student_details__c WHERE Id =:newstudent.Id];
       System.debug('after@@trigger: ' + newdept.no_of_students__c);


       System.assertEquals(1 , newdept.no_of_students__c);
    }
}

error is in the insert newstudent line

Trigger
trigger Test on Student_Details__c (after insert, after update,after delete) {

        studentupdatehandler studobj = new studentupdatehandler();

        if(trigger.isinsert)
        {
        studobj.afterinsert(trigger.new);
        }

        if(trigger.isdelete)
        {
        studobj.afterdelete(trigger.old);
        }

       if(trigger.isupdate)
       {
       studobj.afterupdate(trigger.new,trigger.old);
       }    
}

Triggerhandler
 
public class studentupdatehandler{

     set<id> deptid = new set<id>();  

public void afterinsert(student_details__c[] newstudentslist) {

        list<department__c> newdeptlist = [select id,name,no_of_students__c,(select id from student_details__r) from department__c where id in:forids(newstudentslist)];

        toinsert(newdeptlist);
 } 

     public void afterdelete(student_details__c[] oldstudentslist) {
        list<department__c> olddeptlist = [select id,name,no_of_students__c,(select id from student_details__r) from department__c where id in:forids(oldstudentslist)];

        toupdate(olddeptlist);
 }

    public void afterupdate(student_details__c[] newstudentslist,student_details__c[] oldstudentslist) {

        list<department__c> newdeptlist = [select id,name,no_of_students__c,(select id from student_details__r) from department__c where id in:forids(newstudentslist)];
        toinsert(newdeptlist);


        list<department__c> odeptlist= [select id,name,no_of_students__c,(select id from student_details__r) from department__c where id in:forids(oldstudentslist)];
        toupdate(odeptlist);  

}

Public set<id> forids(student_details__c[] deptlist ){
        set<id> ids = new set<id>();

         for(student_Details__c record: deptlist){

             ids.add(record.Department__c);

            }
return ids;}

Public void toinsert(department__c[] deptlist ){

        for(department__c dept : deptlist){

                   dept.no_of_students__c = dept.no_of_students__c +1;
        }                 
   update deptlist;      
        } 

Public void toupdate(department__c[] odeptlist ){


        for(department__c dept : odeptlist){
                 dept.no_of_students__c = dept.no_of_students__c -1;
             } 
         update odeptlist; 
}


}


I need to create test case for insert, update and delete.

The problem is I am not bale to input data for the student object for the lookup field in it,Department is another object which is lookup in the student object with field department__c,

I feel i am not populating that field in correct manner in test class.

I am just making a baby version of ecommerce website like amazon just for my practice,I have made the homepage and products list page - with 2 products, now in order to proceed further i am confused, how many objects should i be making, my objective is simple,user will be able to select product and add to cart and in end simple checkout. what all objects should i be having? 

and what for i should be having to manage products?,products in carts, inventory?, users?

none has to explain me in details , i just need to have basic idea of what i have to do ,Thanks

After trying to learn and doing trail heads I feel like doing something to next level for me, and I plan to make website portal(hope I am using the right term "portal") like Amazon.com, just a simple versionof it for my learning, where there is a start page for user to browse products and log in.
I just need a start. I got confused where to start, creating objects or visualforce pages. I'll be needing objects for users, products etc.
I just need tips what should I start with.

 

What I am trying to do is make a page where if i click on button then all accounts with type "prospect" to be shown. below is all my code :

 

Error: Formula expression is required for attribute value in in q4controller at line 7 column 58
VF code

<apex:pageblock title = "List of accounts">

                <apex:pageblocktable value="{! acts }" var="a">

                    <apex:column value="{ !a.Name } " /> 
                    <apex:column value="{ !a.Type }" />    
                    <apex:column value="{ !a.Industry }" />

                </apex:pageblocktable>


       </apex:pageblock>


</apex:page>



******Controller class******

Public class q4{

List<account> acts;

public list<account> getacts(){
acts = [Select name,type,industry from account where type = 'Prospect'];
return acts;
}



}
 




what is this error, i don't understand. i have tried googling but wasnt able to pin point what the issue is.also i am new to this so please scuse and silly mistake.
Thanks

trigger ClosedOpportunityTrigge on Opportunity (after update, after insert) {

		list<task> tasklist = new list<task>();
    	list<opportunity> opplist = new list<opportunity>();
    
    	opplist = [select id,stagename from opportunity where stagename = 'Closed Won' and id in :trigger.newmap.keyset()];

    		for (opportunity opp : opplist){
            	if(opp.stagename == 'Closed Won'){
						task addtask = new task();
            			addtask.subject = 'Follow Up Test Task';
						addtask.WhatId = opp.Id;
						tasklist.add(addtask);
				}
		}
		update tasklist;
}


Hi,

The challenge is 

To complete this challenge, you need to add a trigger for Opportunity. The trigger will add a task to any opportunity inserted or updated with the stage of 'Closed Won'. The task's subject must be 'Follow Up Test Task'.

  • The Apex trigger must be called 'ClosedOpportunityTrigger'
  • With 'ClosedOpportunityTrigger' active, if an opportunity is inserted or updated with a stage of 'Closed Won', it will have a task created with the subject 'Follow Up Test Task'.
  • To associate the task with the opportunity, fill the 'WhatId' field with the opportunity ID.
  • This challenge specifically tests 200 records in one operation.

 

I feel the logic is right, but it is showing me error as : 

Challenge Not yet complete... here's what's wrong:
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Account name is required: []

 

Is there something i am doing wrong, please point out if i made any mistakes.

also. i have just started with salesforce and apex 2 weeks ago, if i am missing anythin please give explaination, it would help me alot in understanding.

 

Thanks,

Nitin 

trigger Accnumberupdate3 on contact (before insert ,before update) {
          
               
            list<contact> con = new list<contact>();
             Set <id> ids = new set<id>();
       
			  for( contact c : trigger.new){
			  if(c.Finalize_Number__c == true){
               ids.add(c.Id);}
       } 
           con = [select acc_number__c,finalize_number__c,account.acc_number__c from contact where id in :ids];
        for(contact c : con){
                system.debug('for condition');
            if(c.Finalize_Number__c == true){
               
                c.Acc_Number__c = c.account.acc_number__c;
        
                    }
        
             }
    
    
    

}


OR

 

trigger Accnumberupdate3 on contact (before insert ,before update) {
          
               
            
       
			  for( contact c : trigger.new){
			 
                system.debug('for condition');
            if(c.Finalize_Number__c == true){
               
                c.Acc_Number__c = c.account.acc_number__c;
        
                    }
        
             }
    
    
    

}
 







Hi, I am new to this.
what i am trying to do is make a trigger in which acc_number__c is updated in Contact from the account field acc_number__c if the checkbox field final_number__c is selected in the contact object.
the above both before trigger seems fine logically to me?am i missing something?should i be using after trigger?I tried with after trigger and  it works,what is the problem with this before triggers?

Thanks


 
Hi, I am new to this.
what i am trying to do is make a trigger in which acc_number__c is updated in Contact from the account field acc_number__c if the checkbox field final_number__c is selected in the contact object.
I was confused as to use after or before for this.
i tried with after as follows :
trigger Accnumberupdate2 on contact (after insert ) {
            
            list<contact> conlist = new list<contact>();
            list<contact> con = new list<contact>();
           Set <id> ids = new set<id>();
       for(contact c : trigger.new){
              if(c.Finalize_Number__c == true){
                system.debug('If condition');
                ids.add(c.Id);
                              }
       }
            con = [select acc_number__c,finalize_number__c,account.acc_number__c from contact where id
                    in :ids];
           
                
        for(contact c : con){
               
                c.Acc_Number__c = c.account.acc_number__c;
                conlist.add(c);

        
             }
    
    
 update conlist;   

}

the above code worked.
but when i use the below code with before, it doesnt work, the field doesnt get updated.
trigger Accnumberupdate3 on contact (before insert ,before update) {
          
    acc_number__c,finalize_number__c,account.acc_number__c from contact where id in :ids];
                
        for(contact c : trigger.new){
                system.debug('for condition'+ c.Acc_Number__c);
            if(c.Finalize_Number__c == true){
             c.Acc_Number__c = c.account.acc_number__c;
         
                    }
        
               }
    
    
    

}


I read that i should be using after if i need to update a related object but before if its the same object, since i am trying to uopdate the same object i think before should be done but i may be wrong.
If anyone can please tell what is the problem with before trigger and why is it not working ,that would be great because i feel logically it is fine.I think i need to understand when to use before and after and if someone could make me understand with this example ill be able to understand it..
Thanks

Hi,

 

My Requirement is to display two picklist on a VF page, one below the other, the second onee being the dependent one and then upon the selection of second picklist i.e. the dependent picklist, a table should be displayed with related data, and it should change whenever the second option is changed.

 

so when the value from second pickllist is selected , the data of name and mark__c field from the object CIMMAN__c object should be displayed. where the tick__c value is equal to the selected value from the second picklist(selected). I tried but its apparently not working out, actionsupport i tried but i guess i am just not doing it right. Thanks

I have the code till dependent picklist

 

<apex:page sidebar="false"  Controller="TickController" >
    
<apex:form>

    <apex:actionFunction action="{!createDependPick}" name="generateDependPick" reRender="pick2" />
    
    


    Select the Pick1:

    <apex:selectList id="pick1" value="{!Selected1}" size="1" onchange="generateDependPick()">

        <apex:selectOptions value="{!selectoption1}">

        </apex:selectOptions>

    </apex:selectList>

    


    Select the Pick2:

    <apex:selectList id="pick2" value="{!Selected2}" size="1" >

        <apex:selectOptions value="{!selectoption2}">

        </apex:selectOptions>
   

           
    </apex:selectList>        


            </apex:page>


Controller

public class TickController {

 


public List<SelectOption> selectoption1 {get; set;}
public List<SelectOption> selectoption2 {get; set;}
public String Selected1 {get; set;}
public String Selected2 {get; set;}



    public Tickcontroller(){

            

            selectoption1 = new List<SelectOption>();
            selectoption2 = new List<SelectOption>();

            SelectOption option = new SelectOption('--None--', '--None--');

            selectoption1.add(option);
            selectoption2.add(option);
            option = new SelectOption('1', '1');
            selectoption1.add(option);
            option = new SelectOption('2', '2');
            selectoption1.add(option);
                      }

    public void createDependPick(){

           selectoption2.clear();
           selectoption2.add(new SelectOption('--None--', 'None'));

            if(Selected1  == '1'){
                selectoption2.add(new SelectOption('TDK','TDK'));
                selectoption2 .add(new SelectOption('OUTIA','OUTIA'));

                    }
              else if( Selected1 == '2'){
                   selectoption2 .add(new SelectOption('GNR','GNS'));
                   selectoption2 .add(new SelectOption('SOTD','SOTD'));

                    }
}
        
        
          
        
        
        }
  • November 24, 2017
  • Like
  • 0

heres the scenario

There is sobject Campaign - > under it is related list for custom object PD.There is two fields under PD - Campaign and Dlr

For pd object record creation there is two fields - Campaign(child) and Dlr field [both are lookup field - campaign to Campaign and Dlr to accounts]

What I want to create is trigger to throw error when user tries to create PD object record with a campaign lookup using the Dlr which is already in use with another campaign that got used for creating another PD before.

But I am not atall able to figure out to put in the relation between all thus finding hard to finish.

 

this is what i came up with, if anyone can, pls show me, thank you

 

 

set<id> CampaignId = new set<id>
for(PD__c i : trigger.old)
    campaignid.add(i.Campaign__c)

List<account> CampaignDlr= [Select id (Select id , Dlr__c from PD__c) from account where id in : CampaigniD]

for(PD__c i : trigger.new){

    for(account p : campaigndealer){

        if(i.dlr__c == p.dlr__c){
        I.adderror('Error');
        }

        }
      }
 

  • November 06, 2017
  • Like
  • 0
VF Page
<apex:page controller="productslistpage" showHeader="false">

  <Apex:form >


  <apex:outputText value="{!usermode}  {!Name}" style="float:right;font-weight:bold;color:black;font-size:16px;text-align:left;" />

        <br/><p style="font-size:19px;font-weight:bold;"> Products available today </p><br/>



            <apex:CommandLink action="{!prod1button}" ><br/>    
  <apex:image url="{!$Resource.Testprod1}" width="100" height="180"/><br/>
            <h3>Logo Shirt (Gray)</h3> 
            </apex:commandlink>
            <p>$20.00</p>

    </apex:form>
</apex:page>

Controller
 
public Class productslistpage{

    public list<inventory__c> prodlist{get; set;} 
    public string PID{get; set;}
    public string name{get; set;}
    public string usermode{get; set;}

public productslistpage(){

    this.name = ApexPages.currentPage().getParameters().get('Name');
    this.usermode = ApexPages.currentPage().getParameters().get('usermode');
    prodlist = [Select ButtonName__c,Name, Price__c, Stocks__c,productid__c from Inventory__c];
}     

      PageReference pg = new PageReference('/apex/testprodpage');
public pagereference prod1button(){


      PID = '10004';    

      pg.getParameters().put('PID', PID);

      return pg; 
     }
}


The Vf page contains commandbutton for productone as well as name and other details of product, button is linked to pagereference prod1button which passes the product id to the other page.

What I need help with is I don't want to write each block of code similar to one eanother in the VF and the controller class.Is there a way I can generalise the code with anything, because i don't know how I can,I thought of Repeat but i don't think it helps with the methods in the class, as each method will be required , If i am not wrong. Please any help is appreciated.

 

Thank you,

Niknit

  • August 09, 2017
  • Like
  • 0
@istest

private class StudentupdatehandlerTestClass {
    
      
      @testSetup
           static void testData(){
        
                list<student_details__c> studlist = new list<student_details__c>();
                list<department__c> deptlist = new list<department__c>();
                for(integer i=0;i<2;i++){
                    Department__c  newdept = new department__c();   
                    newdept.name='dept'+i;
                    newdept.no_of_students__c=0;  
                    deptlist.add(newdept);
                }
            insert deptlist;
                   
                for(integer i=0;i<2;i++){
                   student_details__c newstudent = new Student_details__c();
                   newstudent.Name='Student'+i;   
                   newstudent.department__c = deptlist[i].id;    
                   studlist.add(newstudent);
                  }
            insert studlist;
           
           
           }
    
    
      @istest
           static void validateinsert() {
      
      
                  list<department__c> deptlist = [SELECT Id, no_of_students__c FROM Department__c];
 
                  list<student_details__c> studlist = [SELECT Id, name,department__c FROM student_details__c]; 

                  deptlist = [SELECT Id,name, no_of_students__c FROM Department__c];  
  
                    for(integer i=0;i<2;i++){
                       System.assertEquals('dept'+i , deptlist[i].name);
                       System.assertEquals(1 , deptlist[i].no_of_students__c);
                               }
                  }
     
     
       @istest
           static void validateupdate() {
                  list<department__c> deptlist = [SELECT Id, name,no_of_students__c FROM Department__c];
                  list<student_details__c> studlist = [SELECT Id,name, department__c FROM student_details__c];    
 
                       System.assertEquals(1 , deptlist[0].no_of_students__c);
                       System.assertEquals(1 , deptlist[1].no_of_students__c);
                    
                       studlist[1].department__c = deptlist[0].id;
                      
                       update studlist; 
 
                       deptlist = [SELECT Id, name,no_of_students__c FROM Department__c ];
                       
                       System.assertEquals('dept0' , deptlist[0].name);
                       System.assertEquals(2 , deptlist[0].no_of_students__c);
                       System.assertEquals('dept1' , deptlist[1].name);
                       System.assertEquals(0 , deptlist[1].no_of_students__c);        
                  }
            
            }


iin the last 3 lines,          

System.assertEquals(2 , deptlist[0].no_of_students__c);
  its failing as actual value is showing 1, it should be 2.

I don't understand why.

 

About trigger :There are two objects student_details__c and department__c. department__c - contains name and no_of_students__c; student_details__c contains name, department(lookup to department object).
when a student is inserted in a department, that respective department needs to increment the no_of_students__field,similarly when department is changed of a student from one dept to other then no_of_students__c needs to be incremented in the new department and decremented from the old department field. no_of_student__c is the total count of students in respect to the department the belong to in each department object.

Testclass
@istest

private class StudentupdatehandlerTestClass {

    static testMethod void validateupdatechange() {

       Department__c  newdept = new department__c();   
       newdept.name='CSE';
       insert newdept;

       student_details__c newstudent = new Student_details__c();

       newstudent.Name='From TestClass';   
       newstudent.department__c = newdept.id;    



       System.debug('before@@trigger: ' + newdept.no_of_students__c);

       insert newstudent;

       newstudent = [SELECT department__c FROM student_details__c WHERE Id =:newstudent.Id];
       System.debug('after@@trigger: ' + newdept.no_of_students__c);


       System.assertEquals(1 , newdept.no_of_students__c);
    }
}

error is in the insert newstudent line

Trigger
trigger Test on Student_Details__c (after insert, after update,after delete) {

        studentupdatehandler studobj = new studentupdatehandler();

        if(trigger.isinsert)
        {
        studobj.afterinsert(trigger.new);
        }

        if(trigger.isdelete)
        {
        studobj.afterdelete(trigger.old);
        }

       if(trigger.isupdate)
       {
       studobj.afterupdate(trigger.new,trigger.old);
       }    
}

Triggerhandler
 
public class studentupdatehandler{

     set<id> deptid = new set<id>();  

public void afterinsert(student_details__c[] newstudentslist) {

        list<department__c> newdeptlist = [select id,name,no_of_students__c,(select id from student_details__r) from department__c where id in:forids(newstudentslist)];

        toinsert(newdeptlist);
 } 

     public void afterdelete(student_details__c[] oldstudentslist) {
        list<department__c> olddeptlist = [select id,name,no_of_students__c,(select id from student_details__r) from department__c where id in:forids(oldstudentslist)];

        toupdate(olddeptlist);
 }

    public void afterupdate(student_details__c[] newstudentslist,student_details__c[] oldstudentslist) {

        list<department__c> newdeptlist = [select id,name,no_of_students__c,(select id from student_details__r) from department__c where id in:forids(newstudentslist)];
        toinsert(newdeptlist);


        list<department__c> odeptlist= [select id,name,no_of_students__c,(select id from student_details__r) from department__c where id in:forids(oldstudentslist)];
        toupdate(odeptlist);  

}

Public set<id> forids(student_details__c[] deptlist ){
        set<id> ids = new set<id>();

         for(student_Details__c record: deptlist){

             ids.add(record.Department__c);

            }
return ids;}

Public void toinsert(department__c[] deptlist ){

        for(department__c dept : deptlist){

                   dept.no_of_students__c = dept.no_of_students__c +1;
        }                 
   update deptlist;      
        } 

Public void toupdate(department__c[] odeptlist ){


        for(department__c dept : odeptlist){
                 dept.no_of_students__c = dept.no_of_students__c -1;
             } 
         update odeptlist; 
}


}


I need to create test case for insert, update and delete.

The problem is I am not bale to input data for the student object for the lookup field in it,Department is another object which is lookup in the student object with field department__c,

I feel i am not populating that field in correct manner in test class.