Pages

Showing posts with label Variants. Show all posts
Showing posts with label Variants. Show all posts

Friday, 16 July 2021

Umbraco - Copy Grid content

In Umbraco 7, we had Vorto to handle multi-lingual fields.

In Umbraco 8, Variants were introduced, as well as the split screen editor where you can have 2 languages side by side, for easier translation.

My problem?

Normal text fields can be easily copied left to right by selecting them and copy/pasting the content.
What's been bugging me since the very beginning, is that it's a real hassle to copy an entire grid to a new language.

As a Content Editor in charge of translating this content, I am required to rebuild the entire grid-structure. To translate the grid in the screenshot above, I would have to :

  • add an XL row
  • add a headline component
    • copy/paste the text (or translate it on the fly)
  • add a richtext component
    • copy/paste the text (or translate it on the fly)
  • add an M-M row
  • add an image component
    • figure out which image they used, if I want to use the same one
  • add a richtext component
    • copy/paste the text (or translate it on the fly)
  • ... and so on
This gets tedious very fast. What I really want to be able to do is copy the entire grid structure from left to right and then just translate the portions of text that I need to change.

This feature was requested in October 2019. It became up-for-grabs February 2020 (meaning, anyone who felt like it, could do an attempt at implementing it and making a pull request).
April 2021 someone picked it up and started working on it. The pull request is still pending further improvements.

Disclaimer(s) about my "solution"

  • It was tested on Umbraco 8.13. It should work on older versions and will probably remain working on future versions (minor tweaks could be needed, but are unlikely since it's so isolated).
  • When upgrading to a newer version, you'll probably need to redo the modifications.
  • It is a bit hacky (modifying files in Umbraco), but works fine for all the projects I'm working on.
  • It does not take into account that custom propertyeditors might subscribe to certain events emitted by the grid when e.g. adding a new row or control.

My solution

My quick and dirty solution to have the option of copy/pasting the entire structure of the grid from left to right (or even from item A to item B), consists of adding custom code to 2 files in the Umbraco codebase.

What will happen is:
  • A button "Copy Grid" is displayed next to the "Reorder" button. When pressed, the JSON describing the entire grid is copied to localStorage.
  • A button "Paste Grid" is displayed when no rows have yet been added to the grid and will simply grab the JSON from localStorage again. 

The good news is that these files are .js and .html, so there's no compilation step necessary, making this change something a 5 year old (with advanced computer skills) could do.

\Umbraco\js\umbraco.controllers.js

We have to place are code somewhere, so find the definition of the method called "toggleSortMode" (around line 19.000) and insert the following 2 function-definitions above it.
// Start Grid Copy/Paste
var gridCopyAlias = "grid-value-copy";

$scope.copyGridModel = function copyGridModel() {
    localStorageService.set(gridCopyAlias, $scope.model.value);

    var msg = 'Grid successfully copied to clipboard.';
    notificationsService.success(msg);		
}

$scope.pasteGridModel = function pasteGridModel() {
    try {
        var modelValue = localStorageService.get(gridCopyAlias);
        if (modelValue) {
            $scope.model.value = modelValue;							
        } else {
            var msg = 'Couldn\'t find a copied Umbraco Grid. Make sure to copy an existing Grid first.';
            notificationsService.error(msg);    
        }
    } catch (err) {
        var msg = 'Something went wrong pasting the Grid.';
        notificationsService.error(msg, err);
    }
}
// End Grid Copy/Paste

Then, scroll up a bit (~250 lines) to find the definition of Angular controller "Umbraco.PropertyEditors.GridController".
'use strict';
angular.module('umbraco').controller('Umbraco.PropertyEditors.GridController', function ($scope, localizationService, gridService, umbRequestHelper, angularHelper, $element, eventsService, editorService, overlayService, $interpolate) {

and inject 2 additional services at the end:
  • notificationsService : to be able to add warnings, errors in the backoffice
  • localStorageService : something to serve as a clipboard while copy/pasting
It should now look like 
'use strict';
angular.module('umbraco').controller('Umbraco.PropertyEditors.GridController', function ($scope, localizationService, gridService, umbRequestHelper, angularHelper, $element, eventsService, editorService, overlayService, $interpolate, notificationsService, localStorageService) {

\Umbraco\Views\propertyeditors\grid\grid.html

All the way at the top, you will find the definition for the ReOrder button.
    <umb-editor-sub-header appearance="white" ng-if="showReorderButton()">
        <umb-editor-sub-header-content-right>
            <umb-button action="toggleSortMode()" button-style="link" icon="icon-navigation" label-key="{{reorderKey}}" type="button">
            </umb-button>
        </umb-editor-sub-header-content-right>
    </umb-editor-sub-header>

We will add 2 of our own buttons here, to call the methods we just added to the controller.
Just replace the entire section with the code below
    <umb-editor-sub-header appearance="white" ng-if="!showReorderButton()">
        <umb-editor-sub-header-content-right>
            <umb-button action="pasteGridModel()" button-style="link" icon="icon-arrow-down" label="Paste Grid" type="button">
            </umb-button>
        </umb-editor-sub-header-content-right>
    </umb-editor-sub-header>

    <umb-editor-sub-header appearance="white" ng-if="showReorderButton()">
        <umb-editor-sub-header-content-right>
            <umb-button action="copyGridModel()" button-style="link" icon="icon-arrow-up" label="Copy Grid" type="button">
            </umb-button>

            <umb-button action="toggleSortMode()" button-style="link" icon="icon-navigation" label-key="{{reorderKey}}" type="button">
            </umb-button>
        </umb-editor-sub-header-content-right>
    </umb-editor-sub-header>

Make sure to put these modified files in your solution, or they will be overwritten the next time you do a deploy.

Wednesday, 1 July 2020

Umbraco - Enabling Language Fallback by default

Sometimes you need a fresh pair of eyes to see an obvious solution when you're stuck looking in the wrong direction.

(Skip the backstory to the technical implementation if you prefer technical stuff over the story)

Backstory

Earlier, I talked about using Modelsbuilder partial classes to enable Language Fallback on all variant properties, so your View Designers would have an easier time of using fallback without even realizing it.

The reason I want this is:

I want (Razor) View Designers to be able to use

Model.Title

and not

Model.Value<string>("title", fallback: Fallback.ToLanguage)

I want them to
  • not need to know HOW to get fallback on a poperty
  • not need to know WHEN to use it (when a property is variant)
  • not have an excuse to FORGET to use it
I ALSO don't want to use my previously discussed approach where I need to implemented each Variant property in a partial class.

I wanted to find a better solution. I wanted Modelsbuilder to generate the .Value() method using Language Fallback by default.
I went as far as implementing it and making a Pull Request for ModelsBuilder, based on an AppSetting to enable this behaviour.

The PR was basically refused and a long discussion ensued wether or not what I wanted had merit and my solution was the correct approach.

Until one day, Ronald Barendse commented (paraphrased) "Why don't you just override the default Umbraco behaviour?"

My eyes opened and I went to work (and completed it unexpectedly fast).

Implementation

The default behaviour resides in the PublishedValueFallback class. To enable a solution just for this situation, they made the TryGetValue method virtual, so you can override it with whatever you need.

using System.Linq;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Services;
using Umbraco.Web.Models.PublishedContent;

namespace Dpw.Eworld2.Foundation.Umbraco.PublishedContent

{
    public class CustomPublishedValueFallback : PublishedValueFallback
    {
        public CustomPublishedValueFallback(ServiceContext serviceContext, IVariationContextAccessor variationContextAccessor)
            : base(serviceContext, variationContextAccessor)
        {
            
        }

        public override bool TryGetValue<T>(IPublishedContent content, string alias, string culture, string segment, Fallback fallback, T defaultValue, out T value, out IPublishedProperty noValueProperty)
        {
            //When no fallback, use ToLanguage by default
            if (!fallback.Any(f => f == Fallback.DefaultValue || f == Fallback.Language || f == Fallback.Ancestors))
            {
                fallback = Fallback.ToLanguage;
            }

            return base.TryGetValue(content, alias, culture, segment, fallback, defaultValue, out value, out noValueProperty);
        }
    }
}

Bascially, what I do is : when no fallback of any sort is requested, I put fallback to Language Fallback. Nothing else needs to change.

To enable this custom class instead of the default one, you register it in your Startup class as follows:

composition.RegisterUnique<IPublishedValueFallback, CustomPublishedValueFallback>();

I was then able to toss my PR, my custom built ModelsBuilder-version, all remaining partial classes and never need to even think about which property will be Variant.

Wednesday, 15 April 2020

Umbraco 8 - Language fallback for Grid properties

In my previous post (which was hanging around in draft for months until I finally got around to finishing it) I mentioned that my way-of-working with Language Fallback does not work with Grid properties.

Grids are never really empty

The reason for this is that when you use property.Value("propertyAlias", fallback: Fallback.ToLanguage), the only scenario where fallback occurs, is when the value of that property is empty.
When you make a new language version of an item and you do not put anything in the grid, it still is not empty, because what constitutes as an "empty" grid, actually looks like this.

{
  "name": "1 column layout",
  "sections": [
    {
      "grid": "12",
      "rows": []
    }
  ]
}

A second problem I encountered, is that the HtmlHelper-extension that is used to render your grid in a view only accepts a propertyAlias and under the hood it goes straight for the property in question, not through .Value(), preventing you from adding a similar workaround as in my previous article.

Fortunately Umbraco is Open Source, and the code for GetGridHtml is easily located.

public static MvcHtmlString GetGridHtml(this HtmlHelper html, IPublishedContent contentItem, string propertyAlias, string framework)
{
    if (string.IsNullOrWhiteSpace(propertyAlias)) throw new ArgumentNullOrEmptyException(nameof(propertyAlias));

    var view = "Grid/" + framework;
    var prop = contentItem.GetProperty(propertyAlias);
    if (prop == null) throw new NullReferenceException("No property type found with alias " + propertyAlias);
    var model = prop.GetValue();

    var asString = model as string;
    if (asString != null && string.IsNullOrEmpty(asString)) return new MvcHtmlString(string.Empty);

    return html.Partial(view, model);
}

A new way of rendering

So, all I had to do was create my own class with my own extension method.

Now what happens is:
  • I get the value of the grid-property. With language fallback indicated, but that never happens, because a grid is never empty.
  • If the grid is functionally "empty", I get the English value of the same grid-property.
  • Normal processing resumes.

In my views, where - until now - I used the standard way of rendering grids, I had to add a using statement and change the name to my own extension method.

@using MyCode.Umbraco.Web.Extensions;
@inherits UmbracoViewPage<ContentPage>
@{
    Layout = "BasePage.cshtml";
}
<div>
    @Html.GetFallbackGridHtml(Model, ContentPage.GetModelPropertyType(c => c.Body).Alias, "site")
</div>

For those interested, here's the entire class. No rocket science, but it made my job just a little easier again.

using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
using Umbraco.Web.Composing;

namespace MyCode.Umbraco.Web.Extensions
{
    public static class GridExtensions
    {
        public static bool IsGridEmpty(object gridContent)
        {
            var asJToken = gridContent as JToken;
            if (asJToken != null)
            {
                //Check all sections
                var sections = asJToken["sections"] as JArray;
                if (sections != null && sections.Any())
                {
                    //If any section has any row --> not empty
                    foreach (var section in sections)
                    {
                        var rows = section["rows"] as JArray;
                        if (rows != null && rows.Any())
                        {
                            return false;
                        }
                    }
                }
            }

            return true;
        }

        public static MvcHtmlString GetFallbackGridHtml(this HtmlHelper html, IPublishedContent content, string propertyAlias, string framework = "bootstrap3")
        {
            var gridContent = content.Value(propertyAlias, fallback: Fallback.ToLanguage);

            //If gridcontent is "empty", do a fallback to defaultLanguage
            if (IsGridEmpty(gridContent))
            {
                var defaultLanguage = Current.Services.LocalizationService.GetDefaultLanguageIsoCode();
                gridContent = content.Value(propertyAlias, defaultLanguage);
            }

            return html.GetFallbackGridHtml(gridContent, framework);
        }

        public static MvcHtmlString GetFallbackGridHtml(this HtmlHelper html, object gridContent, string framework = "bootstrap3")
        {
            if (gridContent == null)
            {
                return new MvcHtmlString(string.Empty);
            }

            var view = "Grid/" + framework;
            return html.Partial(view, gridContent);
        }
    }
}

Umbraco 8 - ModelsBuilder with Language Fallback


In Umbraco 8, they introduced the much-anticipated multi-language feature called Variants.
I won't describe this in detail, just check the documentation on Variants.

Edit: the approach below is superseded by changing the default fallback behaviour of Umbraco as described here.

Language fallback

In concert with Variants, we can now have language fallback. This basically means that when you have an English and a Dutch version of a page, you do not HAVE to fill in every field on the Dutch version. When left empty it can fall back to the English version (assuming English is marked as Fallback Language in your language settings).


Now, fallback doesn't just magically work, it involves some work on your part.

Assume that message is a contentItem (derived from IPublishedContent) and we want to get the value of the title property.

The traditional way is to get it by calling the Value() method.
var title = message.Value<string>("title");

This will give you the value of the title in the current culture. If this is empty in Dutch, you will get an empty string.

Enable language fallback

To enable language fallback, you would add a fallback parameter.
var title = message.Value<string>("title", fallback: Fallback.ToLanguage);

Verify VariationContext

If - for some reason - the current culture in your context is not set or plain wrong, you can give the culture as a parameter to the Value() method, but this is not the way to go.

I use a lot of API's (derived from Umbraco.Web.WebApi.UmbracoApiController) and they usually don't set the current Umbraco culture.
Given a parameter language containing the culture you need (coming for instance from a request header), you can set the correct culture for Variant fallback as follows:

Current.UmbracoContext.VariationContextAccessor.VariationContext = new VariationContext(language);

You now get the title in the correct language or - when empty - the fallback langauge.

ModelsBuilder

I hear you thinking : "Dude, we've been using ModelsBuilder to have strongly-typed content models for years. Do you really expect us to go back to .Value("propertyName")?"

No, I do not. But it requires some more work.

I won't go into the details of Extending the Modelsbuilder, but here's the gist of it.
The generated class (simplified for brevity) for our Message model would be
[PublishedModel("message")]
public partial class Message : PublishedContentModel
{
    [ImplementPropertyType("title")]
    public string Title => this.Value<string>("title");

    [ImplementPropertyType("someProperty")]
    public string SomeProperty => this.Value<string>("someProperty");
}

We cannot modify this class, because it is generated by the ModelsBuilder. But because it is a partial class, we can extend it.

Below is the custom class you add to your project (same name and namespace as the generated one).
public partial class Message
{
    [ImplementPropertyType("title")]
    public string Title => this.Value<string>("title", fallback: Fallback.ToLanguage);
}

You'll need to remove the implementation for title from the generated class. The next time the generator runs, it will skip the title property because of the ImplementPropertyType-attribute in your custom class.

It is now possible for you to use the following code to get the title (with fallback) from the message item.
var title = message.Title;

Random thoughts

  • The above approach does not work for Grid content, but that's subject for a different post.
  • When creating a new language version of an item in Umbraco, the name of the item is a mandatory field. It would be nice if this could be left empty and also fallback to the English version.
  • If you make a field mandatory, it is mandatory in all languages, so you can't leave it empty and depend on fallback.
    Personally, I made many mandatory fields optional again, because I feel the advantage of fallback outways the need for mandatory fields. (your call)
Feedback or questions? Give me a shout.