function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dan HewDan Hew 

How can I create multiple listviews in APEX?

I need to create multiple list views for several users, how can I do this quickly in APEX?
Ajinkya1225Ajinkya1225
Hi Dan,

I'm not sure if I got your question correctly. If you need to create list views for sObjects (tabs), you can easily do this by using metadada api. Then you can deply profiles to assign appropriate views to profiles.

Here xml snippet for List Views-
 
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
. . .
    <listViews>
        <fullName>All_Mileages</fullName>
        <filterScope>all</filterScope>
        <label>All Mileages</label>
    </listViews>
    <listViews>
        <fullName>My_Mileages</fullName>
        <booleanFilter>1 AND 2</booleanFilter>
        <columns>NAME</columns>
        <columns>CREATED_DATE</columns>
        <filterScope>mine</filterScope>
        <filters>
            <field>NAME</field>
            <operation>equals</operation>
            <value>Eric Bristow</value>
        </filters>
        <filters>
            <field>City__c</field>
            <operation>equals</operation>
            <value>Paris</value>
        </filters>
        <label>My Mileages</label>
    </listViews>
. . .
</CustomObject>

Please upvote and mark this answer as solved, if it helped you.
Cheers!
Ajinkya Deshmukh
MandyKoolMandyKool
Hi Dan,

Creating list views is not supported by Apex as essentially ListViews are treated as Metadata.
You might need to use a Metadata API (https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_intro.htm) and if you want to do it using Apex you might want to look at this: https://github.com/financialforcedev/apex-mdapi

But the bottom line is that you will have to know Metadata API in order to create list views.

The other option you can think of is - Extracting current list views in eclispe (they come wrapped in object manifest) and modifying them and saving back to server. For this approach you should know how the metadata is represented in xml and how to change it create new list views.

Hopes this helps you!  
Dan HewDan Hew
Thank you both for your help, this is what I am looking for.
sfwizardsfwizard
It is difficult to do from Apex. But there are some metdata wrapper apex classes to do it. You might have better luck using jsforce library and doing it in a visualforce page like the object example in the link - https://salesforcecodes.blogspot.com/2020/04/how-to-connect-to-metadata-api-from.html