Search code examples
expressionenginecustom-fields

Custom field name mapping in expressionengine


I am making some changes to a site using ExpressionEngine, there is a concept I can't seem to quite understand and am probably coding workarounds that have pre-provided methods.

Specifically with channels and members, the original creator has added several custom fields. I am from a traditional database background where each column in a table has a specific meaningful name. I am also used to extending proprietary data by adding a related table joined with a unique key, again, field names in the related table are meaningful.

However, in EE, when you add custom fields, it creates them in the table as field_id_x and puts an entry into another table telling you what these are.

Now this is all nice from a UI point of view for giving power to an administrator but this is a total headache when writing any code.

Ok, there's template tags but I tend not to use them and they are no good in a database query anyway.

Is there a simple way to do a query on say the members table and then address m_field_1 as what its really called - in my case "addresslonglat".

There are dozens of these fields in the table I am working on and at the moment I am addressing them with fixed names like "m_field_id_73" which means nothing.

Anybody know of an easy way to bring the data and its field names together easily?

Ideally i'd like to do the following:

$result = $this->EE->db->query("select * from exp_member_data where member_id = 123")->row();
echo $result->addresslonglat;

Rather than

echo $result->m_field_id_73;

Solution

  • This should work for you:

    <?php    
    $fields = $data = array();
    $member_fields = $this->EE->db->query("SELECT m_field_id, m_field_name FROM exp_member_fields");
    foreach($member_fields->result_array() as $row)
    {
        $fields['m_field_id_'.$row['m_field_id']] = $row['m_field_name'];
    }
    
    $member_data = $this->EE->db->query("SELECT * FROM exp_member_data WHERE member_id = 1")->row();
    foreach($member_data as $k => $v)
    {       
        if($k != 'member_id')
        {
            $data[$fields[$k]] = $v;
        }
    }
    print_r($data);
    ?>
    

    Then just use your new $data array.