• Vatsal Kothari
  • SMARTIE
  • 1323 Points
  • Member since 2014

  • Chatter
    Feed
  • 45
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 247
    Replies
Hi everyone,
   There is a custom field of type 'checkbox' called "Primary" in Contact object. If this Primary is checked, then the value of the contact's Email field has to be updated in the custom email field named "PrimaryContactEmail"  in the Account Standard object. How can this be done in Trigger. Please do suggest a solution
User-added image

I am trying to build a report in apex and send an html email.
The report is basicly counting records number. But it has cross queries.
Can you look my code and comments and give me some advice?

Thank you!
  • September 20, 2014
  • Like
  • 0
I want to save current record and want id of that saved record to pass through to page reference . My controller is:
public HomeEvaluationController (ApexPages.StandardController sc)
      {
        myCustomObject = (HomeEvaluation__c) sc.getRecord();
        controller=sc;
     
      }
public PageReference New_form_save()
        {
         controller.save();

           pageid=myCustomObject.Id;
      
         Pagereference ref = new Pagereference('/apex/Ventilation_Ducting?id='+pageid);
         ref.setRedirect(true);
         return ref;
         }

I am getting null value in page id , please help me out
HI Folks,

I have a scenario i.e, Whoever is created the record but that record users manager & system admin only edit the record based on Grade field. For this i implemented a validation, but its not working properly. So please suggest me.

AND(
OR(ISCHANGED( Grade_1__c ), ISCHANGED( Grade_2__c ), ISCHANGED( Grade_3__c )),
OR( $User.Id=$User.ManagerId )
)

Highly appreciated!!

Hi,
 
I'm building a trigger for the Case object... whereby every time a Case is created I need the Entitlement Lookup field to automatically populate to 'Default Entitlement'. I've written this code below but comes up with an error message:

1. trigger CheckFieldValues on Case (before insert) {
2.    for (Case c : Trigger.new) {
3.        if (c.Status == 'New')
4.            c.Entitlement = 'Default Entitlement';          
5.        }
6.    }

ERROR MESSAGE: Error: Compile Error: Illegal assignment from String to SOBJECT:Entitlement at line 4 column 13

Not an expert on Triggers so any help would be good!

Thanks,
J
Hi folks,
      how to fix the following error:

Expecting equal sign found


List<Topic> to=[select id,name from topic ];

for(Integer i;i<to.size();i++)
    System.debug('topic:'+to[i]);

Thanks in advance
Karthick
Hi
I need to create a list in that i have add 6 values, finally that list should be inserted in db,

My code is as below, 

List < Forecast_Revenue_Report__c > frList = new List < Forecast_Revenue_Report__c > ();

  Forecast_Revenue_Report__c frr = new Forecast_Revenue_Report__c();
  frr.opp_id__c = opp.Id;
           if(frr.Forecast_Amount__c != 0){
                 frr.Forecast_Amount__c = this.amount1; 
                 frList.add(frr);
                 frr= null;
                 
                 frr.Forecast_Amount__c = this.amount2;
                 frList.add(frr);
                 frr= null;

                 frr.Forecast_Amount__c = this.amount3;
                 frList.add(frr);
                 frr= null;

                 frr.Forecast_Amount__c = this.amount4;
                 frList.add(frr);
                frr= null;

                 frr.Forecast_Amount__c = this.amount5;
                 frList.add(frr);
                 frr= null;

                 frr.Forecast_Amount__c = this.amount6;
                 frList.add(frr);
                frr= null;
           }
        insert frList;

In this case i can insert  only frr.Forecast_Amount__c = this.amount6;value(list contain final value), but i need to get all the 6 types of amonut in Forecast_Amount__c filed/ List(frList) can any one help for this!
Hi All,

I have created a validation rule to ensure the users update notes(custom text area field) every time they change the opportunity stage.

And( ISCHANGED( StageName ) , Not(ISCHANGED( Notes2__c ) )) this is the formula.This works fine. But my Salesforce users want to update the notes with minimum 20 characters which I tried using another validation rule  with the formual AND(ISCHANGED( StageName ), if(len( Notes2__c )<(len(Priorvalue(Notes2__c))+20),true,false)) but it is not working as expected.

system is going into loop and asking the user to update the notes even though they entered more than 20 characters.

Please advise any other way of achieving this.
thanks in advance
  • September 16, 2014
  • Like
  • 0
@isTest

private class MyTestMethod {

   // Methods for testing


static testMethod void verifyAccountDescriptionsWhereOverwritten(){

    // Perform our data preparation.

    List<Account> accounts = new List<Account>{};

        

    for(Integer i = 0; i < 500; i++){

        Account a = new Account(Name = 'Test Account ' + i);

        accounts.add(a);

    }



    // Start the test, this changes governor limit context to

    // that of trigger rather than test.

    test.startTest();

        

    // Insert the Account records that cause the trigger to execute.

    insert accounts;

        

    // Stop the test, this changes limit context back to test from trigger.

    test.stopTest();

        

    // Query the database for the newly inserted records.

    List<Account> insertedAccounts = [SELECT Name, Description

                                      FROM Account

                                      WHERE Id IN :accounts];

        

    // Assert that the Description fields contains the proper value now.

    for(Account a : insertedAccounts){

      System.assertEquals(

        'This Account is probably left over from testing. It should probably be deleted.',

        a.Description);

    }

}
}




now since we are inserting 300 records
 before start test we can add max. 100 records(as it refreshes the limit) . //  insert accounts;
when start test runs we can add 100 new records 

but still 100 records are left .
wen i save this test class its not showing error.

m  not able to understand this point thru docs also
Hi Vatsal,
                  I completed this please help me below code only covered 68 % below i mensioned not covered code

public with sharing class MyCls {

      public ApexPages.StandardSetController con{get; set;}

  
        public List<Myobject__c> objectList{ get{
                                                   if(con != null)
                                                        return ( List<Myobject__c)con.getRecords();
                                                    else
                                                        return null ;
                                                }
                                                set;}
   

    public MyCls() {
  
    Database.QueryLocator qLoc;
   
      qLoc = Database.getQueryLocator([SELECT contact__c,Number__C,DropboxPDFSave__c,date_time__c FROM Myobject__c ORDER BY  date_time__c DESC ]);
  
        con = new ApexPages.StandardSetController(qLoc);
 
    }
     

public Boolean hasNext
    {
        get
        {
            return con.getHasNext();
        }
        set;
    }

    public Boolean hasPrevious
    {
        get
        {
            return con.getHasPrevious();
        }
        set;
    }

    public Integer pageNumber
    {
        get
        {
            return con.getPageNumber();
        }
        set;
    }

    public void previous()
    {
        con.previous();
    }

    public void next()
    {
        con.next();
    }
}

please help me.........

Not covered code:

public ApexPages.StandardSetController con{get; set;}

 
        public List<Myobject__c> objectList{ get{
                                                   if(con != null)
                                                        return ( List<My_object__c>)con.getRecords();
                                                    else
                                                        return null ;
                                                }
                                                set;}


return con.getHasNext();
return con.getHasPrevious();
return con.getPageNumber();

please help me.........
Hi 


   Opportunity is parent object and Approvel by source is a child object. Under one parent object  multiple  child objects are there. Child object having  "source of child" picklist field values are(CCI,Risk,Revenu,SD).  Parent object also having "source" it is  text field.

 One parent is having multiple childs all the "source of child" values should  update to parent "source"  field seprated by comma. Dupplictes should not be repeat and even we update child  "source of child" that should update in related parent "source" text filed and even if we deleted child record  parent filed should based on that.


  Please help me on the above trigger.


  
Hi all, i have a custom object that is a related list of opportunity Object. Inside my custom object i have a custom buton that open a visualforce page with renderas=PDF.
<apex:page standardController="MiCustomObject__c">
How can i access Opportunity field from this page?
Can i access parent object from child?
Regards
  • September 12, 2014
  • Like
  • 0
I need a scheduled apex job for field update. I have the following code but it doesn't work. Any ideas about what could be the problem?


global class ReportStatusNotification implements Schedulable {

   public void execute(SchedulableContext ctx)  {
    List<Project__c> projs = new List<Project__c>();

    for(Project__c p : [SELECT Last_Status_Report__c, Report_Status_Indicator__c FROM Project__c]){
      if (p.Last_Status_Report__c.month() == Date.Today().month()) {
        p.Report_Status_Indicator__c = 'Green';
      } else {
        p.Report_Status_Indicator__c = 'Red';
      }
      projs.add(p);
    }

    update projs;
}

ReportStatusNotification m = new ReportStatusNotification();
    String sch = '0 0 0 5-31 * ?';
    String jobID = system.schedule('ReportStatusNotification', sch, m);

}
Hi am new to salesforce please write the test class for the following controller.....

public class profileshortlists {

Id id = ApexPages.currentPage().getParameters().get('id');
public List<Profiles_Shortlisting__c> profilelists{get; set;}



public profileshortlists(ApexPages.StandardController controller) {
        profilelists = new List<Profiles_Shortlisting__c>([select name,Candidate__c,Position__c,Candidate_Status__c,resume__c from Profiles_Shortlisting__c where id =: id]);
       
        profilelists.add(new Profiles_Shortlisting__c(name='temp'));
    
    
        }
     public PageReference save() {
  insert profilelists;
  System.PageReference pageReference = new System.PageReference('/a02/o');
 
   return  PageReference;
   //return new PageReference('/'+id);
  }

}
  • September 12, 2014
  • Like
  • 0
I have a trigger all I want to do is make field a equal to field b when the document is saved.  The first feild (name) which is the standard feild is a required field.  When I try to save this it says needs = in line 2 column 30.  I dont know what I am doing wrong. Thank you for your help!

Trigger updateFields on  McLabs2__Property__c (before update) {
     for (McLabs2__Property__c : trigger.new){
     Name = McLabs2__Property_Address__c;
    }
}
Hi all,

I was wondering if its possible for multiple if statements to fire independantly inside one trigger. I wish to see if a checkbok is either true or false, the date and time field gets populated with the current time and date. This works if im doing one if statement, the trouble begins when i create a similar if statement below. The trigger will populate both the date and time fields instead of just one. I am trying to avoid creating multiple triggers and instead having one. The code  is as follows:
trigger checkedTimeTriggers on Match_Day_Check_List__c (before insert, before update) {

for(match_day_check_list__c t: trigger.new){

if(t.Handshake_Event_Setup__c == True || t.Handshake_Event_Setup__c == False)
    {
    t.Handshake_Event_Setup_Checked_At__c = DateTime.Now();
    }
  
Else{
 if(t.Access_Manager_Checks__c == True || t.Access_Manager_Checks__c == False)
    {
    t.Access_Manager_Checks_Checked_At__c = DateTime.Now();
    }
  }
 }
}

I have tried doing this without the else however the same problem occurs. Thank you.
I have Market , Business  custom objects. Market is Master  object and Business is child object. So Market has any no of Business records in its related list.

Now i want to update a Market  object field , if  Market has  No Business Records. It is Text field. Can any one correct the below field ? I am getting error on sowl statements.

trigger MarketChange on Market__c (before insert,before update) {

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

for(Market__c py : Trigger.new){
Pset.add(py.id);
}
List<Market__c> Ltf = [select id,(select id,Market__c  from Business__r ) from Market__c];  // Error Here

if(Ltf.size() > 0){
for(Market__c px : Trigger.new){
px.ResultField__c = 'No Business data';
}
}
}

Error : Compile Error: Didn't understand relationship 'Business__c' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. at line 8 column 17
  • September 09, 2014
  • Like
  • 0
trigger Winning on Opportunity (before update) {
  for (Opportunity opp : Trigger.new) {
    // Access the "old" record by its ID in Trigger.oldMap
    Opportunity oldOpp = Trigger.oldMap.get(opp.Id);

    // Trigger.new records are conveniently the "new" versions!
    Boolean oldOppIsWon = oldOpp.StageName.equals('Closed Won');
    Boolean newOppIsWon = opp.StageName.equals('Closed Won');
   
    // Check that the field was changed to the correct value
    if (!oldOppIsWon && newOppIsWon) {
      opp.I_am_Awesome__c = true;
    }
  }
}

when I try to save the above code, iam getting error message Error Error: Compile Error: Invalid field I_am_Awesome__c for SObject Opportunity at line 13 column 7
 I have I_am_Awesome__c custom field in the oppurtunity object still I am getting the message, can some one help me on this?
Hi

Me again- I have written a trigger on a join object to update the one of its parent object based on the other's details.

The two objects are Accounts and Rate Type and the join object is called Company and Rate Type Links. May someone please take a look and let me know where I am going wrong as it is not firing.

trigger UpdateGroupRates on Company_and_RateType_Link__c (after update, after insert)
{  
if(trigger.isUpdate)
{
  Set<Id> accountIds = new Set<Id>();
  Set<Id> ratesIds = new Set<Id>();
  for(Company_and_RateType_Link__c tempJ : Trigger.new)
  {
   accountIds.add(tempJ.Company__c);
   ratesIds.add(tempJ.Rate_Type__c);
  }
 
  List<Account> AccountList = [Select Id, name, Rate_Type__c, Fixed_Credit_Card_Rate__c, Fixed_Debit_Card_Rate__c from Account where Id IN: accountIds];
 
  List<Rate_Type_del__c> Ratelist = [Select id, Name, Rate_Type__c, Number_Credit_Card_Fee__c, Number_Debit_Card_Fee__c from Rate_Type_del__c where id in: ratesIds];
 
  for(Company_and_RateType_Link__c tempJ : Trigger.new)
  {
   for(Account tempAcc : AccountList)
   {
    if(tempJ.Company__c == tempAcc.Id)
    {
     for(Rate_Type_del__c tempRate : Ratelist)
     {

                       if(tempJ.Rate_Type__c == tempRate.Id )
      {
       tempAcc.Rate_Type__c = tempRate.Rate_Type__c;
                            tempAcc.Fixed_Credit_Card_Rate__c = tempRate.Number_Credit_Card_Fee__c;
                            tempAcc.Fixed_Debit_Card_Rate__c = tempRate.Number_Debit_Card_Fee__c;
      }    
    
     }
   
    }
  
   }
  
  } 
   update AccountList;
}
      
}
  • September 09, 2014
  • Like
  • 0
Hi,
I am trying to create a validation rule for if a value is inserted into the picklist, two text boxes must have information in them. The formula i have created so far is:
OR(
ISPICKVAL(Manufacturer_PC__c, “Apple”),
ISPICKVAL(Manufacturer_PC__c, “Blackberry”),
ISPICKVAL(Manufacturer_PC__c, “HTC”),
ISPICKVAL(Manufacturer_PC__c, “Nokia”),
ISPICKVAL(Manufacturer_PC__c, “Samsung”),
ISPICKVAL(Manufacturer_PC__c, “Sony”),
ISBLANK(IMEI__c),
ISBLANK(serial_number__c ))
If any of them values are chosen in the picklist, IMEI and Serial number textboxes should not be null.
Many thanks.

How to use continuation class for Webservice callout from trigger using future method.

Is it possible using trigger? We can use it with Visualforce page but I want to use it with trigger.

Please help.
Someone could help me to create a class test for my trigger? i'm kinda newbie on salesforce :p

.here is my trigger.
trigger MembroOportunidade_aiu on OpportunityTeamMember (after insert, after update) {
	
	for(OpportunityTeamMember om : Trigger.New){
		// verificar se papel do membro do time é igual a representante de vendas 	
		if(om.TeamMemberRole == 'Representante de Vendas'){
			   Opportunity opp = [Select o.Vendedor__c, o.Id From Opportunity o 
			   					  where Id = :om.OpportunityId];
			   opp.Vendedor__c = om.UserId;
		// se papel correto, alterar vendedor da oportunidade		
		 update opp;		   
		}
	}		
}

 
Hi,

 Please suggest me am find challenge in improving performance in code coverage. Please advice me if this code is correct or not how to modify to get more code coverage. 

 Below code is working perfect only issue is with code coverage. 
 
trigger NewDiscountProgramUpdate on Opportunity (Before Update) 
{
// ******** Trigger Created By Sudhir ************  
// Loop through the incoming records

  list<opportunity> opp = new list<opportunity>();


for (Opportunity o : Trigger.new) {       
    
        
   // Check for Deal Reg Not Null
 if ( o.FORCE_NSP__c == NULL && o.discount_program__c <> 'NSP' && o.Deal_Registration__c <> NULL ) 
   {
     if ( o.Partner_Driven__c == 'Yes'  && o.Partner_Led__c == 'No' && o.K_12__c == 'No'  ) 
      {
        o.discount_program__c = 'DEALREG/PI';
        o.Abbv_Discount_Program__c = 'DR/PI';        
      }
     else if ( o.Partner_Driven__c == 'No'  && o.Partner_Led__c == 'Yes' && o.K_12__c == 'No'  ) 
     {
        o.discount_program__c = 'DEALREG/PL';
        o.Abbv_Discount_Program__c = 'DR/PL';    
     }
     else if ( o.Partner_Driven__c == 'Yes'  && o.Partner_Led__c == 'Yes' && o.K_12__c == 'No'  ) 
     {
       o.discount_program__c = 'DEALREG/PI/PL';
       o.Abbv_Discount_Program__c = 'DR/PI/PL';  
     }
     else if ( o.Partner_Driven__c == 'No'  && o.Partner_Led__c == 'No' && o.K_12__c == 'Yes' ) 
     {
       o.discount_program__c = 'DEALREG/K-12';
       o.Abbv_Discount_Program__c = 'DR/K12';    
     }
     else if ( o.Partner_Driven__c == 'Yes'  && o.Partner_Led__c == 'No' && o.K_12__c == 'Yes' )
     {
       o.discount_program__c = 'DEALREG/PI/K-12';
       o.Abbv_Discount_Program__c = 'DR/PI/K12';    
     }
     else if (   o.Partner_Driven__c == 'No'  && o.Partner_Led__c == 'Yes' && o.K_12__c == 'Yes'  )
     {
       o.discount_program__c = 'DEALREG/PL/K-12';
       o.Abbv_Discount_Program__c = 'DR/PL/K12';   
     }
     else if ( o.Partner_Driven__c == 'Yes'  && o.Partner_Led__c == 'Yes' && o.K_12__c == 'Yes' )
     {
       o.discount_program__c = 'DEALREG/PI/PL/K-12';
       o.Abbv_Discount_Program__c = 'DR/PI/PL/K12';   
     }
    else  
     {
     o.discount_program__c = 'DEALREG';
     o.Abbv_Discount_Program__c = 'DR';     
     } 
    }
     opp.add(o);
 }   
     
 
}


Please advice me also how to write test class for above trigger I wrote a test class which is giving only 14% code coverage. 

Thanks

Sudhir

This validation rule makes sure that if either the checkbox  Non_Standard__c is checked or the text field Non_Standard_Terms_Conditions__c is populated, the user has to fill in the Non_Standard_Terms__c multi-select pick list.

This is not working:
AND (
OR(Non_Standard__c = TRUE, NOT (ISBLANK(Non_Standard_Terms_Conditions__c ))),
ISBLANK( Non_Standard_Terms__c )
)

Could you please help me?

Thanks a lot in advance.
 

Hi,

Need to write a trigger such that if a Contact already exists ( based on email, phone or name) on the Parent Account or any of the Parents' Child accounts, then if a user tries to Create a Contact, an error should be thrown.

This trigger should be Account based and not Org. 

Thank You.

  • October 20, 2014
  • Like
  • 0
trigger updatepicklistlist on Orderc__c (after insert,after  Update,after delete) {
  Map<id,Account> mapAcc=new Map<id,Account>();
  set<id> accids=new set<id>();
list<Orderc__c> lstorder=new list<Orderc__c>();
      for(Orderc__c ord:trigger.new){
       accids.add(ord.Party_Name__c);
   }
     for(Orderc__c ord:trigger.old){
       accids.add(ord.Party_Name__c);
   }
for(account acc:[select id,Status__c,Discount__c from  account where id =: accids]) 
      {
     mapAcc.put(acc.id,acc);
         
     System.debug('List of Acccounts@@@@@@@@@@@@@@@@@@'+mapAcc);
      }
  if(accids.Size()>0)
  {
      for(Orderc__c o:Trigger.New)
      {
          if(mapAcc.get(o.Party_Name__c) .Discount__c==Null)
          {
             o.addError('Please Enter Discount in Account'); 
          }
          else
          {
             mapAcc.get(o.Party_Name__c) .Status__C='Existing';  
          }
       
        
      }
   
  }
Update mapAcc.values();
}
<apex:page standardController="Account" recordSetVar="accs">
<apex:pageBlock >
        <apex:pageBlockTable value="{!accs}" var="acc">
        <apex:column headerValue="Action"/>
        <apex:outputLink title="view detail in a Popup window" onclick="return openPopup('{!acc.Id}');"> Details </apex:outputLink>
       <apex:column value="{!acc.Name}"/>
       <apex:column value="{!acc.Industry}"/>
       <apex:column value="{!acc.Type}"/>
       </apex:pageBlockTable>
</apex:pageBlock>
<script>
    function openPopup(id)
    {
    var newwin=windows.open(!'{!$Page.Popup}?id='+id,'Popup','height=600,width=650,left=100,top=100,resizable=no',scrollbars=yes,toolbar=no,status=no');
    if(window.focus)
    {
    newwin.focus();
    }
    return false;
    }
    </script>
    </apex:page>
how to write a account trigger toupdate status picklistfield (cold call.prospecting,existing) on account change picklist field
to existing,whenever order is having atleast one order here order is lookup with account.
trigger insertrecord on x__c (before insert) {
list<x__c> cu=trigger.new;
for(x__c xg:trigger.new)
{
xg.name='hjh';
insert xg;
}
}
Hi everyone,
   There is a custom field of type 'checkbox' called "Primary" in Contact object. If this Primary is checked, then the value of the contact's Email field has to be updated in the custom email field named "PrimaryContactEmail"  in the Account Standard object. How can this be done in Trigger. Please do suggest a solution
Validation put in place to require more than two characters in length on Contact First and Last Name....can any one give me ans .


Thanks,
Viswa
Hi,

I have a requirment where there are two Custom Fileds 1.) Identification Details 2.) Identification proof here identification is a text data type and Identification Details is of Picklist which consists of an option of selecting SSN # I know that the field dependency cannot be applied for Identification proof since it is a text data type so I want to give a custom validation saying if the user selects the SSN# then the format of the SSN should be like "1234-4567-125" and whenever the identification detail is selected then the Identification proof must be made compulsory field.

Hope you understand my requirment please help me with this.

Regards
How Can I Write Calculator Prog In VF Page? Plz Any One Can Ping The Prog Or Syntax
User-added image

I am trying to build a report in apex and send an html email.
The report is basicly counting records number. But it has cross queries.
Can you look my code and comments and give me some advice?

Thank you!
  • September 20, 2014
  • Like
  • 0
I want to save current record and want id of that saved record to pass through to page reference . My controller is:
public HomeEvaluationController (ApexPages.StandardController sc)
      {
        myCustomObject = (HomeEvaluation__c) sc.getRecord();
        controller=sc;
     
      }
public PageReference New_form_save()
        {
         controller.save();

           pageid=myCustomObject.Id;
      
         Pagereference ref = new Pagereference('/apex/Ventilation_Ducting?id='+pageid);
         ref.setRedirect(true);
         return ref;
         }

I am getting null value in page id , please help me out
I know why the error " Illegal assignment from List to Id" is coming here..how to resolve it. any ideas ?

public with sharing class ExamplePageController {
 
    public list<String> InitialList  {get;set;}
    public list<String> CurrentList  {get;set;}

    public ExamplePageController() {
    InitialList = new list<String>();
    InitialList.add(UserInfo.getUserId());
    CurrentList = new list<String>();
   
  }
   
  public PageReference manualShareRead(){
      Id recordId= ApexPages.currentPage().getParameters().get('parentid');
      //Id userOrGroupId='005f0000000jioGAAQ';
      Id userOrGroupId=CurrentList;
      // Create new sharing object for the custom object Job.
      Scheme__Share jobShr  = new Scheme__Share();
  
      // Set the ID of record being shared.
      jobShr.ParentId = recordId;  
      system.debug('-------------------Record Id----------'+recordId); 
      // Set the ID of user or group being granted access.
      jobShr.UserOrGroupId = userOrGroupId;
      system.debug('-------------------User Id----------'+userOrGroupId);
      // Set the access level.
      jobShr.AccessLevel = 'Edit';
       
      // Set rowCause to 'manual' for manual sharing.
      // This line can be omitted as 'manual' is the default value for sharing objects.
      jobShr.RowCause = Schema.Scheme__Share.RowCause.Manual;
       
    --------------- remaining code-------------