Skip to content

Context Aware Blocks

nairdo edited this page Feb 8, 2013 · 12 revisions

Sometime it's advantageous to create a BlockType that can perform some generic functionality against a variety of other entities. Adding the [ContextAware] decoration to your block will give it the ability use the entity that is in the "Context".

The attribute can be used in one of two ways. If your block can support context for any type of entity, you’d just decorate it with the [ContextAware] attribute without any parameter as shown here:

using Rock.Web.UI;

namespace RockWeb.Blocks.Core
{
    /// <summary>
    /// User control for editing the value(s) of a set of attributes for a given entity and category
    /// </summary>
    [ContextAware]
    [TextField( 1, "Entity Qualifier Column", "Filter", "The entity column to evaluate when determining if this attribute applies to the entity", false, "" )]
    [TextField( 2, "Entity Qualifier Value", "Filter", "The entity column value to evaluate.  Attributes will only apply to entities with this value", false, "" )]
    [TextField( 3, "Attribute Categories", "Filter", "Delimited List of Attribute Category Names", true, "" )]
    [TextField( 4, "Xslt File", "Behavior", "XSLT File to use.", false, "AttributeValues.xslt" )]
	public partial class AttributeCategoryView : RockBlock

Then, when you add an instance of your block to a page, the framework will automatically add a Block Field Attribute for the user-admin to set the type of entity that is providing context.

If your block only supports a specific entity type, you can include that type in the [ContextAware] attribute like this:

namespace Rock.Web.UI
{
    /// <summary>
    /// A Block used on the person detail page
    /// </summary>
    [ContextAware( "Rock.Crm.Person" )]
    public class PersonBlock : RockBlock

In this case, user-admin configuration is unnecessary since the block only supports a single entity type.

Using the Context

The page and framework are responsible for putting the necessary entities into the context when appropriate.

Continuing with the previous example of a block that is context aware of a Rock.Crm.Person entity, in order to obtain the actual person in the context, the block will use the ContextEntities dictionary and the key (which in this case is "Rock.Crm.Person") as shown here:

    if ( ContextEntities.ContainsKey( "Rock.Crm.Person" ) )
    {
        Person = ContextEntities["Rock.Crm.Person"] as Person;
Clone this wiki locally