You will need to rewrite the method Mage_Catalog_Model_Resource_Product_Collection::addAttributeToSort()
and handle your attribute code separately.
Here is a similar example for showing products that have images on top of the ones that don't.
You can do a similar thing for your custom attribute.
Follow the example above, but make your new class look like this:
<?php
class Easylife_Sorting_Model_Resource_Product_Collection
extends Mage_Catalog_Model_Resource_Product_Collection {
public function addAttributeToSort($attribute, $dir = self::SORT_ORDER_ASC){
//don't screw up the admin sorting
if (Mage::app()->getStore()->getId() == Mage_Core_Model_App::ADMIN_STORE_ID){
return parent::addAttributeToSort($attribute, $dir);
}
if ($attribute == 'catname') {
$this->addAttributeToSelect($attribute);
//add a 1|0 flag for products depending on:
// - 0 - if the attribute value is null or empty
// - 1 - if the attribute is not null
$this->addExpressionAttributeToSelect(
'has_catname',
"(CASE WHEN {{catname}} = '' OR {{catname}} IS NULL THEN 0 ELSE 1 END)",
array('catname'=>$attribute)
);
//sort by the flag set above
$this->getSelect()->order(array('has_catname DESC', 'catname '.$dir));
return $this;
}
//if not sorting by catname let magento do its magic
else {
return parent::addAttributeToSort($attribute, $dir);
}
}
}
I haven't tested this but it should work...I think.