Create a list view filter via apex

Create a list view filter via apex for a custom object that would then be available to all users. Is this even possible ? and if so please provide a code example Thanks


Yes you can create list view from Apex. You can run the below code in the developer console to see a list view being created on a custom object. This is a little crude way of doing it. You can consume the Metadata API WSDL and then use that to create the list views, which is more cleaner way of doing it. 🙂

HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
req.setHeader('Content-Type', 'text/xml');
req.setHeader('SOAPAction', 'create');

String b = '<?xml version="1.0" encoding="UTF-8"?>';
b += '<soapenv:Envelope xmlns:soapenv="" xmlns:xsd="" xmlns:xsi="">';
b += '<soapenv:Header>';
b += '<ns1:SessionHeader soapenv:mustUnderstand="0" xmlns:ns1="">';
b += '<ns1:sessionId>' + UserInfo.getSessionId() + '</ns1:sessionId>';
b += '</ns1:SessionHeader>';
b += '</soapenv:Header>';
b += '<soapenv:Body>';
b += '<create xmlns="">';
b += '<metadata xsi:type="ns2:ListView" xmlns:ns2="">';
//This is the API name of the list view
b += '<fullName>Car__c.listView2</fullName>';
b += '<booleanFilter>1</booleanFilter>';
//Columns you want to display
b += '<columns>NAME</columns>';
b += '<columns>CREATED_DATE</columns>';
//Filterscope should be set to Everything for every one to be able to access this List view
b += '<filterScope>Everything</filterScope>';
// Enter the filter that you want to set
b += '<filters>';
b += '<field>NAME</field>';
b += '<operation>equals</operation>';
b += '<value>Mercedes </value>';
b += '</filters>';
b += '<label>Mercedes View</label>';
b += '</metadata>';
b += '</create>';
b += '</soapenv:Body>';
b += '</soapenv:Envelope>';

// Set this to org's endpoint and add it to the remote site settings.
HTTPResponse resp = h.send(req);

Source : Link , Question Author : max , Answer Author : Sam

Leave a Comment