Hanan Ali
Hanan Ali

Reputation: 102

Magento Conditional addFieldToFilter

I wanted to create a IF CONDITION in collection. If $mtype is not empty then this condition work addFieldToFilter('main_table.m_type', $mtype) and if the criteria does not match this filter would not work.

$collection = Mage::getModel('manufacturers/manufacturers')->getCollection()
                                ->addStoreFilter(Mage::app()->getStore(true)->getId())
                                ->addFieldToFilter('main_table.status', 1)
                                ->addFieldToFilter('main_table.m_type', $mtype)
                                ->addOrder(Mage::helper('manufacturers')->getManufacturerSort(), Mage::helper('manufacturers')->getManufacturerOrder())
                            ->getData();

I hope you people know about the answer of this question or you would guide me a better way to do.

Thanks, Hanan Ali

Upvotes: 3

Views: 807

Answers (1)

Roman Snitko
Roman Snitko

Reputation: 3655

$collection = Mage::getModel('manufacturers/manufacturers')->getCollection()
    ->addStoreFilter(Mage::app()->getStore(true)->getId())
    ->addFieldToFilter('main_table.status', 1)
    ->addOrder(Mage::helper('manufacturers')->getManufacturerSort(), Mage::helper('manufacturers')->getManufacturerOrder());

if (!empty($mtype)) {
    $collection->addFieldToFilter('main_table.m_type', $mtype);
}

$data = $collection->getData();

Upvotes: 1

Related Questions