Showing posts with label Kentico Tips. Show all posts
Showing posts with label Kentico Tips. Show all posts

Friday, April 12, 2024

Kentico Cheat Sheets (Notes)

 These are the common requirement during the development in Kentico. Keeping these in one place will help the developers in their productivity.

// Ternary example

<%# !string.IsNullOrEmpty((string)Eval("YourColumn")) ? "True" : "False" %>

<%# !String.IsNullOrEmpty(Eval("YourColumn").ToString()) ? "True" : "False" %>   

<%# !string.IsNullOrEmpty((string)Eval("YourColumn")) ? "<p>For detailed information and more, please visit the <a href=\"" + Eval("YourColumn") + "\" target=\"_blank\">Link text 1</a> for this column.</p>" : Eval("YourColumn") + "<br /><br /><strong>For detailed another information please visit the <a onclick=\"_gaq.push(['_trackEvent', 'Link', 'Click' 'Event Topic'])\" target=\"_blank\" href=\"" + Eval("YourColumn") + "\">Link text 2</a> for this column.</strong><br />" %>  

<%# !String.IsNullOrEmpty(Eval("Column1").ToString()) || !String.IsNullOrEmpty(Eval("Column2").ToString()) ? "<strong>Value</strong><br>" : "" %>

/* ********** */

// IfEmpty

<%# IfEmpty(Eval("ImageLink"), "", "<img src=\"" + Eval("ImageLink") + "\" class=\"alignright\" alt=\"" + Eval("DocumentName") + "\" />") %>

<%# IfEmpty(Eval("DownloadLink"), "", "<a href=\"" + Eval("DownloadLink") + "\" class=\"btn icon-download\" target=\"_blank\">Download</a>") %>

{% if (!String.IsNullOrEmpty(DocumentPageDescription)){ %}

  <p>{% DocumentPageDescription %}</p>

{% } #%}

/* ********** */

// Transformation: RegexReplace()

{% 

  replacedString = RegexReplace(YourColumn, @"[^0-9a-zA-Z\._]", string.Empty);

  return;

#%}

<p>{% replacedString %}</p>

/* ********** */

// Transformation: documents at specific path, classname

{% 

  subFolderHome = Documents["/SubFolder/Home"];

  subFolderHomeChildren = subFolderHome.Children.Where("ClassName = 'ProjectName.SubFolderHomepage'");

  return;

#%}

<ul>

{% subFolderHomeChildren.WithAllData.ApplyTransformation("ProjectName.Transformations.MainNavigation_Level_1") %}

</ul>

/* ********** */

// add 'active' class if 

{% 

  selectedPath = IsDocumentOnSelectedPath();

  isCurrent = IsCurrentDocument();

  return;

#%}

<li class="nav-item{% if( isCurrent || selectedPath ) { " active" }#%}">

  <a class="nav-link" href="{% NodeAliasPath %}">

    {% IfEmpty(DocumentMenuCaption, DocumentName, DocumentMenuCaption) %}

  </a>

</li>

/* ********** */

// Visbility

<p runat="server" Visible='<%# Eval<string>("Name") != "some-value" %>'>

<asp:Placeholder runat="server" ID="pl1" visible='<%# ... %>'>

   ...

</asp:Placeholder>

<asp:Placeholder runat="server" ID="pl2" visible='<%# !pl1.Visible %>'>

   ...

</asp:Placeholder>

<cms:QueryRepeater ID="qrConcentrations" runat="server" 

    Visible='<%# isCurrentPage(Eval<String>("nodeAlias"))%>'

    QueryName="custom.DegreePrograms.GetConcentrationsBySchoolModalityAndCategory" 

    TransformationName="custom.degreeprograms.concentrations" 

    OrderBy="v1.DegreeName ASC" 

    PagerControl-PagerHTMLBefore="<li>" 

    PagerControl-PagerHTMLAfter="</li>">

</cms:QueryRepeater>


/* check if webpart contains content, hide if no content */

{% (ViewMode != "LiveSite") || (et_sc != null && et_sc.Trim() != "") #%}

{% if ((et_sc != null && et_sc.Trim() != "") == False) { "Full-width" } else { if ((et_sc != null && et_sc.Trim() != "") == True) { "two-column" } } #%}


{% if(OfficeShowStaff == True) { return true; } else { return false; }  #%}


/* transformation: check if first record */

<%# DataItemIndex == 0 ? "First record" : "Not first record" %>


/* transformation: check if last record */

<%# DataItemIndex == DataRowView.DataView.Count - 1 ? "Last record" : "Not last record" %>

{% DataItemIndex == DataItemCount - 1 ? "Last record" : "Not last record" %}

/* transformation: `ApplyTransformation` */

{% Documents[NodeAliasPath].Children.WithAllData.ApplyTransformation("custom.VirtualMapImageGallery.CarouselGallery_Slide") #%}

{% Documents["/News"].Children.WithAllData.ApplyTransformation("custom.VirtualMapImageGallery.CarouselGallery_Slide") #%}

/* K# Examples */

// If statement

{% if (CurrentDocument.RelatedTitlesHeader == "") { "Related Books" } else { CurrentDocument.RelatedTitlesHeader } %}

{% if (bizFormField != null) { "<p>$$value:bizFormField$$</p>" } %}

// Nested if statement

{% if (CMSContext.CurrentDocument.RelativeURL == "~/georgia/rate-quote") { GetResourceString("MHI.RateQuote.Georgia") } else { if (CMSContext.CurrentDocument.RelativeURL == "~/indiana/rate-quote") { GetResourceString("MHI.RateQuote.Indiana") } else { if (CMSContext.CurrentDocument.RelativeURL == "~/oklahoma/rate-quote") { GetResourceString("MHI.RateQuote.Oklahoma") } else { if (CMSContext.CurrentDocument.RelativeURL == "~/south-carolina/rate-quote") { GetResourceString("MHI.RateQuote.SouthCarolina") }}}} #%}

// Escaping apostrophe in macro conditional

{% if (QueryString["DateSelected"]) { %} 

    CONVERT(date, EventDate) <= '{% QueryString["DateSelected"]|(handlesqlinjection)true %}' AND CONVERT(date, EventEndDate) >= '{% QueryString["DateSelected"]|(handlesqlinjection)true %}'

    {% }|(handlesqlinjection)false 

#%}

// select parent document name based on nodealiaspath

{% Documents[NodeAliasPath].Parent.DocumentName #%}

/* WebPart Visibility */

// Do NOT show if DocumentName is equal to "Home"

{%DocumentName|(notequals)Home|(truevalue){?param?}%}

// Do NOT show if NodeID is equal to "321"

{%NodeID|(notequals)321|(truevalue){?param?}%}

// Hide page(s) in the /Landing-Pages directory

{%CMSContext.CurrentDocument.NodeAliasPath|(Contains)Landing-Pages|(not)#%}

// Show if DocumentName is equal to "Home"

{%DocumentName|(equals)Home|(truevalue){?param?}%}

// Show if path contains

{%Contains(CMSContext.CurrentDocument.NodeAliasPath, "Landing-Pages")#%}

// Show if path does not contain

{%!Contains(CMSContext.CurrentDocument.NodeAliasPath, "Landing-Pages")#%}

{%not(Contains(CMSContext.CurrentDocument.NodeAliasPath, "Landing-Pages"))#%}

{% !EditedObject.NodeAliasPath.Contains("/Parts-Store") #%}

// Visibility based on Wildcard value

{%QueryString["County"] != ""%}

// Get QueryString value

{% QueryString.parameter %}

// Multiconditional

{% if (PortalContext.ViewMode == "Design") { return false; } else { if (PortalContext.ViewMode == "Edit") { return false } else { return true }} #%}

// Date format

<%# GetDateTime("BlogPostDate", "D") %>

{% CurrentDateTime.Year#%}

{% CurrentDocument.DocumentModifiedWhen.Format("{0:MM/dd/yyyy}") #%}    /* 09/12/2016 */

{% CurrentDocument.DocumentModifiedWhen.Format("{0:T}") #%}             /* 1:42:31 PM */

/* String replace */

// Kentico: Transformation, string replace, tolower

<%# Eval("DocumentName").ToString().Replace(" ", "-").ToLower() %>

/* Kentico caching long lists of data */

items = Cache(GlobalObjects.CustomTables["BCLS.Reagents"].items);

items2 = Cache(GlobalObjects.CustomTables["BCLS.FlowInstrumentsAndSoftware"].items);

// Resolve Localization strings in transformation

<%# ResHelper.LocalizeString("{$Autobag.SpareParts.Btn_AddToRFQ$}") %>

PersonDivision LIKE '%{% QueryString["School"].ToString().Replace("-", " ").ToLower() %}%' and PersonIsFacultyLeader = 1

/* Get Custom Table data using macro */

{% GlobalObjects.CustomTables["customtable.SampleTable"].Items[3].GetValue("ItemText") %}

/* Set site to non-https from db */

update CMS_SettingsKey

  set KeyValue='False'

  where KeyName='CMSUseSSLForAdministrationInterface'

  update CMS_Tree

  set IsSecuredNode= NULL, RequiresSSL=NULL

/* jquery ajax call example */

$.ajax({

  url: 'http://localhost/rest/content/currentsite/all?classnames=claremont.LocationContentBlock&hash=12c0c34e0ee345c1e1d5679a56b7efe4567d0a6b08f6a9b05a264be4657c8702',

  dataType: 'xml',

  success: function(xml, status, xhr) {

    $(xml).find('claremont_LocationContentBlock').each(function() {

      var name = $(this).find('DocumentName').text();

      var location = $(this).find('NodeAlias').text();

      var zip = $(this).find('ZipCode').text();

      $('<li>' + zip + ' - ' + name + ' (' + location + ')' + '</li>').appendTo('#zipCodes');

      $('<p>' + zip + '</p>').appendTo('#rawData');

    });

    console.log('Status: ' + xhr.statusText);

  },

  error: function(xhr, status, error) {

    console.log('Error occurred: ' + xhr.statusText);

  }

});

/* Dates */

<%# FormatDateTime(Eval("EventDate"), "MMMM d") %>

<%# IfEmpty(Eval("EventEndDate"), "", IfCompare(FormatDateTime(Eval("EventDate"), "MMM d"), FormatDateTime(Eval("EventEndDate"), "MMM d"), " - " + IfCompare(Eval<DateTime>("EventDate").Month, Eval<DateTime>("EventEndDate").Month, FormatDateTime(Eval("EventEndDate"), "MMMM d"), FormatDateTime(Eval("EventEndDate"), " d")), "")) %>

/* Format Numbers */

<%# String.Format("{0:n}", Int64.Parse(Eval("Field").ToString())) %>    // 100,000.00

<%# String.Format("{0:n0}", Int64.Parse(Eval("Field").ToString())) %>   // 100,000

<%# String.Format("{0:C}", Eval("TotalPriceIncludingOptions")) %>

/* sql */

/* populate dropdowns */

SELECT Code as Value, Code as Name FROM MyCodeTable

SELECT Location AS Code, Location FROM customtable_ConferenceLocations

SELECT REPLACE(Location, ' ','-') AS Code, Location FROM customtable_ConferenceLocations

SELECT '' AS Code, '-- Select Location --' AS Location

    UNION

SELECT Location AS Code, Location 

FROM customtable_ConferenceLocations

/* Check current version and hotfix version */

SELECT *

FROM CMS_SettingsKey

WHERE KeyName = 'CMSDataVersion' OR

KeyName = 'CMSDBVersion' OR

KeyName = 'CMSHotfixVersion'

/* get document by categories */

SELECT DocumentName

FROM View_CMS_Tree_Joined

WHERE DocumentID IN (Select DocumentID FROM CMS_DocumentCategory WHERE CategoryID in (Select CategoryID from CMS_Category where CategoryName IN ('News', 'FAQs')))

/* Custom table control settings */

Custom table item selector form control: https://www.screencast.com/t/slxjPobM

/* transformation: custom variable */

{%

  myVariable = ( !String.IsNullOrWhiteSpace( DocumentMenuCaption ) ) ? DocumentMenuCaption : DocumentName;

  return;

#%}

<a href="GetDocumentUrl()">{% myVariable %}</a>

/* pipe delimited list */

{% if (!String.IsNullOrEmpty(LocationFeaturesList)) { %}

  <ul class="list-unstyled text-primary lead mb-3">

    <li>{% LocationFeaturesList.ToString().Replace("|","</li><li>") %}</li>

  </ul>    

{% } #%}

/* CSS cache busting  */

<link href="~/CMSPages/GetResource.ashx?stylesheetname=<CODE_NAME>&vid={% GlobalObjects.CssStylesheets.<CODE_NAME>.StylesheetVersionGUID #%}" type="text/css" rel="stylesheet"/>