Difference between revisions of "Upload images in questionnaire"

From Catglobe Wiki
Jump to: navigation, search
(Update for new viewer)
(Tag: visualeditor)
(Update for new viewer)
(Tag: visualeditor)
Line 305: Line 305:
  
 
<source lang="javascript" line="1">
 
<source lang="javascript" line="1">
/*-------------------------------------------------------------------------
+
Question.bind('afterShowQuestion', function(question, answerSheet, element) {
Set initial information for the uploading image
+
  $('.cg-ui-input').hide();
-------------------------------------------------------------------------*/
+
var folderid = '{{D_Current_Folder_Id}}';
quest.onInit = function()
+
var dlg; 
{
+
  $.getScript("../../Script/ServerMethods/ServerMethods.js", function(){
quest.ImageList = new ImageList($("#attachmentContainer").get(0), "800px","400px" );
+
  $.getScript("../../Script/XmlParser/xmlp.js", function(){
quest.ImageList.setFolderId('{{D_Current_Folder_Id}}');
+
    ServerMethods.registerMethod(new Method(TYPE_ARRAY,'GetImageInfo',false,null,'~/Common/Resources/View/ImagesTab.ascx',new Parameter(TYPE_INT, 'imagepk')));
        $("#attachmentContainer").append($("<input name='QUESTION.D_Image_Guid' type='hidden'>"));
+
    openImagedialog();
 +
  });
 +
  });//END getScript LV1
 +
//SUB FUNCTION
 +
  function openImagedialog() {
 +
    window.getActiveDialog = function(body) {
 +
      var strBody = $(body).prop('outerHTML');
 +
      var imageId = parseInt(strBody.substring(strBody.lastIndexOf("addList(")+8,strBody.lastIndexOf(",'Add')")));
 +
      //console.log(imageId);
 +
      Question.attr('answer', imageId);
 +
      //console.log(Question);
 +
      $(parent.document).find('.ui-widget-overlay').remove();
 +
      $(parent.document).find('.ui-dialog').remove();
 +
      $('#comUp').text('An Image has just been uploaded. Please click "Next" button to continue');
 +
   
 +
      return {papa: {}};
 +
    };
 +
var virtualAppHost = window.location.origin;
 +
    var url = virtualAppHost + "/Common/ResourceExplorer/EditImagePage.aspx?afn=Images/Resources&parenttype=6" +
 +
"&parentid=" + folderid;
 +
var $dialog = $('<div></div>')
 +
              .html('<iframe style="border: 0px; " src="' + url + '" width="100%" height="100%"></iframe>')
 +
              .dialog({
 +
                  autoOpen: false,
 +
                  modal: true,
 +
                  height: 190,
 +
                  width: 463,
 +
                title: "Add new image"
 +
              });
 +
$dialog.dialog('open');  
 
}
 
}
 
+
 
/*-------------------------------------------------------------------------
+
});
- Validate the question. Automaticaly called.
 
- You must upload at least 1 image
 
-------------------------------------------------------------------------*/
 
function questioncheck()
 
{
 
  // Subscription form valid variable
 
var valid = true;
 
    ErrorMessages.getInstance().clearErrorMessages();
 
var list = quest.ImageList.getImages();
 
if (list.length < 1)
 
{
 
ErrorMessages.getInstance().showErrorMessage('You must upload at least 1 image.');
 
valid = false;
 
}
 
  // Return result of validation
 
    var getGuid = quest.ImageList.getGUIDs();
 
  $("input[name$='QUESTION.D_Image_Guid']").val(getGuid);
 
  return valid;
 
}
 
 
 
/*---------------------------------------------------------------------------------------------------------------
 
End JAVA_SCRIPT of QUESTION Insert_Image
 
---------------------------------------------------------------------------------------------------------------*/
 
 
 
 
</source>
 
</source>
 
== Source ==
 
== Source ==
 
Questionnaire Resource Id on cg.catglobe.com site: 75216
 
Questionnaire Resource Id on cg.catglobe.com site: 75216

Revision as of 13:10, 5 April 2019

Introduction

We have a client who wants respondents to be able to upload images in a questionnaire

Solution

When the recipient open the answer sheet to answer, we will create the new folder whose name is recipient's name under the questionnaire then store the images that the he uploads in the image tab of this new created folder.

How to do it

Requirement

  • The user template of the recipients must have the navigation access to open the Image tab of the Folder and upload the images in this image tab.

Step 1: Preparation

  • In the group list, create the group containing the recipients and grant the needed navigation accesses to this group
  • In the folder list, create the folder containing all the recipient's folder.
  • Check the folder template resource id that the folder will use.

Step 2: Create the new folder for the recipient

(You can see the script in the workflow whose resource id is 45408 in cg.catglobe.com)

 1 array para = Workflow_getParameters();
 2 number userId = para[0];
 3 
 4 number ImageFolderResourceId = 45406;
 5 number FolderTemplateResourceId = 2071;
 6 
 7 array newFolder ;
 8 number userResourceId = User_getResourceIdFromUserId(userId);
 9 array userinfo = User_getUserByResourceId(userResourceId);
10 string ExistedFolderName = getNameFromResourceUniqueId(ImageFolderResourceId) + "\\"+ userinfo[USER_NAME];
11 array ExistedFolder = Folder_getFolderByName(ExistedFolderName);
12 
13 if (ExistedFolder == empty) 
14 {
15 newFolder = Folder_new(userinfo[USER_NAME],FolderTemplateResourceId ,ImageFolderResourceId); 
16 Folder_save(newFolder);
17 }
18 else 
19 {
20 newFolder = ExistedFolder ;
21 }
22 array permissions = {{userId , "FullControl"}};
23 updateUserPermission(newFolder[FOLDER_RESOURCE_ID], permissions);
24 string guid = getResourceGuid(newFolder[FOLDER_RESOURCE_ID]);
25 return getResourceIdFromGuid(guid);


Step 3: Set up the questionnaire

(You can see the questionnaire whose resource id is 1219174 in cg.catglobe.com)

Step 3.1 : Create the dummy question for storing the folder id

We will call the workflow in step 2 to get the new created folder id of recipient

Step 3.2 : Add the following script to the questionnaire

Paste this code below into Javascript tab of the questionnaire

  1 /*---------------------------------------------------------------------------------------------------------------
  2 	Server info
  3 ---------------------------------------------------------------------------------------------------------------*/
  4 var ServerInfo =
  5 {
  6    "rootPath" : window.location.protocol+"//"+window.location.host
  7 }
  8 
  9 
 10 /*---------------------------------------------------------------------------------------------------------------
 11 	ResourceType enumeration
 12 ---------------------------------------------------------------------------------------------------------------*/
 13 var ResourceType =
 14 {
 15    "Folder":"Folder"
 16 };
 17 
 18 
 19 //
 20 // IFrame
 21 //
 22 function IFrame(parentElement)  
 23 {  
 24    // Create the iframe which will be returned  
 25    var iframe = document.createElement("iframe");  
 26   
 27    // If no parent element is specified then use body as the parent element  
 28    if(parentElement == null)  
 29       parentElement = document.body;  
 30   
 31    // This is necessary in order to initialize the document inside the iframe  
 32    parentElement.appendChild(iframe);  
 33 
 34    // Get the document object of the IFrame
 35    iframe.getDocument = function()
 36    {
 37       // Depending on browser platform get the iframe's document, this is only  
 38       // available if the iframe has already been appended to an element which  
 39       // has been added to the document  
 40 
 41       var doc;
 42 
 43       if(this.contentDocument)  
 44          // Firefox, Opera  
 45          doc = this.contentDocument;  
 46       else if(this.contentWindow)  
 47          // Internet Explorer  
 48          doc = this.contentWindow.document;  
 49       else if(this.document)  
 50          // Others?  
 51          doc = this.document;
 52 
 53       // If we did not succeed in finding the document then throw an exception  
 54       if(doc == null)  
 55          throw "Document not found, append the parent element to the DOM before creating the IFrame";
 56 
 57       return doc;
 58    }
 59 
 60    // Set iframe source
 61    iframe.setSource = function(src)
 62    {
 63       // Set the source
 64       this.src = src;
 65 
 66       // Initialize the iframe's document
 67       this.doc = this.getDocument();
 68  
 69       // Open and close the iframe's document, this will allow us to manipulate
 70       // the iframe's contents by script
 71       iframe.doc.open();  
 72       iframe.doc.close();  
 73    }
 74   // Set iframe source
 75    iframe.setWidth = function(width)
 76    {
 77       // Set the width
 78       this.width = width;
 79    }	
 80   // Set iframe source
 81    iframe.setHeight = function(height)
 82    {
 83       // Set the height
 84       this.height = height;
 85    }
 86 
 87    // Initiate the iframe's document property
 88    iframe.doc = iframe.getDocument();
 89   
 90    // Open and close the iframe's document, this will allow us to manipulate
 91    // the iframe's contents by script
 92    iframe.doc.open();  
 93    iframe.doc.close();  
 94   
 95    // Return the iframe, now with an extra property iframe.doc containing the  
 96    // iframe's document  
 97    return iframe;  
 98 }
 99 
100 /*---------------------------------------------------------------------------------------------------------------
101 	AttachmentList question control
102 ---------------------------------------------------------------------------------------------------------------*/
103 
104 function ImageList(elementContainer, width,height,viewimage)
105 {
106    this._elementContainer = elementContainer;
107 this._iframe = new IFrame(this._elementContainer);
108 $(this._iframe)
109 .attr("id", "ImageListIFrame")
110 .bind("load",
111 	function()
112 	{
113 		if(this.src == '')
114 			return;
115 if (viewimage == "off")
116 {
117 $('#ImageListIFrame').contents().find('#ImagesximageGrid_main').hide();
118 $('#ImageListIFrame').contents().find('#Imagesxtoolbar_Item_1').hide();
119 $('#ImageListIFrame').contents().find('#Imagesxtoolbar_Item_2').hide();
120 $('#ImageListIFrame').contents().find('#Imagesxtoolbar_Item_3').hide();
121 
122 }
123 else
124 {
125 $('#ImageListIFrame').contents().find('#Imagesxtoolbar').hide();
126 $('#ImageListIFrame').contents().find('#ImagesximageGrid_c_0_2').hide();
127 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_0_2').hide();
128 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_1_2').hide();
129 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_2_2').hide();
130 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_3_2').hide();
131 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_4_2').hide();
132 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_5_2').hide();
133 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_6_2').hide();
134 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_7_2').hide();
135 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_8_2').hide();
136 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_9_2').hide();
137 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_10_2').hide();
138 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_11_2').hide();
139 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_12_2').hide();
140 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_13_2').hide();
141 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_14_2').hide();
142 $('#ImageListIFrame').contents().find('#ImagesximageGrid_rc_15_2').hide();
143 }
144 	});
145 if (width != null)
146    this._iframe.setWidth(width);
147 if (height != null)
148    this._iframe.setHeight(height);
149 }
150 
151 //ImageList.path = "{rootPath}/Common/Resources/View/ContainerPage.aspx?tabtype=Images&type={type}&id={id}&isportal=false";
152 ImageList.path = "{rootPath}/Common/Resources/View/ContainerPage.aspx?tabtype=Images&type={type}&id={id}&isportal=false";
153 
154 ImageList.prototype =
155 {
156    
157    createImageListUrl: function(type, id)
158    {
159       return ImageList.path
160          .replace("{rootPath}", ServerInfo.rootPath)
161          .replace("{type}", type)
162          .replace("{id}", id);
163    },
164    
165    setFolderId: function(FolderId)
166    {
167        $(this._iframe)
168          .attr("src", this.createImageListUrl(ResourceType.Folder, FolderId));
169    },
170 
171    getImages: function()
172    {
173       var Name = 1;
174       var nameList = new Array();
175 
176       with(this._iframe.contentWindow)
177       {
178 
179 
180          
181          var grid = getCGExecuter().getGridUtilities().getGrid(__gridClientId);
182 
183          for (var rowIndex = 0; rowIndex <grid.Rows.length; rowIndex ++)
184          {
185             
186             nameList.push(grid.Rows.rows[rowIndex].getCell(Name).getValue());
187 
188          }
189       }
190 
191       return nameList;
192    },
193   /* getGUIDs: function()
194    {
195       var Name = 2;
196       var nameList = new Array();
197       
198       with(this._iframe.contentWindow)
199       {
200 
201 
202          var grid = getCGExecuter().getGridUtilities().getGrid(__gridClientId);
203          var guidtext;
204          for (var rowIndex = 0; rowIndex <grid.Rows.length; rowIndex ++)
205          {
206            guid = grid.Rows.rows[rowIndex].getCell(Name).getValue();
207             nameList.push(jQuery.trim(guid.split('<a')[0]));
208 
209          }
210       }
211 
212       return nameList;
213    }
214 */
215    getGUIDs: function()
216    {
217       var Name = 2;
218       var nameList = new Array();
219        with(this._iframe.contentWindow)
220       {
221 
222       guid = '{{D_GUID}}';
223       alert("nham"+guid);
224       nameList.push(jQuery.trim(guid.split('<a')[0]));
225       }
226       return nameList;
227 }
228 }
229 /*---------------------------------------------------------------------------------------------------------------
230 	End JAVA_SCRIPT of QUESTIONNAIRE
231 ---------------------------------------------------------------------------------------------------------------*/

Step 3.3 : Create the question for showing the upload form

Paste this code below into Javascript tab of that question

 1 Question.bind('afterShowQuestion', function(question, answerSheet, element) {
 2   $('.cg-ui-input').hide();
 3 var folderid = '{{D_Current_Folder_Id}}';
 4 var dlg;  
 5    $.getScript("../../Script/ServerMethods/ServerMethods.js", function(){
 6    		$.getScript("../../Script/XmlParser/xmlp.js", function(){
 7     		ServerMethods.registerMethod(new Method(TYPE_ARRAY,'GetImageInfo',false,null,'~/Common/Resources/View/ImagesTab.ascx',new Parameter(TYPE_INT, 'imagepk')));
 8     		openImagedialog();
 9   		});
10    });//END getScript LV1
11 //SUB FUNCTION
12   function openImagedialog() {
13     window.getActiveDialog = function(body) {
14       var strBody = $(body).prop('outerHTML');
15       var imageId = parseInt(strBody.substring(strBody.lastIndexOf("addList(")+8,strBody.lastIndexOf(",'Add')")));
16       //console.log(imageId);
17       Question.attr('answer', imageId);
18       //console.log(Question);
19       $(parent.document).find('.ui-widget-overlay').remove();
20       $(parent.document).find('.ui-dialog').remove();
21       $('#comUp').text('An Image has just been uploaded. Please click "Next" button to continue');
22      
23       return {papa: {}};
24     };
25 	var virtualAppHost = window.location.origin;
26     var url = virtualAppHost + "/Common/ResourceExplorer/EditImagePage.aspx?afn=Images/Resources&parenttype=6" +
27 		"&parentid=" + folderid;
28 	var $dialog = $('<div></div>')
29                .html('<iframe style="border: 0px; " src="' + url + '" width="100%" height="100%"></iframe>')
30                .dialog({
31                    	autoOpen: false,
32                    	modal: true,
33                    	height: 190,
34                    	width: 463,
35                  	title: "Add new image"
36                });
37 	$dialog.dialog('open'); 
38 }
39   
40  });

Source

Questionnaire Resource Id on cg.catglobe.com site: 75216