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

Answer

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.setMethod('POST');
req.setHeader('Content-Type', 'text/xml');
req.setHeader('SOAPAction', 'create');

String b = '<?xml version="1.0" encoding="UTF-8"?>';
b += '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
b += '<soapenv:Header>';
b += '<ns1:SessionHeader soapenv:mustUnderstand="0" xmlns:ns1="http://soap.sforce.com/2006/04/metadata">';
b += '<ns1:sessionId>' + UserInfo.getSessionId() + '</ns1:sessionId>';
b += '</ns1:SessionHeader>';
b += '</soapenv:Header>';
b += '<soapenv:Body>';
b += '<create xmlns="http://soap.sforce.com/2006/04/metadata">';
b += '<metadata xsi:type="ns2:ListView" xmlns:ns2="http://soap.sforce.com/2006/04/metadata">';
//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>';

req.setBody(b);
req.setCompressed(false);
// Set this to org's endpoint and add it to the remote site settings.
req.setEndpoint('https://ap1.salesforce.com/services/Soap/m/25.0');
HTTPResponse resp = h.send(req);
System.debug(resp.getBody());

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

Leave a Comment