Filter data in template or PHP callback - is there any preference?

abdfahim

Well-known member
In my PHP callback function for a custom page, I return a multidimensional array consisting all the custom user fields in crosstab format.

Code:
<?php
class MyTest_ControllerPublic_CustomField
{
    public static function getCustomField(XenForo_ControllerPublic_Abstract $controller, XenForo_ControllerResponse_Abstract &$response)
    {
        $db = XenForo_Application::getDb();
        $results = $db->fetchAll("SELECT u.username AS username, ufv.field_id AS field_id, ufv.field_value AS field_value FROM xf_user AS u
                INNER JOIN xf_user_field_value AS ufv ON (u.user_id = ufv.user_id)");
        $resultset = array();
        foreach($results as $val){
            $resultset[$val['username']][$val['field_id']] = $val['field_value'];
        }
        $response->params['customfields'] = $resultset;
    }
}
?>
Now, I want to display only those users who have a certain field_value for a certain field_id. So, in template, I am using
Code:
<xen:foreach loop="$customfields" key="$key" value="$value">
        <xen:if is="{$value.field_id_2} == "some_text">
            {$key}:{$value.field_id_1}<br>
        </xen:if>
</xen:foreach>
Here my question is, should I filter out the users inside the template as above (which causes PHP to pass larger array to template), or it is better to filter out them in the PHP file (which would result in an extra for loop):

Code:
<?php
class MyTest_ControllerPublic_CustomField
{
    public static function getCustomField(XenForo_ControllerPublic_Abstract $controller, XenForo_ControllerResponse_Abstract &$response)
    {
        $db = XenForo_Application::getDb();
        $results = $db->fetchAll("SELECT u.username AS username, ufv.field_id AS field_id, ufv.field_value AS field_value FROM xf_user AS u
                INNER JOIN xf_user_field_value AS ufv ON (u.user_id = ufv.user_id)");
        $resultset = array();
        foreach($results as $val){
            $resultset[$val['username']][$val['field_id']] = $val['field_value'];
        }

        foreach($resultset as $key=>$val){
            if($val['field_id_2'] == "some_text"){
                     unset($resultset[$key]);
            }
        }

        $response->params['customfields'] = $resultset;
    }
}
?>
 

abdfahim

Well-known member
Can I do that? To be honest, I don't know any simple SQL query to run in xf_user_field_value and results in the array as shown

Code:
Array (
    "user_1" => Array ( "field_id_1" => "Winter" ),
    "user_2" => Array ( "field_id_1] => "Summer" ),
    "user_4" => Array ( "field_id_1" => "Autumn" )
)
xf_user_field_value structure
upload_2017-7-20_13-33-26.png
 
Top