This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

Christopher19815
Christopher19815

Hello,

I am new to october cms and struggling. I must be looking in a completly wrong direction or expect something that simply isn't there with October. Please shed some light. I feel like an idiot :) :

In the fields.yaml of a model myModel i have a simple dropdown:

origin:
        label: 'Origin'
        span: auto
        type: dropdown

in the myModel class:

 public function getOriginOptions()
{
     return ['ch' => 'Switzerland',
             'at' => 'Austria',
             'de' => 'Germany'
         ];
 }

So I can create records which save to database with ch ,at or de for the column origin

Everything fine.

But then in the twig part of a front-end page : If I write {{ record.origin }} (where record is one record of myModel) , I simply get ch ,at or de rendered. But I want to display Switzerland ,Austria or Germany

...What basic concept am I missing here? What is the right way to display the value instead of the key?

Thank you very much for your time Christopher

Last updated

matthewpawley
matthewpawley

Hey,

You could simply set your array keys to the value, e.g:

return ['Switzerland' => 'Switzerland',
             'Austria' => 'Austria',
             'Germany' => 'Germany'
         ];

Or, render your twig as follows:

{{ record.getOriginOptions[record.origin] }}

You could also write a method in your model to retrieve the title value which you call in twig, something along the lines of:

public function getOrigin()
{
    $options = $this->getOriginOptions();
    return isset($options[$this->origin])
        ? $options[$this->origin]
        : '';
}

Which you could call in twig as {{ record.getOrigin }}

My preference would probably be the last suggestion.

Shantarli
Shantarli

You can use accessor here. Add this to your model:

public function getOriginAttribute()
{
    $value = array_get($this->attributes, 'origin');
    return array_get($this->getOriginOptions(), $value);
}
Christopher19815
Christopher19815

Got it. :)

Shantarli's advice works like a charm.

Toughdevelopers suggestions 2 and 3 probably have some little flaw and don't output anything for me.

Anyway: Thank you both!

1-4 of 4

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.