phpwordpressdynamics-crmalexacrm-toolkit

Using AlexaCRM/dynamics-webapi-toolkit I need to add a filter for a "modifiedon" datetime


As the title says, I am using the AlexaCRM/dynamics-webapi-toolkit package in a php project. I have some code where I retrieve multiple records (That part works). However, I need to add a sort of filter where I only get the ones that has "modifiedon" for the last X days. Here is current working code

$pagingInfo = new \AlexaCRM\Xrm\Query\PagingInfo();
$pagingInfo->Count = 10;

$client = ClientFactory::createOnlineClient(
    'https://some-microsoft-crm.com',
    'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
    'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
);

$query = new QueryByAttribute('contact');
$query->ColumnSet = new \AlexaCRM\Xrm\ColumnSet(columnSet(true));
$query->PageInfo = $pagingInfo;

$result = $client->RetrieveMultiple($query);

The format for "modifiedon" is "2024-07-22T10:57:01Z". (This works if I put in the exact date for $query->AddAttributeValue("modifiedon", $twoDaysAgoDateTimeFormat);

I have tried adding a parameter as some other forum suggested, but it failed every time I did the request on this line: $query->AddAttributeValue("modifiedon", 'ge ' . $twoDaysAgoDateTimeFormat); or $query->AddAttributeValue("modifiedon ge", $twoDaysAgoDateTimeFormat);

Any suggestions would be helpful.


Solution

  • First, the QueryByAttribute only supports operator " eq ". You can refer to source code line 400.

    You should use FetchExpression instead. Below code retrieves contacts that modified in the last 3 days:

    $fetchXML = <<<FETCHXML
    <fetch mapping="logical"> 
        <entity name="contact">
            <all-attributes />
            <filter>
                <condition attribute="modifiedon" operator="last-x-days" value="3" />
            </filter>
        </entity>
    </fetch>
    FETCHXML;
    
    $fetchExpression = new FetchExpression($fetchXML);
    $collection = $client->RetrieveMultiple($fetchExpression);
    

    Here is the official tutorial.

    BTW, FetchXml can also be generated with Advanced find(step1-3) and FetchXML Builder.