I have a button on a saved search that runs a suitelet. It all works great except that the button opens a blank suitelet page when pressed.
This page is blank and requires no user interaction.
Is there any way to close it automatically either via another function within the button itself or by a function at the end of the script?
I have tried putting several variations of a window.close function in myself but it never closes.
The link from the search button and the Suitelet which it runs are below. Any help you can offer will be greatly appreciated.
(PS I have noticed that when I click the button on the search it navigates away from the search to a basic item search and I have to press the back button, how do I stop it doing this? Thank you)
Thank you
Button:
'<button onclick="window.open(/app/site/hosting/scriptlet.nl?script=602&deploy=1&compid=*******_SB2&field_id=' || {systemnotes.field} || '&rec_id=' || {internalid} || ');>Approve'
Suitelet:
/**
* #NApiVersion 2.x
* #NScriptType Suitelet
* #NModuleScope SameAccount
*/
define (['N/record'], function (record) {
function onRequest(scriptContext) {
var rec_id=scriptContext.request.parameters.rec_id; //getting parameter
var field_id=scriptContext.request.parameters.field_id; //getting parameter
var itemRecObj= record.load({ type: record.Type.INVENTORY_ITEM, id: rec_id, isDynamic:true });
if (field_id =='custom1'){
itemRecObj.setValue({ fieldId: 'checkbox1', value: true });
}
else if (field_id=='custom2'){
itemRecObj.setValue({ fieldId: 'checkbox2', value: true });
}
else if (field_id=='custom3'){
itemRecObj.setValue({ fieldId: 'checkbox3', value: true });
}
{
itemRecObj.save();
}
function closer(){
window.open('','_self').close()();
}
}
return {
onRequest: onRequest
};
});
You can do something like this in button url after adding url
"window.open(/app/site/hosting/scriptlet.nl?script=5737&deploy=1&compid=&h=&recId=' || {internalid} || ',_blank, toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400);"
/**
* #NApiVersion 2.x
* #NScriptType Suitelet
* #NModuleScope SameAccount
*/
define (['N/record'], function (record) {
function onRequest(scriptContext) {
var rec_id=scriptContext.request.parameters.rec_id; //getting parameter
var field_id=scriptContext.request.parameters.field_id; //getting parameter
var itemRecObj= record.load({ type: record.Type.INVENTORY_ITEM, id: rec_id, isDynamic:true });
if (field_id =='custom1'){
itemRecObj.setValue({ fieldId: 'checkbox1', value: true });
}
else if (field_id=='custom2'){
itemRecObj.setValue({ fieldId: 'checkbox2', value: true });
}
else if (field_id=='custom3'){
itemRecObj.setValue({ fieldId: 'checkbox3', value: true });
}
itemRecObj.save();
scriptContext.response.write("Item Approved");
}
return {
onRequest: onRequest
};
});
It will help. Further Check for window.open in js and you need to use it in saved search not in script.
Related
I would like to run some jQuery code once another jQuery function named loadItems has completed. The loadItems function is from the IAS jQuery plugin https://github.com/webcreate/infinite-ajax-scroll
How can I do this using jQuery
The loadItems function is:
/**
* Loads items from certain url, triggers
* onComplete handler when finished
*
* #param string the url to load
* #param function the callback function
* #param int minimal time the loading should take, defaults to $.ias.default.loaderDelay
* #return void
*/
function loadItems(url, onCompleteHandler, delay)
{
var items = [],
container,
startTime = Date.now(),
diffTime,
self;
delay = delay || opts.loaderDelay;
$.get(url, null, function (data) {
// walk through the items on the next page
// and add them to the items array
container = $(opts.container, data).eq(0);
if (0 === container.length) {
// incase the element is a root element (body > element),
// try to filter it
container = $(data).filter(opts.container).eq(0);
}
if (container) {
container.find(opts.item).each(function () {
items.push(this);
});
}
if (onCompleteHandler) {
self = this;
diffTime = Date.now() - startTime;
if (diffTime < delay) {
setTimeout(function () {
onCompleteHandler.call(self, data, items);
}, delay - diffTime);
} else {
onCompleteHandler.call(self, data, items);
}
}
}, 'html');
}
And it is being called in the HTML with:
<script type="text/javascript">
jQuery.ias({
container : '.category-products',
item: '.products-grid',
pagination: '.toolbar-bottom',
next: '.next',
loader: '<img src="http://example.com/skin/frontend/bootstrapped/default/images/ajax-loader.gif" /> Loading more products, please be patient...',
onPageChange: function(pageNum, pageUrl, scrollOffset) {
// This will track a pageview every time the user scrolls up or down the screen to a different page.
path = jQuery('<a/>').attr('href',pageUrl)[0].pathname.replace(/^[^\/]/,'/');
_gaq.push(['_trackPageview', path]);
},
triggerPageTreshold: 100,
thresholdMargin: 700,
trigger: 'Load more items',
history: true,
onLoadItems: function(items) {
jQuery.each(items, function(i, ul){
jQuery(ul).find('select.qtychange').customSelect()
});
}
});
jQuery(document).ready(function() {
jQuery().UItoTop({ easingType: 'easeOutQuart' });
});
</script>
The function already provides callback functionality; simply provide an anonymous function in the onCompleteHandler parameter when you call the loadItems function. Something like this:
loadItems('/foo.php', function(data, items) {
console.log('loading complete');
console.log(data);
console.log(items);
});
Got it working in the end by adding an onRenderComplete to the plugins options as below.
<script type="text/javascript">
jQuery.ias({
container : '.category-products',
item: '.products-grid',
pagination: '.toolbar-bottom',
next: '.next',
loader: '<img src="http://example.com/skin/frontend/default/default/images/ajax-loader.gif" /> Loading more products, please be patient...',
onPageChange: function(pageNum, pageUrl, scrollOffset) {
// This will track a pageview every time the user scrolls up or down the screen to a different page.
path = jQuery('<a/>').attr('href',pageUrl)[0].pathname.replace(/^[^\/]/,'/');
_gaq.push(['_trackPageview', path]);
},
triggerPageTreshold: 100,
thresholdMargin: 700,
trigger: 'Load more items',
history: true,
onLoadItems: function(items) {
jQuery.each(items, function(i, ul){
jQuery(ul).find('select.qtychange').customSelect()
});
},
onRenderComplete: function () {
console.log('it worked');
// added my code here
}
});
</script>
Strangely it is not mentioned in the plugins docs but I saw in the code and just gave it a shot.
Working with a modal form that submits edited information via ajax post. The thing is, it submitted once the first time .. fire up the modal form again, then submit, and twice it goes and so on and so forth. Does anyone had this sort of experience before? Please help.
$("#editInfo").click(function () {
valform = ["realname","email"];
valneed = 2;
$('#smallModal .modal-body').empty();
$('#smallModal .modal-body').load('/profile.php?action=profile_edit_info');
$('#smallModal .modal-title').text('Edit Personal Information');
$('#smallModal').modal('show')
$('#smallModal').on('shown.bs.modal', function () {
$("#smallModal #profileeditinfoform").keydown(function(event){
if(event.keyCode == 13 && event.target.nodeName!='TEXTAREA')
{
event.preventDefault();
return false;
}
});
$("#realname_comment").hide();
$("#email_comment").hide();
$('#realname').bind("change", function() {
$('#realname').addClass("spinner");
var v_realname = verifyVar($('#realname').val(),'name');
displayVerify(v_realname,'realname');
});
$('#email').bind("change", function() {
$('#email').addClass("spinner");
var v_email = verifyVar($('#email').val(),'email');
displayVerify(v_email,'email');
});
$("#editinfo_submit_btn").click(function(event) {
event.preventDefault();
$('#loader').fadeIn();
formData = $("#profileeditinfoform").serialize();
var v_submit = submitEditInfo(formData);
verifySubmitEditInfo(v_submit);
$('#loader').fadeOut();
});
});
});
function submitEditInfo(data) {
var alldata = data + '&action=profileeditinfo';
return $.ajax({
type: 'POST',
cache: false,
data: alldata,
url: '/ajax/submit.php'
});
}
function verifySubmitEditInfo(ajaxCall) {
ajaxCall.success(function(realData) {
response = JSON.parse(realData)
if (!response.success) {
$.gritter.add({
title: response.title,
image: '/img/custom/fail.png',
sticky: false,
text: response.message
});
} else {
valform = [];
$("#submitdiv").hide();
$("#profileeditinfoform").find("input:text").val('');
$('#infodiv').slideUp(200).load('/divloader.php?req=profile_info').slideDown(200);
$.gritter.add({
title: response.title,
image: '/img/custom/success.png',
sticky: false,
text: response.message
});
$("#smallModal").modal('hide');
}
});
}
Every time you click, you're adding a new event handler:
$('#smallModal').on('shown.bs.modal' //...
Are you sure you want to do this on "click", or might it be better to set this up outside of the click handler?
In fact, you're binding event handlers as a response to other events all over this code. That's probably not a great idea, unless you unbind them once you're done.
You need to pull out your binders, you bind a new time every time the button is clicked! Only bind on load, not under button click event.
I'm trying to initialize my ember text field view to prefill it with the query string. But whenever i add an init function to my view all other defined events stop triggering.
How do i get my events to keep working while using initialization ?
App.SearchBarView = Ember.TextField.extend({
throttle_instance: _.debounce(function(){
var value = this.get('value');
this.update();
}, 1000),
/**
* Initialize the textbox with a set value
*/
init: function(){
var query = "testquery";
if(query && query.length > 0){
this.set('value', query[0]);
this.get('controller').set('query', query[0]);
this.update();
}
},
insertNewline: function() {
this.update();
},
/**
* Handle the keyup event and throttle the amount of requests
* (send after 1 second of not typing)
*/
keyUp: function(evt) {
this.get('controller').set('query', this.get('value'));
this.throttle_instance();
},
/**
* Update the pages results with the query
*/
update: function(){
var value = this.get('value');
this.get('controller').filterByQuery(value);
}
});
You need to call this._super() inside your init method to maintain the view's default behaviour:
...
init: function() {
this._super();
}
...
Hope it helps.
I made a method for my UI class that clears inputs in a containing div.
The problem is, once it is called, The checkboxes never get set through AJAX calls until you refresh the page. The example below is for my group/user management. If you click on a group to edit, a jQuery UI dialog pops up with the attributes and permissions of that group. If you cancel, and try to add a new one, the inputs are cleared. If you then goto edit a group after that, the inputs are not updated.
Edit: It seems the checkboxes stop working if the cancel button is clicked regardless if my clearInputs method is called or not.
Here is the method of the UI class:
clearInputs: function(container) {
$(container + " :input").val("");
$(container).find('input[type=checkbox]:checked').prop('checked', false);
}
And an example of the calling code (copied from my project, but I cut some of the fat out...
/* The user clicks the edit group button... */
$(document).delegate('.group_edit', 'click', function() {
var groupId = $(this).attr('id').replace("group_edit_", "");
// This call to the clearInputs method is commented out,
// and behaves as I described above.
// ui.clearInputs("#dialogGroup");
$.ajax({
type: "POST",
url: "ajax.users.php",
data: {
action: "get_privs",
group: groupId
},
success: function (result) {
if (result.success == true) {
// Set the name value
$("#name").val(result.GroupName);
// Update each of the checkboxes
$.each(result.privs, function(priv, grant) {
grant = Boolean(parseInt(grant));
$('#dialogGroup input[value=' + priv + ']').prop('checked', grant);
});
/* Create the dialog */
$("#dialogGroup").dialog({
buttons: {
"OK" : function () {
$(this).dialog("close");
var form_data = new Array();
$.each($("input[#name='cbox[]']:checked"), function() {
form_data.push($(this).val());
});
$.ajax({
/* Saves the form data */
});
},
"Cancel": function() {
ui.clearInputs("#dialogGroup");
$(this).dialog("close");
}
}
});
And finally to add a group:
$(document).delegate('#group_add', 'click', function() {
var dialog = "#dialogGroup";
// ui.clearInputs(dialog);
$(dialog).dialog({
modal: true,
title: "Create Group",
buttons: {
"OK": function() {
$(this).dialog("close");
$("#dialogNotify").html("Saving...");
$("#dialogNotify").dialog('open');
var form_data = new Array();
$.each($("input[#name='cbox[]']:checked"), function() {
form_data.push($(this).val());
});
$.ajax({
/* Save the form data */
});
},
Cancel: function() {
$(this).dialog("close");
}
}
});
});
I hope I included everything... If not I will update.
try this:
$( document ).ready(function()
{
var search_on = $('#formX');
$( search_on )
//CHANGE "input" for "input,select" to search all fields
.find('input')
.each(function( e )
{
if( $(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox' )
{
$(this).attr('checked',false);
//USE RESET() IF IS A FORM FIELD
$(this).reset();
}
//IF IS A DROPDOWN
/*
else if( $(this).attr('type') == undefined )
{
$(this).find('option').attr('selected',false);
}
*/
else
{
$(this).val('');
//USE RESET() IF IS A FORM FIELD
//$(this).reset();
}
});
});
Or use this function( if is a form ):
jQuery.fn.reset = function () {
$(this).each (function() { this.reset(); });
}
And Call
$('#formX').reset();
I figured it out. The problem was inside of my method, I had:
clearInputs: function(container) {
$(container + " :input").val("");
$(container).find('input[type=checkbox]:checked').prop('checked', false);
}
The first line of the method, I guess is doing something to all inputs.
If you change the first line to
$(container + " :input[type=text]").val("");
It works fine...
I've added a custom button to TinyMCE which brings up a bespoke link-picker. When the user selects some text and clicks the button the dialog appears and when they've picked the url I'm using execCommand('insertHTML', false, "<a href... etc">) on the selection.
This works fine - now, when the link has already been created, and the user wants to edit it, they click the link button again (when the cursor is inside the linked text as normal), but then here is the situation - I don't know how to access the already created link and it's attributes to then load up and populate the dialogue again!
Have search TinyMCE site, Stack, Google in general. Hoping for (and also slightly dreading) a simple answer - but if not, a complex one will be fine!!
If anybody knows the answer or can point me to it, I'd be extremely grateful. Thanks in advance,
Rob
EDIT - bits of my code to explain need
In the TinyMCE init:
setup: function (ed) {
ed.addButton("link", {
title: "Link",
onclick: function (evt) {
Intranet.TextEditor._loadUrlDialog(jQueryTextAreaObject, evt);
}
});
}
The function which is called above:
_loadUrlDialog: function (jQueryTextAreaObject, clickEvent) {
var mce = $(jQueryTextAreaObject).tinymce();
var isSelected = mce.selection.getContent().length != 0 ? true : false;
if (isSelected) {
Intranet.UrlDialog.Fn.LoadDialog("", true, "", function (url, target, title) {
var theTarget = target == false ? "_self" : "_blank";
var link = "" + mce.selection.getContent() + "";
mce.execCommand('insertHTML', false, link); // creates new link
});
}
else {
/// THIS IS THE MISSING BIT!
};
}
You have two ways of achieving this:
When pushing the button you check for the selection parent node. If the node is a link then you can get the link information from the html a-element. To populate your dialogue you will know what to do.
The other option is to add a contextmenu on rightclick, which will provide the necessary functionalities.
Here is the plugin code for this (keep in mind that you will have to add "customcontextmenu" to the plugin-setting of your tinymce).
/**
* editor_plugin_src.js
*
* Plugin for contextmenus.
*/
(function() {
var Event = tinymce.dom.Event, each = tinymce.each, DOM = tinymce.DOM;
tinymce.PluginManager.requireLangPack('customcontextmenu');
/**
* This plugin a context menu to TinyMCE editor instances.
*
* #class tinymce.plugins.customcontextmenu
*/
tinymce.create('tinymce.plugins.customcontextmenu', {
/**
* Initializes the plugin, this will be executed after the plugin has been created.
* This call is done before the editor instance has finished it's initialization so use the onInit event
* of the editor instance to intercept that event.
*
* #method init
* #param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
* #param {string} url Absolute URL to where the plugin is located.
*/
init : function(ed) {
var t = this, lastRng;
t.editor = ed;
// Registiere commands
ed.addCommand('edit_inline_element', function() {
//edit_inline_element(ed, ed.right_clicked_node); //ed.right_clicked_node is the actually clicked node
//call or do whatever you need here
});
// delete link
ed.addCommand('delete_inline_element', function() {
$(ed.right_clicked_node).replaceWith($(ed.right_clicked_node).html());
});
// assign the right clicked node (it is the evt.target)
ed.onClick.add(function(ed, evt) {
if (evt.button == 2) ed.right_clicked_node = evt.target;
});
/**
* This event gets fired when the context menu is shown.
*
* #event onContextMenu
* #param {tinymce.plugins.ContextMenu} sender Plugin instance sending the event.
* #param {tinymce.ui.DropMenu} menu Drop down menu to fill with more items if needed.
*/
t.onContextMenu = new tinymce.util.Dispatcher(this);
ed.onContextMenu.add(function(ed, e) {
if (!e.ctrlKey) {
// Restore the last selection since it was removed
if (lastRng)
ed.selection.setRng(lastRng);
var menu = t._getMenu(ed);
if ((typeof menu).toLowerCase() == 'object')
{
menu.showMenu(e.clientX, e.clientY);
Event.add(ed.getDoc(), 'click', function(e) {
hide(ed, e);
});
Event.cancel(e);
}
// sonst Standardmenu anzeigen
}
});
ed.onRemove.add(function() {
if (t._menu)
t._menu.removeAll();
});
function hide(ed, e) {
lastRng = null;
// Since the contextmenu event moves
// the selection we need to store it away
if (e && e.button == 2) {
lastRng = ed.selection.getRng();
return;
}
if (t._menu) {
t._menu.removeAll();
t._menu.destroy();
Event.remove(ed.getDoc(), 'click', hide);
}
};
ed.onMouseDown.add(hide);
ed.onKeyDown.add(hide);
},
_getMenu: function(ed){
var t = this, m = t._menu, se = ed.selection, col = se.isCollapsed(), el = se.getNode() || ed.getBody(), am, p1, p2;
if (m) {
m.removeAll();
m.destroy();
}
p1 = DOM.getPos(ed.getContentAreaContainer());
p2 = DOM.getPos(ed.getContainer());
m = ed.controlManager.createDropMenu('contextmenu', {
offset_x : p1.x + ed.getParam('contextmenu_offset_x', 0),
offset_y : p1.y + ed.getParam('contextmenu_offset_y', 0),
constrain : 1
});
t._menu = m;
if ((typeof ed.right_clicked_node) !== "undefined" && ed.right_clicked_node.nodeName.toLowerCase() == 'a' )
{
m.add({
title: $(ed.right_clicked_node).attr('title'),
});
m.addSeparator();
m.add({
title: 'Edit link',
icon: 'edit_inline_element',
cmd: 'edit_link'
});
m.add({
title: 'Delete link',
icon: 'delete_inline_element',
cmd: 'delete_link'
});
t.onContextMenu.dispatch(t, m, el, col);
return m;
}
else {
// kein Menu anzeigen
return 0;
}
}
});
// Register plugin
tinymce.PluginManager.add('customcontextmenu', tinymce.plugins.customcontextmenu);
})();