Copy image from field to a variable

Kumar38
Kilo Sage

I have a catalog item that has attachment variable and reference variable. Upon selection of a record from a reference field , picture (type : user_image ) available on the selected record needs to be copied over to attachment variable. Is this possible , given that the target cannot be defined ?

 

2 REPLIES 2

Anubhav24
Mega Sage
Mega Sage

Robert34
Tera Contributor

Hi Kumar,

You can try to do it using Catalog Client Script onChange and fetching attachment data from record via GlideAjax once Reference field changes.

 

Example:

 

Form with two variables:

attachment_from_user (type: Attachment)

user_record (type: reference - with reference to sys_user record)

Robert34_0-1696962353360.png

 

Catalog Client Script onChange

Robert34_1-1696962397422.png

 

Client Callable Script Include

Robert34_2-1696962414649.png

 

Each time user will select User record in reference field, catalog client script will use GlideAjax to fetch data from User record's "photo" field and get the sys_id of the attachment that is hold there and return it back to catalog client script. Once returned, it'll set the same sys_id value to attachment variable

 

Both Attachment Variable and Image field hold sys_id value of the attachment that's being set there so You should be able to simply copy the sys_id

 

Is that helpful? or is there anything more to the requirement that You have?

 

Note: In this scenario, Attachment variable will hold reference to the same attachment that is stored on the User record's field. If You select the user, attachment variable gets filled in and You decide to click Delete on the attachment variable field, it'll Delete the actual Attachment from User record's field. So it'll be better to make attachment variable read only and only editable via script

 

Here are the scripts for easy copy paste:

Catalog Client Script

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    var ga = new GlideAjax('GetImageAndAttach');
	ga.addParam('sysparm_name', 'getRecordFile');
	ga.addParam('sysparm_table', 'sys_user');
	ga.addParam('sysparm_id', newValue);
	ga.addParam('sysparm_field', 'photo');
	ga.getXMLAnswer(process);

    function process(response) {
		g_form.setValue('attachment_from_user', response);
	}

}

 

Script Include

var GetImageAndAttach = Class.create();
GetImageAndAttach.prototype = Object.extendsObject(AbstractAjaxProcessor, {

	getRecordFile: function() {
		var table = this.getParameter('sysparm_table');
		var id = this.getParameter('sysparm_id');
		var imageField = this.getParameter('sysparm_field');

		var image = new GlideRecord(table);
		if(image.get(id)){
			return image.getValue(imageField);
		}
	},

    type: 'GetImageAndAttach'
});