1

I have a column named photo

How can I add a default image in a list item, which in my case is photo? for example If a user does not have the proper image for an item, or if he forget to add image. How to automatically add a default image?

My default image could be founded in /SiteAssets/default.png.

Thanks for your time!

  • Which SharePoint version are you using? I am confused by the tags which you have selected for the question. Please select proper tags, So others can identify & give you a solution. – Hardik May 10 '16 at 13:48
  • Do you want the solution using SharePoint Designer? & Is your SP 2013 is on-permises? – Hardik May 10 '16 at 13:49
2

Here's a example based on a jsLink-boilerplate I created. Because of the boilerplate origins there still is some code that is not used but for an example this will be enough.

Install it on your list following these steps:

  1. Edit the provided snippets and fill in your variables such as fieldname, listName, jsLinkPath, defaultValue, etc.
  2. Create a file based on my jsLink snippet and upload it to the masterpage catalog (you need to adjust the script path's for that).
  3. Run the Installationscript. This is used to attach the jsLink to the field. Afterwards SharePoint will add the .js where it's necessary.
  4. Visit your List and create a new item or edit an old. The .js we added should now add a default value if the field is empty or the other conditions fail.
  5. If you want to change the conditions search for the MAGIC in the provided jsLink

Installationscript:

var listName = 'YourListName';
var fieldName = 'YourColumnName';
var jsLinkPath = '~site/_catalogs/masterpage/callItWhateverYouWant.jslink.js';

var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var list = web.get_lists().getByTitle(listName);
var listFields = list.get_fields();

var field = listFields.getByTitle(fieldName);
field.set_jsLink(jsLinkPath);
field.update();

clientContext.load(field);
clientContext.executeQueryAsync(
       function () {
           console.log('jslink set to : ' + field.get_jsLink());
       }, function (err, args) {
           console.log('Error.');
           console.log(args);
       });

jsLink:

if (window.SPClientTemplates) {
    (function (_) {
        'use strict';

        ///########################################################################### Settings
        var settings = {
            solutionKey: 'ensureDefaultValue',
            fieldName: 'YourColumnName',
            defaultValue: 'http://YourDefaultImagePath.png',
            scriptUrl: '~site/style%20library/callItWhateverYouWant.jslink.js'
        };
        ///########################################################################### Settings

        ///########################################################################### Custom Render

        var DefaultValue = {};
        (function (_) {
            var ensureDefaultValue = function (ctx) {
                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
//!!!!!! MAGIC !!!!!!!
                var emptyValidator = function () {
                    emptyValidator.prototype.Validate = function (value) {
                        if (!value || value === 'http://' || value === 'something you dont want it to be') {
                            var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
                            formCtx.updateControlValue(settings.fieldName, settings.defaultValue);
                        }

                        return new SPClientForms.ClientValidation.ValidationResult(false, 'You never really use this its just a point in the lifecycle we can use.');
                    };
                };

                var validators = new SPClientForms.ClientValidation.ValidatorSet();
                validators.RegisterValidator(new emptyValidator());
                formCtx.registerClientValidator(formCtx.fieldName, validators);

                return defaultRenderField(ctx);
            };
            _.ensureDefaultValue = ensureDefaultValue;
        })(DefaultValue);

        ///########################################################################### Custom Render

        ///########################################################################### Default HTML Helper

        var defaultRenderField = function (_ctx) {
            var controlMode = _ctx.FieldControlModes && _ctx.FieldControlModes[_ctx.CurrentFieldSchema.Name] ?
                _ctx.FieldControlModes[_ctx.CurrentFieldSchema.Name] : _ctx.ControlMode;
            switch (controlMode) {
                case SPClientTemplates.ClientControlMode.DisplayForm:
                    return renderMapping[_ctx.CurrentFieldSchema.FieldType]['DisplayForm'](_ctx);
                    break;
                case SPClientTemplates.ClientControlMode.EditForm:
                    return renderMapping[_ctx.CurrentFieldSchema.FieldType]['EditForm'](_ctx);
                    break;
                case SPClientTemplates.ClientControlMode.NewForm:
                    return renderMapping[_ctx.CurrentFieldSchema.FieldType]['NewForm'](_ctx);
                    break;
                case SPClientTemplates.ClientControlMode.View:
                    return renderMapping[_ctx.CurrentFieldSchema.FieldType]['View'](_ctx);
                    break;
                default:
                    utilities.log('Could not determine Controlmode');
                    utilities.log(_ctx);
            }
        };

        var defaultRenderFieldView = function (_ctx) {
            var listItem = _ctx.CurrentItem;
            var listSchema = _ctx.ListSchema;
            var field = _ctx.CurrentFieldSchema;
            if (typeof field.FieldRenderer == 'undefined') {
                var fieldRenderMap = {
                    Computed: new ComputedFieldRenderer(field.Name),
                    Attachments: new AttachmentFieldRenderer(field.Name),
                    User: new UserFieldRenderer(field.Name),
                    UserMulti: new UserFieldRenderer(field.Name),
                    URL: new UrlFieldRenderer(field.Name),
                    Note: new NoteFieldRenderer(field.Name),
                    Recurrence: new RecurrenceFieldRenderer(field.Name),
                    CrossProjectLink: new ProjectLinkFieldRenderer(field.Name),
                    AllDayEvent: new AllDayEventFieldRenderer(field.Name),
                    Number: new NumberFieldRenderer(field.Name),
                    BusinessData: new BusinessDataFieldRenderer(field.Name),
                    Currency: new NumberFieldRenderer(field.Name),
                    DateTime: new DateTimeFieldRenderer(field.Name),
                    Text: new TextFieldRenderer(field.Name),
                    Lookup: new LookupFieldRenderer(field.Name),
                    LookupMulti: new LookupFieldRenderer(field.Name),
                    WorkflowStatus: new RawFieldRenderer(field.Name)
                };

                if (field.XSLRender == '1') {
                    field.FieldRenderer = new RawFieldRenderer(field.Name);
                }
                else {
                    field.FieldRenderer = fieldRenderMap[field.FieldType];
                    if (field.FieldRenderer == null)
                        field.FieldRenderer = fieldRenderMap[field.Type];
                }
                if (field.FieldRenderer == null)
                    field.FieldRenderer = new FieldRenderer(field.Name);
            }
            return field.FieldRenderer.RenderField(ctx, field, listItem, listSchema);
        };

        var renderMapping = {
            'Text': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPField_FormDisplay_Default(_ctx) },
                'EditForm': function (_ctx) { return SPFieldText_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldText_Edit(_ctx) }
            },
            'Number': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPField_FormDisplay_Default(_ctx) },
                'EditForm': function (_ctx) { return SPFieldNumber_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldNumber_Edit(_ctx) }
            },
            'Integer': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPField_FormDisplay_Default(_ctx) },
                'EditForm': function (_ctx) { return SPFieldNumber_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldNumber_Edit(_ctx) }
            },
            'Boolean': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPField_FormDisplay_DefaultNoEncode(_ctx) },
                'EditForm': function (_ctx) { return SPFieldBoolean_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldBoolean_Edit(_ctx) }
            },
            'Note': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPFieldNote_Display(_ctx) },
                'EditForm': function (_ctx) { return SPFieldNote_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldNote_Edit(_ctx) }
            },
            'Currency': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPField_FormDisplay_Default(_ctx) },
                'EditForm': function (_ctx) { return SPFieldNumber_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldNumber_Edit(_ctx) }
            },
            'File': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPFieldFile_Display(_ctx) },
                'EditForm': function (_ctx) { return SPFieldFile_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldFile_Edit(_ctx) }
            },
            'Calculated': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPField_FormDisplay_Default(_ctx) },
                'EditForm': function (_ctx) { return SPField_FormDisplay_Empty(_ctx) },
                'NewForm': function (_ctx) { return SPField_FormDisplay_Empty(_ctx) }
            },
            'Choice': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPField_FormDisplay_Default(_ctx) },
                'EditForm': function (_ctx) { return SPFieldChoice_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldChoice_Edit(_ctx) }
            },
            'MultiChoice': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPField_FormDisplay_Default(_ctx) },
                'EditForm': function (_ctx) { return SPFieldMultiChoice_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldMultiChoice_Edit(_ctx) }
            },
            'Lookup': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPFieldLookup_Display(_ctx) },
                'EditForm': function (_ctx) { return SPFieldLookup_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldLookup_Edit(_ctx) }
            },
            'LookupMulti': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPFieldLookup_Display(_ctx) },
                'EditForm': function (_ctx) { return SPFieldLookup_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldLookup_Edit(_ctx) }
            },
            'Computed': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPField_FormDisplay_Default(_ctx) },
                'EditForm': function (_ctx) { return SPField_FormDisplay_Default(_ctx) },
                'NewForm': function (_ctx) { return SPField_FormDisplay_Default(_ctx) }
            },
            'URL': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPFieldUrl_Display(_ctx) },
                'EditForm': function (_ctx) { return SPFieldUrl_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldUrl_Edit(_ctx) }
            },
            'User': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPFieldUser_Display(_ctx) },
                'EditForm': function (_ctx) { return SPClientPeoplePickerCSRTemplate(_ctx) },
                'NewForm': function (_ctx) { return SPClientPeoplePickerCSRTemplate(_ctx) }
            },
            'UserMulti': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPFieldUserMulti_Display(_ctx) },
                'EditForm': function (_ctx) { return SPClientPeoplePickerCSRTemplate(_ctx) },
                'NewForm': function (_ctx) { return SPClientPeoplePickerCSRTemplate(_ctx) }
            },
            'DateTime': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPFieldDateTime_Display(_ctx) },
                'EditForm': function (_ctx) { return SPFieldDateTime_Edit(_ctx) },
                'NewForm': function (_ctx) { return SPFieldDateTime_Edit(_ctx) }
            },
            'Attachments': {
                'View': function (_ctx) { return defaultRenderFieldView(_ctx) },
                'DisplayForm': function (_ctx) { return SPFieldAttachments_Default(_ctx) },
                'EditForm': function (_ctx) { return SPFieldAttachments_Default(_ctx) },
                'NewForm': function (_ctx) { return SPFieldAttachments_Default(_ctx) }
            }
        };

        ///########################################################################### Default HTML Helper

        ///########################################################################### Helper
        var utilities = {
            log: function (message) {
                if (window.console && window.console.log && settings.debugging) {
                    // console is available
                    console.log(settings.solutionKey + ' : ' + message);
                }
            }
        };
        ///########################################################################### Helper

        ///########################################################################### jsLink Overhead
        // Register renderer
        var registerField = function () {
            // JSLink event declaration
            var jsLink = {
                Templates: {},
                OnPostRender: [
                    function (ctx) {
                        //check if the list contains the field for jslink
                        if (listHasJsLinkField(ctx)) {
                            ctx.dataModel = ctx.dataModel || {};
                            ctx.dataModel[settings.key] = {
                                listId: ctx.listName,
                                viewId: ctx.view
                            };
                        }
                    }
                ]
            };
            var AllFields = [
                {
                    fields: [settings.fieldName],
                    forms: {
                        'NewForm': 'DefaultValue.ensureDefaultValue',
                        'EditForm': 'DefaultValue.ensureDefaultValue'
                    }
                }
            ];
            var fields = {};
            for (var i = 0; i < AllFields.length; i++) {
                for (var j = 0; j < AllFields[i].fields.length; j++) {
                    var forms = {};

                    for (var form in AllFields[i].forms) {
                        var functionObject = eval(AllFields[i].forms[form]);
                        forms[form] = functionObject;
                    }

                    fields[AllFields[i].fields[j]] = forms;
                }
            }
            jsLink.Templates.Fields = fields;

            SPClientTemplates.TemplateManager.RegisterTemplateOverrides(jsLink);

            function listHasJsLinkField(ctx) {
                for (var i = 0; i < ctx.ListSchema.Field.length; i++) {
                    if (ctx.ListSchema.Field[i].RealFieldName === settings.fieldName) {
                        return true;
                    }
                }
                return false;
            }
        };

        // Register init-function for mds
        var mdsRegisterField = function () {
            var thisUrl = SPClientTemplates.Utility.ReplaceUrlTokens(settings.scriptUrl);
            registerField();
            RegisterModuleInit(thisUrl, registerField);
        };

        // Check for MDS
        if (typeof _spPageContextInfo !== 'undefined' && _spPageContextInfo !== null) {
            utilities.log('Register jsLink for MDS');
            mdsRegisterField();
        } else {
            utilities.log('Register jsLink');
            registerField();
        }
        ///########################################################################### jsLink Overhead
    })({});
}
  • thanks you so much this is exactly what I was looking for! – Nderon Hyseni May 11 '16 at 12:03
  • but i cannot make it to work! – Nderon Hyseni May 12 '16 at 13:09
  • @NderonHyseni and what exactly was the problem? Did you check the browser dev tools? – Mx. May 25 '16 at 11:57
2

I am having a solution but it may be not the only solution. Here is my approach.

  • Create a Workflow which will trigger when a new item is added or existing item is changed
  • In the workflow check CurrentItem whether your ImageField is null?
  • If it is null then Set the value of your CurrentItem's ImageField to the default image URL
  • Make sure that you should have your default image uploaded somewhere in the library and you have proper link

Let me know your thoughts.

  • Thanks for your answer I appreciate it, but I cannot make it thought workflow. I want to make it with javascript – Nderon Hyseni May 10 '16 at 13:55
  • Are you using default list entry form? or you have made some custom form for entry? – Aakash Maurya May 10 '16 at 13:57
  • I am using default list entry – Nderon Hyseni May 10 '16 at 13:58
  • 1
    If you do not want a workflow then please clean up your tags, remove SharePoint-Designer and everything not relevant and add JavaScript as tag. Proper tags will... no.. might.. get you proper answer – Danny '365CSI' Engelman May 10 '16 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.