• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

How exactly do you go about extending a datawriter?

#1
I am trying to extend the forum datawriter, but I'm not doing something right. My datawriter is definitely getting initiated (IE all listeners are correct) but when I try to save a forum from the backend, I am given the error of: The field 'my_custom_field' was not recognised.

Here is my datawriter:

PHP:
<?php

class TFP_Addon_Extend_DataWriter_Forum extends XFCP_TFP_Addon_Extend_DataWriter_Forum
{
    protected function _getFields()
    {
        return parent::_getFields() + array('xf_forum' => array(
            'my_custom_field'  => array('type' => self::TYPE_UINT, 'default' => 0)));
    }

    protected function _preSave()
    {
        if (XenForo_Application::isRegistered('my_custom_field'))
        {
            $this->set('my_custom_field', $this->get('my_custom_field'));
        } else {
            $this->set('my_custom_field', 0);
        }
        return parent::_preSave();
    }
}
The new column exists in xf_forum and my forum edit screen in the admincp is showing the correct database value. The only thing holding me up is that I can't save it for some reason and I'm having a hard time finding an existing addon that extends a core datawriter.
 

Chris D

XenForo developer
Staff member
#2
The way you're adding your new array onto the existing array won't work. The overlapping keys ('xf_forum' in this case) won't overwrite or merge what's there already. Incidentally, using array_merge would also overwrite the existing 'xf_forum' key in its entirety with your 'xf_forum' key which would, in this case, actually remove all the existing fields and replace them with your own.

array_merge_recursive may work, but there is a better way! Just do this:

PHP:
    protected function _getFields()
    {
        $fields = parent::_getFields();

        $fields['xf_forum']['my_custom_field'] = array('type' => self::TYPE_UINT, 'default' => 0);

        return $fields;
    }
 
#3
I should have noticed that. Long day.

That fixed my error, but my field still wasn't saving. I finally figured out that in my _preSave() method I was using
PHP:
$this->get()
and I should have been using
PHP:
XenForo_Application::get()
. I got clued in my looking at another addon's code, though it isn't clear to me what XenForo_Application::get() actually does. But it does appear to be working now.
 

Robust

Well-known member
#5
array_merge_recursive actually still produced errors for me with other add-ons. The way Chris mentioned is the only way that has worked for me.