Search This Blog

Monday, January 26, 2009

Hide the nested controls when a Publishing field value is blank

In a Page Layout, when a publishing field value is blank, it may occupy few pixel space which creates uneven format positions. So overcome this I had created a custom control which supresses the control nested inside this custom control when the value of the field is blank.

------------------------------

Please compile the below code and check for typos since I extracted this from a code doing other things as well. From within the page using SPContext we have access to the data for the same page, hence we can check its value and decide to either render or not render the nested control contents.

Here is how usage would look like:

<custom:HideWhenBlank runat="server" FieldNameToCheck="ImageFieldHere">
....
.. <...... Field="ImageFieldHere" >


</custom:HideWhenBlank>

so the value of "ImageFieldHere" will be checked before displaying the image and if it is blank, all the HTML and publishing controls inside the tags will not be parsed and vice versa, i.e. if the image does exist it will be shown.
Also as a note 1) this will work for all data types and not just image types.
2) It is not necessary to inherit from SPSecurityTrimmedControl and you could use other UI base control.
3) In SPD in design mode you will continue to see the nested controls (a check made in above code for design mode), since we would not have access to SPContext at that time. We can the see the end result when the page is shown in browser.


Here is the code:


1 [CLSCompliant(false)]
2 [ParseChildren(false)]
3 [Guid("please put a guid here")]
4 public class CustomTrimming : Microsoft.SharePoint.WebControls.SPSecurityTrimmedControl
5 {
6 public string FieldNameToCheck {get;set;}
7 protected override void Render(HtmlTextWriter writer)
8 {
9 SPListItem item = null;

if (!DesignMode)

{

10 if (SPContext.Current != null)
11 {
12 item = SPContext.Current.ListItem;
13 }
14 if ((FieldNameToCheck != string.Empty) && (item != null))
15 {
16
17 if (CheckIfNullOrBlank(item[FieldNameToCheck]) == false)
18 {
19 base.Render(writer);
20 }
21 }
}
else // to display the nested controls / html when in SharePoint Designer 2007
{

base.Render(writer);


}
22 }
23
24 private bool CheckIfNullOrBlank(object data)
25 {
26 if (data == null || (Convert.ToString(data).Trim() == string.Empty))
27 {
28 return true;
29 }
30 else
31 {
32 return false;
33 }
34 }
35
36 }
37

Add the above as a Class file, add SharePoint dll references, assign a Strong Name key. Assuming you are using VseWSS, this will create a WSP file.

Hope this helps.
Mohan

No comments: