XF 2.1 How to add custom user profile field on addon install?

XDinc

Well-known member
Hi everyone,
I would like to create a custom user field option when addon install...I have no experience with user_field before,

I have some questions to ask.. I'd appreciate it if you were the supporter or join discussion.
Please, If there's something (resource or post about this problem) I missed, forward it.

My sample code is below,
Code:
<?php

namespace XDinc\NewAddon;

use XF\AddOn\AbstractSetup;
use XF\Db\Schema\Alter;
use XF\Entity\UserProfile;

class Setup extends AbstractSetup
{
    public function install(array $stepParams = [])
    {
        $this->db()->insertBulk('xf_user_field', [
            [
                'field_id' => 'x_field',
                'display_group' => 'preferences',
                'display_order' => 10,
                'field_type' => 'select',
                'field_choices' => '',
                'user_editable' => 'yes',
                'moderator_editable' => 'yes',
                'match_type' => 'none',
                'match_params' => '',
                'max_length' => 0,
                'viewable_profile' => 0,
                'viewable_message' => 0,
                'display_template' => ''
            ],
         
        ], 'field_id');

        \XF::repository('XF:UserField')->rebuildFieldCache();
    }

    public function upgrade(array $stepParams = [])
    {
        // ToDo: Implement upgrade() method.

        // \XF::repository('XF:UserField')->rebuildFieldCache();
    }

    public function uninstall(array $stepParams = [])
    {
       $this->db()->delete('xf_user_field','field_id = ?', 'x_field');

}

QS-1. How can I add field title and description?

I don't think it's that way;
"field_title" or "field_description"

QS-2. How can I add to choices? (Ex: Enable-Disable)
Code:
  'field_choices' => '???',
QS-3. How can I set field to default choice? (Ex: Default: Enable)


I want it to look like this when I installed addon;

198773

@Chris D ;
@Xon ; @DragonByte Tech

Thanks for your support.
 
Take a look at this topic for a good example: https://xenforo.com/community/threads/add-custom-user-profile-field-on-addon-install.153396/
Code:
$field = $this->em()->create('XF:UserField');
$field->field_id = 'fieldId';
// set other fields

$title = $field->getMasterPhrase(true);
$title->phrase_text = 'Title';
$field->addCascadedSave($title);

$description = $field->getMasterPhrase(false);
$description->phrase_text = 'Description';
$field->addCascadedSave($description);

$field->save();
 
Top Bottom