I Can Not Remove The Default Drop Down of a $has_o

2019-08-02 18:05发布

问题:

I have tried: removeFieldFromTab removeByName replaceField

But the field persists.

use SilverStripe\ORM\DataObject;
use //.....

class Product extends DataObject {
    private static $db = [
        'ProductName'=>'Varchar',
        'TagLine'=>'Text',
        'GeneralDescription'=>'HTMLText'

    ];
    private static $has_one = [
        'SplashImage'=>Image::Class,
        'ProductCategory'=>ProductCategory::Class
    ];
    private static $has_many = [
        'ProductImage'=>Image::Class,
        'Features'=>'Feature'
    ];
    private static $owns = [
        'SplashImage',
        'ProductImage'
    ];
    private static $summary_fields = array(
        'ProductName'=>'Product Name'
    );   
    private static $searchable_fields = [

    ];
    public function getCMSFields(){
        $fields = parent::getCMSFields();            

        $categoryField = DropdownField::create('ProductCategory', 'Choose Product Category', ProductCategory::get()->map('ID', 'ProductCategoryTitle'));            

        $fields->replaceField('ProductCategory', $categoryField);

        return $fields;     
    }
}

I am not getting any errors but the default drop down field that has the id #'s is at the top.

回答1:

With has_one relations the field name should be <RelationName>ID, so in your case ProductCategoryID.

You have to reference the append ID to the relation name in order for SilverStripe to remove the field from the CMS tab by name.

$fields->removeByName('ProductCategoryID');

Also, if you create a custom field for a has_one relation, make sure you use <RelationName>ID as the name for the field. Eg. to create a Dropdown, use:

DropdownField::create(
    'ProductCategoryID', // Use RelationName + ID
    'Choose Product Category', 
    ProductCategory::get()->map('ID', 'ProductCategoryTitle')
);