I am using word javascript Api for developing a word add-in, I need to insert a content control on button click and send a ajax request. In ajax response i need to update the same content control.
I am trying to use following approaches :
1). While inserting the cc in document set tag as 'temporary' and after getting the ajax response, searching CC using 'contentControls.getByTag', but with multiple content control not able to update the correct cc as ajax response could take time so multiple cc will have 'temporary' tag.
2). After inserting the cc in the document, i tried to load the cc 'ID' using:
var range2 = context.document.getSelection().parentContentControlOrNullObject;
context.load(range2);
But it returns undefine.
Please guide me how i can achieve the above requirement. Which is the correct way to do this or can i use the same range object into another word run and update the cc for that range.
this should be really simple to do. When you insert the content control with the API a content control object is returned. This is effectively a handle to that content control. Once loaded you can later do any operations with it including adding modifying the content. Check out this example on how to do this:
function InsertCCandUpdate() {
Word.run(function(context) {
// we first insert a content control, on this case on the selection!
//notice we'll hold a reference to the CC in the myCC var:
var myCC = context.document.getSelection().insertContentControl();
context.load(myCC);
return context.sync()
.then(function(){
// myCC holds a handle to the contentt control.... then we can update its content
myCC.insertText(getSomeContent(),"replace");
})
});
}
function getSomeContent(){
//this method is just to simulate your AJAX call.
return("some text from your AJAX call");
}
I think this will help you in your scenario.
thanks!
Related
I've got a site that accepts file uploads which are sent as multipart/form-data within a POST request. To verify that the upload, which shows the filename afterwards, is secured against XSS I want to upload a file which contains HTML Tags in the filename.
This is actually harder than I expected. I can't create a file containing < on my filesystem (Windows). Also, I don't know a way to change the filename of the file input element inside the DOM before the upload (which is what I would do with normal/hidden inputs). So I thought about editing the POST body before it's uploaded, but I don't know how. Popular extensions (I recall Tamper Data, Tamper Dev) only let me change headers. I guess this is due to the plugin system of Chrome, which is the Browser I use.
So, what's the simplest way of manipulating the POST requests body? I could craft the entire request using cUrl, but I also need state, lots of additional parameters and session data etc. which gets quite complex... A simple way within the Browser would ne nice.
So, while this is not a perfect solution, it is at least a way to recreate and manipulate the form submit using FormData and fetch. It is not as generic as I'd like it to be, but it works in that case. Just use this code in the devtools to submit the form with the altered filename:
let formElement = document.querySelector('#idForm'); // get the form element
let oldForm = new FormData(formElement);
let newForm = new FormData;
// copy the FormData entry by entry
for (var pair of oldForm.entries()) {
console.log(pair[0]+': '+pair[1]);
if(typeof(pair[1]) == 'object' && pair[1].name) {
// alter the filename if it's a file
newForm.append(pair[0],pair[1],'yourNewFilename.txt');
} else {
newForm.append(pair[0],pair[1]);
}
}
// Log the new FormData
for (var pair of newForm.entries()) {
console.log(pair[0]+': ');
console.log(pair[1]);
}
// Submit it
fetch(formElement.action, {
method: formElement.method,
body: newForm
});
I'd still appreciate other approaches.
I am sending through a form object to Google Apps Script with:
var formObject = $("#my_form")[0];
google.script.run.processForm(formObject)
The form includes a file input and I have no problem retrieving this and the other input values on the server with something like:
function processForm(formObject) {
var user_name = formObject.userNameInputName;
}
The documentation is clear that GAS can send through a form providing it is the only parameter:
https://developers.google.com/apps-script/guides/html/reference/run#myFunction(...)
My question is:
How do I access a data attribute value of a form input server side?
And to answer this I need to ask a silly question:
What is a "form object"? What is it's structure, what does it "look like" - is it just a JavaScript object or something else? (if I console.log(formObject) client side it just displays the HTML). If I know this I figure I will know how to access the data attribute value correctly.
Edit:
I ended up just adding a hidden input field to the form and setting the val() of it via an on click event before submitting the form, then I could access the value server side with:
function processForm(formObject) {
var user_name = formObject.userNameInputName;
var was_a_data_attribute = formObject.myHiddenInputField;
}
I'm making a project in pyramid framework, so i have a view which have a form in it with 2 input type texts and a submit button.
The form is a post method, so im getting them with a POST request.
I want to send them to a new view and display them on the screen.
meaning:
on 0.0.0.0:6543 is the form on first view.
I want to display the values the user insert in the input on 0.0.0.0:6543/here
I tried with HTTPfound but i guess im missing an understanding on how to really pass the variables.
Please help me...
The easiest way to accomplish is to use sessions.
You need a session backend which stores your data on a server (see pyramid_redis_session). There are also cookie-based session solutions where all data is stored on the client side.
The first view writes all passed over data to a session:
request.session["mydata"] = value
The second view reads data from the session
print(request.session["mydata"])
Another way to pass the data from one view to another is via the URL. This does not require server-side support, unlike sessions. Also, it's RESTful ;)
return HTTPFound('/here?greeting=Hello&subject=World')
In your second view you then simply get the variables from request.GET:
greeting = request.GET.get('greeting', '')
subject = request.GET.get('subject', '')
# pass the data to the template
return {
"greeting": greeting,
"subject": subject
}
Regarding your comment: You can't use HTTPFound with POST. You can, however, directly submit your form to /here using <form method="post" action="/here" ...>. In this case you'll be able to access the data using request.POST.get('greeting').
We have a number of forms on our site that are shown with jquery .dialog and we submit them using an ajax post request.
I've done a fair bit of research and from what I can tell there isn't any definite patterns on how to return validation errors from the server side as a result of an ajax request.
Pretty much the only pattern I could find was to post the form and then do validation server side and in either case return a json object that encapsulated a result and if the result was incorrect the form html
ie.
{result: true}
{success: false, html = "<form>....</form>"}
So in the case the result was false you would need to rewire up any events attached to items on the form as you would be replacing the old form with the new form that has the validation errors.
This seems like an ok approach but you also end up potentially returning a lot more data to the client that you need to when they only really need to validation messages and you are also forced to rewire the form up which is a bit annoying.
I did find one other mention of somehow getting the validation errors and returning them in a json object from the action and somehow telling the client to display them against the correct fields.
Is there any frameworks out there that make this easier or should I write my own or just stick to returning the entire partial for the form and rewiring it when validation is incorrect?
I don't know of any frameworks that handle this particular case–and I don't know that there's a clear best practice–but it's easy enough to serialize validation errors and return them as a JSON object. You could try this extension method on ModelStateDictionary:
public static IEnumerable<ValidationResult> GetValidationResults(this ModelStateDictionary dictionary)
{
foreach (var key in dictionary.Keys)
foreach (var error in dictionary[key].Errors)
if (error != null)
yield return new ValidationResult(error.ErrorMessage, new string[] { key });
}
And in the controller:
if (!ModelState.IsValid)
{
return new JsonResult(ModelState.GetValidationResults());
}
But you're right, you would then have to loop through the object and append the errors to the correct fields. If you have ClientValidationEnabled and UnobtrusiveJavaScriptEnabled set to true, the loop would look something like this:
$.each(errors, function(i, item) {
$('span[data-valmsg-for=' + item.MemberNames[0] + ']').html(item.ErrorMessage);
})
If not, it wouldn't be that difficult to match up the error messages to their respective fields as the object contains the field name. This would definitely save you some data across the wire, but it moves a larger share of the validation responsibility into Javascript. Like I said, I don't know that there's a clear best practice, but I have used this method in the past with success.
I'm wondering if anyone can assist me in updating the code detailed here (http://oif.eafarris.com/blog/pre-fill-cck-node-fields-based-on-a-node-re...) for Drupal 7. The function described in that post is identical to what I'm looking to do on my Drupal 7 site but I'm not well versed enough programmatically to do it myself.
I have a content type Event. On the node creation form for Event, I have an autocomplete field for "Client". Below that are additional fields for name, address, etc. The end result I'm hoping to achieve here is:
User enters client name in the autocomplete Client field.
Entered client name matches an existing client and is selected.
Using the node ID of the selected client, the address fields are then populated automatically.
I have a JSON view with a nid argument which spits out the required fields at the url http://domain.com/json-clients/[nid]. But I am unable to get that info returned to the correct fields on the form.
Below is the code as I've got it modified trying to get it to work with D7. Anyone see the glaring errors and care to assist?
(function ($) {
Drupal.behaviors.sponsorhelper = function () {
$("input[name='field_client[und][0][nid]']").blur(function() {
nidRegEx = /\[nid:(\d+)\]/;
SponsorHelper.fill($(this).attr('value').match(nidRegEx)[1]);
})
};
SponsorHelper.fill = function(nid) {
var url = Drupal.settings.basePath + 'json-clients/' + nid;
jQuery.getJSON(url, function (data, result) {
if (result != 'success') {
return;
}
$("input[name='field_address_1[und][0][value]']")
.attr('value',data.nodes[0].node.field_address_1_value);
$("input[name='field_address_2[und][0][value]']")
.attr('value',data.nodes[0].node.field_address_2_value);
})
};
})(jQuery);
Any help is greatly appreciated.
Thanks.
Instead of writing your own javascript try handling this with a couple of drupal's community modules. Check out:
http://drupal.org/project/conditional_fields
http://drupal.org/project/computed_field/
You can us conditional fields to hide the address until the client info is put in. Then use computed fields to search for the client and auto fill the address fields.