Posted by jdemeza81 on
Leave a commentI already identified some of the shortcomings of the Magento SOAP API in my previous article including a lack of pagination. Since then I’ve realised another interesting feature that I think is missing (or at least I can’t seem to find) and that is the ability to do an OR query via the API. By default, Magento treats all filters as AND queries. For example if I want to search for myself amongst the customers I could use the following filter:
1 2 3 4 | $filters = array('filter' => array( array('key' => 'firstname', 'value' => 'Jarrod'), array('key' => 'lastname', 'value' => 'Demeza') )); |
Which would create a SQL where clause like this:
1 | WHERE firstname = 'Jarrod' AND lastname = 'Demeza' |
But what if I wanted to find myself or a different customer? How do we construct our filter? To answer that question we are going to further enhance our module by creating a data helper that allows for a combination of AND and OR queries.
Helpers are stored in the Helper directory. Create that directory and the following file:
app/code/local/MezaIT/CustomerAddress/Helper/Data.php
1 2 3 4 | <?php class MezaIT_CustomerAddress_Helper_Data extends Mage_Api_Helper_Data { ... } |
Notice our class extends the Mage_Api_Helper_Data class. For the full implementation refer to the code on Github.
The same way we told the module about our models in the previous article, we need let the module know about the new helper. Add this entry to the config.xml in the ‘global’ section.
1 2 3 4 5 | <helpers> <mezait_customeraddress> <class>MezaIT_CustomerAddress_Helper</class> </mezait_customeraddress> </helpers> |
We can now call the helper from our API code like this:
1 2 | $helper = Mage::helper('mezait_customeraddress'); $parsedFilters = $helper->parseFilters($filters); |
For a better example take a look on Github where I have updated our existing ‘count’ and ‘pagedList’ methods to use the new helper.
Before we made our changes, filters where simply an array of complex filters that were interpreted as an AND query by Magento. Our helper has extended our methods to expect an array of arrays of complex filters. The inner arrays are the AND queries and the outer array is the OR query.
Now we can search like this:
1 2 3 4 5 6 7 8 9 10 | $filters = array('filter' => array( array( array('key' => 'firstname', 'value' => 'Jarrod'), array('key' => 'lastname', 'value' => 'Demeza') ), array( array('key' => 'firstname', 'value' => 'Someone'), array('key' => 'lastname', 'value' => 'Else') ) )); |
Which creates a SQL where clause like this:
1 | WHERE (firstname = 'Jarrod' AND lastname = 'Demeza') OR (firstname = 'Someone' AND lastname = 'Else') |
Ok, next we really are going to look at the C# portion of this series!
Tags: api, magento, php, soap, sql
Previously we expanded the Magento SOAP API to support a paginated list of customers and their default address information. Now […]
Read more© 2019 Meza Information Technology | Design by Vlad Carp