silverstripesilverstripe-4

SilverStripe CMS, Dropdown Field search by title or another match?


Hi I would like to get a search either by title or by product code in this use case, but the map('ID', 'Title') method does not expect an array to the second parameter, how could I get it?

/* original snippet */
DropdownField::create(
    'ProductID',
    'Prodotto',
    Product::get()->sort('Title', 'ASC')->map('ID', 'Title')
)->setEmptyString('-- Seleziona --');

/* dummy sample snippet */
DropdownField::create(
    'ProductID',
    'Prodotto',
    Product::get()->sort('Title', 'ASC')->map('ID', ['Code','Title'])
)->setEmptyString('-- Seleziona --');

I took a look at the API, unfortunately I couldn't find a method that satisfies this for the DropdownField.

Thank you


Solution

  • Your question asks for a search but your code is generating a string for the DropDownField.

    If you want more advanced labels for the Dropdown you'd need a helper method on the Product DataObject like

    public function getCodeAndTitleFormatted() 
    {
        return $this->Code . ': ' . $this->Title;
    }
    

    Then you use this method in your ->map() statement to create your DropDownField like:

    DropdownField::create(
        'ProductID',
        'Prodotto',
        Product::get()->sort('Title', 'ASC')->map('ID', 'getCodeAndTitleFormatted')
    )->setEmptyString('-- Seleziona --');