1

I have a custom fieldtype for Craft which stores its value as an array of Models using AttributeType::Mixed. See below for an example of the FieldType and Model setup

class MyCustomFieldType extends BaseFieldType
{
    public function defineContentAttribute()
    {
        return AttributeType::Mixed;
    }
} 

class MyCustomModel extends BaseModel
{
    protected function defineAttributes()
    {
        return array(
            'url'      => AttributeType::String,
            'category' => AttributeType::String
        );
    } 
}

Then when the value is persisted, it's saved as an array, which Craft natively saves as JSON

$values = [new MyCustomModel(), new MyCustomModel(), ...];

To display the value in Twig I can do something like

{% for item in entry.myCustomField %}
    {{ item.category }}
{% endfor %}

My question is, how can I only display the elements in my field which have a specific attribute value? For example, if I wanted to display only those items with a category of main, where 'category' is an attribute on my model?

{% for item in entry.myCustomField.category('main') %}
    {{ item.category }}
{% endfor %}
1

Would this help?

Filter Entries by Field Value

Than it would be something like this I suppose (never used it myself):

{% for item in entry.myCustomField.search('category':'main') %}
    {{ item.category }}
{% endfor %}
  • Thanks for the help. I tried that ( the syntax is 'category:main' rather than 'category' : 'main') but that only seems to work for ElementCriteriaModel instances. Not sure how I can achieve the same thing for a custom type? – James Jan 28 '17 at 16:28
  • A long shot here. But have you tried it without the search() function? Just entry.myCustomField('category:main'). I would find it weird that it would work differently with custom fields than it does when using default ones. – Tom De Smet Jan 28 '17 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.