How to PUT (save) object to REST endpoint using Restangular - restangular

Given I have resource id and data as plain JSON, how do I save that JSON to /cars/123/ ???
There seem to be no clear explanation. I don't have restangular element.
restangularizeElement might be the option, but it lacks any meaningful documentation.
All I know is that I want to save {make: 'honda', color: 'now blue, was red'} for car_id == 123.
Thanks.

If you have plain object you cannot use Restangular save function to update (it will make put request as object has id) object.
Easiest way to achieve it construct your end point url then call put function...
Restangular.one('cars', 123).customPUT(carObject).then(function(response){
TO-DO
})
If you want to restangularized your plain object you can use this one...
Restangular.restangularizeElement(null,carObject, 'cars').put().then(function (response) {
TO-DO
})
The comman way should be like this. Whenever you get object from backend with get or getList your object will be Restangularized unless you do not choose to turn them plain object by calling .plain() method of Restangular response. Then you can safely call .save() and it will automatically will be put or post accordingly...

Here is what worked for me. Thanks to #wickY26:
updateGroup: function (group, id_optional) {
if (!group.hasOwnProperty('restangularCollection')) {
// safe to assume it is NOT restangular element; sadly instanceof won't work here
// since there is no element class
// need to restangularize
group = Restangular.restangularizeElement(null, group, ENDPOINT);
group.id = id_optional;
}
return group.put();
},

Related

Get newly created id of a record before redirecting page

I would like to retrieve the id of a newly created record using javascript when I click on save button and just before redirecting page.
Do you have any idea please ?
Thank you !
One way to do this in Sugar 7 would be by overriding the CreateView.
Here an example of a CustomCreateView that outputs the new id in an alert-message after a new Account was successfully created, but before Sugar gets to react to the created record.
custom/modules/Accounts/clients/base/views/create/create.js:
({
extendsFrom: 'CreateView',
// This initialize function override does nothing except log to console,
// so that you can see that your custom view has been loaded.
// You can remove this function entirely. Sugar will default to CreateView's initialize then.
initialize: function(options) {
this._super('initialize', [options]);
console.log('Custom create view initialized.');
},
// saveModel is the function used to save the new record, let's override it.
// Parameters 'success' and 'error' are functions/callbacks.
// (based on clients/base/views/create/create.js)
saveModel: function(success, error) {
// Let's inject our own code into the success callback.
var custom_success = function() {
// Execute our custom code and forward all callback arguments, in case you want to use them.
this.customCodeOnCreate(arguments)
// Execute the original callback (which will show the message and redirect etc.)
success(arguments);
};
// Make sure that the "this" variable will be set to _this_ view when our custom function is called via callback.
custom_success = _.bind(custom_success , this);
// Let's call the original saveModel with our custom callback.
this._super('saveModel', [custom_success, error]);
},
// our custom code
customCodeOnCreate: function() {
console.log('customCodeOnCreate() called with these arguments:', arguments);
// Retrieve the id of the model.
var new_id = this.model.get('id');
// do something with id
if (!_.isEmpty(new_id)) {
alert('new id: ' + new_id);
}
}
})
I tested this with the Accounts module of Sugar 7.7.2.1, but it should be possible to implement this for all other sidecar modules within Sugar.
However, this will not work for modules in backward-compatibility mode (those with #bwc in their URL).
Note: If the module in question already has its own Base<ModuleName>CreateView, you probably should extend from <ModuleName>CreateView (no Base) instead of from the default CreateView.
Be aware that this code has a small chance of breaking during Sugar upgrades, e.g. if the default CreateView code receives changes in the saveModel function definition.
Also, if you want to do some further reading on extending views, there is an SugarCRM dev blog post about this topic: https://developer.sugarcrm.com/2014/05/28/extending-view-javascript-in-sugarcrm-7/
I resolved this by using logic hook (after save), for your information, I am using Sugar 6.5 no matter the version of suitecrm.
Thank you !

OwinContext.Request multi-part/form-data parsing?

Is there an easy way to parse multi-part/form-data information from an OwinContext.Request instance?
I know how to do this using HttpContext.Current.Request.Form.Get(), but I'm not sure if I really want to be doing that in the Owin pipeline.
I know I can use .ReadFormAsync() to get an IFormCollection, which appears to work fine for standard submits, but with a multi-part/form-data post the boundary value, content type, and variable name are all getting rolled into the key. So I can't just do formVars.Get("VariableName"), because it's not the variable name, it's a composite. Seems like it shouldn't be doing that though... right?
public AppFunc PreAuthMiddleware(AppFunc next) {
AppFunc appFunc = async (IDictionary<string, object> environment) => {
IOwinContext context = new OwinContext(environment);
IFormCollection formVars = await context.Request.ReadFormAsync();
... Now What ...
await next.Invoke(environment);
};
return appFunc;
}
I was hoping that accessing form variables and file data would be as easy as it was with HttpContext, but it seems there may be more work to be done.
If anyone has any insight on this, please let me know. Otherwise I'll probably just end up hacking the key names together if I see the main content-type is multi-part/form-data.

How do I use findOrCreateEach in waterline/sailsjs?

I been looking around on the sails site and was lead to the waterline page. I am curious to how I can use the findOrCreateEach method. Specifically, number of arguments, what it will return, and how it will benefit me using it? I been searching, around and going to have to dive into the source code. I figure I ask here while I look.
Method without bluebird promises
Model.findOrCreateEach(/* What Goes Here */).exec(/* What Returns Here */);
With bluebird promises
Model.findOrCreateEach(/* What Goes Here */).then(/* What Returns Here */);
findOrCreateEach is deprecated; that's why it's not in the documentation. The best way to replicate the functionality is by using .findOrCreate() in an asynchronous loop, for example with async.map:
// Example: find or create users with certain names
var names = ["scott", "mike", "cody"];
async.map(names, function(name, cb) {
// If there is a user with the specified name, return it,
// otherwise create one
User.findOrCreate({name: name}, {name: name}).exec(cb);
},
function done(err, users) {
if (err) { <handle error and return> }
<users now contains User instances with the specified names>
});

Getting value with javascript and use it in controller

First of all i am using play framework with scala,
What i have to do is , using the data which i am getting with that function;
onClick: function(node) {
if(!node) return;
alert(node.id);
var id = node.id;
}
So what the question is how i can call the methods from controller with this id ? Since js is client-side but scala works with server-side , i need something creative.
This is the function i need to call from my controller.
def supertrack(id:Long) = Action {
}
I have just found out that i need use ScalaJavaScriptRouting in order to send a ajax request to the server.
For the documentation
http://www.playframework.com/documentation/2.1.1/ScalaJavascriptRouting

CodeIgniter: URIs and Forms

I'm implementing a search box using CodeIgniter, but I'm not sure about how I should pass the search parameters through. I have three parameters: the search string; product category; and the sort order. They're all optional. Currently, I'm sending the parameters through $_POST to a temporary method, which forwards the parameters to the regular URI form. This works fine. I'm using a weird URI format though:
http://site.com/products/search=computer,sort=price,cat=laptop
Does anyone have a better/cleaner format of passing stuff through?
I was thinking of passing it into the products method as arguments, but since the parameters are optional things would get messy. Should I suck it up, and just turn $_GET methods on? Thanks in advance!
Query Strings
You can enable query strings in CodeIgniter to allow a more standard search function.
Config.php
$config['enable_query_strings'] = FALSE;
Once enabled, you can accept the following in your app:
http://site.com/products/search?term=computer&sort=price&cat=laptop
The benefit here is that the user will find it easy to edit the URL to make a quick change to their search, and your search uses common search functionality.
The down side of this approach is that you are going against one of the design decisions of the CodeIgniter development team. However, my personal opinion is that this is OK provided that query strings are not used for the bulk of your content, only for special cases such as search queries.
A much better approach, and the method the CI developers intended, is to add all your search parameters to the URI instead of a query string like so:
http://site.com/products/search/term/computer/sort/price/cat/laptop
You would then parse all the URI segments from the 3rd segment ("term") forward into an array of key => value pairs with the uri_to_assoc($segment) function from the URI Class.
Class Products extends Controller {
...
// From your code I assume you are calling a search method.
function search()
{
// Get search parameters from URI.
// URI Class is initialized by the system automatically.
$data->search_params = $this->uri->uri_to_assoc(3);
...
}
...
}
This would give you easy access to all the search parameters and they could be in any order in the URI, just like a traditional query string.
$data->search_params would now contain an array of your URI segments:
Array
(
[term] => computer
[sort] => price
[cat] => laptop
)
Read more about the URI Class here: http://codeigniter.com/user_guide/libraries/uri.html
If you're using a fixed number of parameters, you can assign a default value to them and send it instead of not sending the parameter at all. For instance
http://site.com/products/search/all/somevalue/all
Next, in the controller you can ignore the parameter if (parameter == 'all'.)
Class Products extends Controller {
...
// From your code I assume that this your structure.
function index ($search = 'all', $sort = 'price', $cat = 'all')
{
if ('all' == $search)
{
// don't use this parameter
}
// or
if ('all' != $cat)
{
// use this parameter
}
...
}
...
}