Search code examples
piranha-cms

Get/Set List Field on Blocks


This in my class in Models.Regions

public class Slider
{
    [Field]
    public StringField  Title       { get; set; }
    [Field]
    public TextField    Description { get; set; }
    [Field]
    public ImageField   Background  { get; set; }
    [Field(Title = "Text on Button")]
    public StringField  NameButton  { get; set; }
    [Field]
    public StringField  Link        { get; set; }
}

In Models.Blocks i make a Block named SliderBlock.cs and I need to insert a list of sliders

[BlockType(Name = "Slider", Category = "Content")]
public class SliderBlock : Block
{
    public List<Models.Regions.Slider> Sliders { get; set; }
}

How can I view the list from the manager?


Solution

  • The approach is slightly different for Blocks, and unfortunately the documentation is not up to date on this area. To create lists of Block you use a BlockGroup, for a slider accepting a single type of element the code could be:

    [BlockGroupType(Name = "Slider", Category = "Content")]
    [BlockItemType(Type = typeof(SliderItemBlock))]
    public class SliderGroup : BlockGroup
    {
    }
    
    
    [BlockType(Name = "Slider Item", Category = "Content", IsUnlisted = true)]
    public class SliderItemBlock : Block
    {
        [Field]
        public StringField Title { get; set; }
    
        [Field]
        public TextField Description { get; set; }
    
        [Field]
        public ImageField Background { get; set; }
    
        [Field(Title = "Text on Button")]
        public StringField NameButton { get; set; }
    
        [Field]
        public StringField Link { get; set; }
    }
    

    A couple of notes on the example code.

    1. As you can see them SliderGroup is in fact a Block as well. This means you can add fields to the Block Group as well if you want global fields that are valid for all of the items, for example background color. If you want to do this you need to add UseCustomView = true to the BlockGroupType attribute, and provide an EditorTemplate for the Block Group when you handle your global fields.
    2. In the BlockType attribute I have added IsUnlisted = true. This means that SliderItemBlock will only be visible when adding an item to a SliderGroup, and not when adding a block to the general page flow.
    3. You can specify multiple BlockItemType attributes for a group, this will give you the possibility to have a slider that supports different types of items. If you don't add any BlockItemType attributes to the group all block types will be available to add inside of the group.
    4. Don't forget that block groups needs to be registered, just like normal blocks.

    UPDATED 2019-09-26

    We've updated the documentation to include a section on how to create custom block groups which you can read here:

    http://piranhacms.org/docs/extensions/custom-block-groups

    Best regards

    Håkan