Clickable form with editable fields with ng-click - edit

I am building an address book where users can edit fields as they click on them. I found this fiddle via a thread:
http://jsfiddle.net/timriley/GVCP2/
But it does not explain how to do with with a JSON style data source. As a beginner in Angularjs I am struggling to find a way to bind the editable forms to the data model so my attempt is pretty poor:
function ClickToEditCtrl($scope) {
$scope.contacts = [
{
"id": 1,
"Name": "Betty",
"Surname": "Smith",
"Address": "24 Funny Avenue, wc149m, London, United Kingdom"
},
{
"id": 2,
"Name": "Anabella",
"Surname": "Vicks",
"Address": "19 Euston Road n12clm, London, Isle of Man"
}];
$scope.editorEnabled = false;
$scope.enableEditor = function() {
$scope.editorEnabled = true;
$scope.editableAddress = $scope.contacts.Address;
};
$scope.disableEditor = function() {
$scope.editorEnabled = false;
};
$scope.save = function() {
$scope.contacts = $scope.editableAddress;
$scope.disableEditor();
};
}
http://jsfiddle.net/
How do I make all fields editable and updatable in the JSON array?

Forget the messy question above. I found this brilliant AngularJS Bundle I wish I knew about 2 days ago: http://vitalets.github.io/angular-xeditable/.
FIXED

Related

The response to 'getList' must be like { data : [...] } , but the received data is not an array. React admin error

The response to 'getList' must be like { data : [...] }, but the received data is not an array. The dataProvider is probably wrong for 'getList'
Response
{
"data": [
{
"id": 6,
"product_title": "Foam chair",
"product_description": "Fantastic Foam chair",
},
{
"id": 5,
"product_title": "Shinez cleaning liquid",
"product_description": "Shinez cleaning liquid shoes is good for electronics",
},
{
"id": 4,
"product_title": "Shinez cleaning liquid buy 1 get 1 free",
"product_description": "Shinez cleaning liquid shoes is a good for electronics and computers",
},
{
"id": 3,
"product_title": "Raj kiran Motor cycle",
"product_description": "Raj kiran Motor cycle old one",
},
{
"id": 2,
"product_title": "Ka ka cycle broken cycle",
"product_description": "Ka ka cycle broken into multiple pieces",
},
{
"id": 1,
"product_title": "ka ka police cap",
"product_description": "This is police cap used by ka team",
}
]
}
But still I get the
The response to 'getList' must be like { data : [...] }, but the received data is not an array. The dataProvider is probably wrong for 'getList'
here is the actual code
<BrowserRouter>
<Admin catchAll={NotFound}
dataProvider={dataProvider}
authProvider={authProvider}
loginPage={myLoginPage} >
</Admin>
</BrowserRouter>
I am using django rest framework as backend and using 'ra-data-django-rest-framework'
Need help on this. Thanks a lot.
Had a look at the following questions
React-Admin "Get List" DataProvider
The response to 'GET_LIST' must be like { data : [...] }, but the received data is not an array
const fetchJson = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
// Not working even if add content-range
// Content-Range: posts 0-24/319,
//adding console.log , returns undefined here
console.log( fetchUtils.fetchJson );
return fetchUtils.fetchJson(url, options);
}
const dataProvider = drfProvider('http://127.0.0.1:8000/api', fetchJson);
Imp. info: I am receiving the response on request.
adding console.log , returns undefined.
The solution , it expects the response in this format
{
"count": 10,
"next": "http://127.0.0.1:8000/api/products/?page=2",
"previous": null,
"results": [
{
"id": 10,
"product_title": "Crompton pedastal fan",
"product_description": "Nice Crompton pedastal fan",
},
{
"id": 10,
"product_title": "Crompton pedastal fan",
"product_description": "Nice Crompton pedastal fan",
}
]
}
Digging deep opens up that, it works seamlessly with class-based views like generics view, I was using function-based view in Django. Now I changed to class based view, everything is working cool.
class ProductList (generics.ListCreateAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer

GraphQL query - Query by ID

I have installed the strapi-starter-blog locally and I'm trying to understand how I can query article by ID (or slug). When I open the GraphQL Playground, I can get all the article using:
query Articles {
articles {
id
title
content
image {
url
}
category {
name
}
}
}
The response is:
{
"data": {
"articles": [
{
"id": "1",
"title": "Thanks for giving this Starter a try!",
"content": "\n# Thanks\n\nWe hope that this starter will make you want to discover Strapi in more details.\n\n## Features\n\n- 2 Content types: Article, Category\n- Permissions set to 'true' for article and category\n- 2 Created Articles\n- 3 Created categories\n- Responsive design using UIkit\n\n## Pages\n\n- \"/\" display every articles\n- \"/article/:id\" display one article\n- \"/category/:id\" display articles depending on the category",
"image": {
"url": "/uploads/blog_header_network_7858ad4701.jpg"
},
"category": {
"name": "news"
}
},
{
"id": "2",
"title": "Enjoy!",
"content": "Have fun!",
"image": {
"url": "/uploads/blog_header_balloon_32675098cf.jpg"
},
"category": {
"name": "trends"
}
}
]
}
}
But when I try to get the article using the ID with variable, like here github code in the GraphQL Playground with the following
Query:
query Articles($id: ID!) {
articles(id: $id) {
id
title
content
image {
url
}
category {
name
}
}
}
Variables:
{
"id": 1
}
I get an error:
...
"message": "Unknown argument \"id\" on field \"articles\" of type \"Query\"."
...
What is the difference and why can't I get the data like in the example of the Github repo.
Thanks for your help.
It's the difference between articles and article as the query. If you use the singular one you can use the ID as argument

Using Ramda compose, groupBy and sort in order to process an array of objects

I am new to Ramda and I am trying to achieve the following:
I have an array of objects (i.e. messages).
I want to group the messages by counter party ID (either the sender or the recipient ID, whichever is not 1, see my groupBy lambda below).
I am going to obtain an object whose keys will be the counter party IDs and values an array of the messages exchanged with that counter party.
I then want to sort by date descending those arrays of messages.
And finally keep the most recent message and thus obtain an array containing the most recent message exchanged with each of the counter parties.
Because I have two counter parties above, I should have an array of two messages.
Here is what I have attempted:
const rawMessages = [
{
"sender": {
"id": 1,
"firstName": "JuliettP"
},
"recipient": {
"id": 2,
"firstName": "Julien"
},
"sendDate": "2017-01-28T19:21:15.863",
"messageRead": true,
"text": "ssssssss"
},
{
"sender": {
"id": 3,
"firstName": "Juliani"
},
"recipient": {
"id": 1,
"firstName": "JuliettP"
},
"sendDate": "2017-02-01T18:08:12.894",
"messageRead": true,
"text": "sss"
},
{
"sender": {
"id": 2,
"firstName": "Julien"
},
"recipient": {
"id": 1,
"firstName": "JuliettP"
},
"sendDate": "2017-02-07T22:19:51.649",
"messageRead": true,
"text": "I love redux!!"
},
{
"sender": {
"id": 1,
"firstName": "JuliettP"
},
"recipient": {
"id": 3,
"firstName": "Juliani"
},
"sendDate": "2017-03-13T20:57:52.253",
"messageRead": false,
"text": "hello Juliani"
},
{
"sender": {
"id": 1,
"firstName": "JuliettP"
},
"recipient": {
"id": 3,
"firstName": "Juliani"
},
"sendDate": "2017-03-13T20:56:52.253",
"messageRead": false,
"text": "hello Julianito"
}
];
const currentUserId = 1;
const groupBy = (m: Message) => m.sender.id !== currentUserId ? m.sender.id : m.recipient.id;
const byDate = R.descend(R.prop('sendDate'));
const sort = (value, key) => R.sort(byDate, value);
const composition = R.compose(R.map, R.head, sort, R.groupBy(groupBy));
const latestByCounterParty = composition(rawMessages);
console.log(latestByCounterParty);
Here is the corresponding codepen:
https://codepen.io/balteo/pen/JWOWRb
Can someone please help?
edit: Here is a link to the uncurried version: here. The behavior is identical without the currying. See my comment below with my question as to the necessity of currying.
While I think the solution from Scott Christopher is fine, there are two more steps that I might take with it myself.
Noting that one of the important rules about map is that
map(compose(f, g)) ≍ compose(map(f), map(g))
when we're already inside a composition pipeline, we can choose to unnest this step:
R.map(R.compose(R.head, R.sort(R.descend(R.prop('sendDate'))))),
and turn the overall solution into
const currentMessagesForId = R.curry((id, msgs) =>
R.compose(
R.values,
R.map(R.head),
R.map(R.sort(R.descend(R.prop('sendDate')))),
R.groupBy(m => m.sender.id !== id ? m.sender.id : m.recipient.id)
)(msgs)
)
Doing this, is, of course, a matter of taste. But I find it cleaner. The next step is also a matter of taste. I choose to use compose for things that can be listed on a single line, and hence make some obvious connection between the formats compose(f, g, h)(x) and f(g(h(x))). If it spans multiple lines, I prefer to use pipe, which behaves the same way, but runs it's functions from first to last. So I would change this a bit further to look like this:
const currentMessagesForId = R.curry((id, msgs) =>
R.pipe(
R.groupBy(m => m.sender.id !== id ? m.sender.id : m.recipient.id),
R.map(R.sort(R.descend(R.prop('sendDate')))),
R.map(R.head),
R.values
)(msgs)
)
I find this top-down reading easier than the bottom up needed with longer compose versions.
But, as I said, these are matters of taste.
You can see these examples on the Ramda REPL.
Your example was close to what you wanted, though you need just needed to move the composition of head and sort to the function argument given to map and then call values on the final result to convert the object to an array of values.
const currentMessagesForId = R.curry((id, msgs) =>
R.compose(
R.values,
R.map(R.compose(R.head, R.sort(R.descend(R.prop('sendDate'))))),
R.groupBy(m => m.sender.id !== id ? m.sender.id : m.recipient.id)
)(msgs))
currentMessagesForId(currentUserId, rawMessages)

How to make ember work with Django REST gis

I am currently trying to setup ember to interact with Django's REST Framework using the ember-django-adapter.
This works flawless. But since I started using djangorestframework-gis, ember is not able to process the responses anymore.
I have not found anyone building geoJSON with ember except for: https://gist.github.com/cspanring/5114078 But that does not seem to be the right approach because I do not want to change the data model?
This is the api-response:
{
"type": "FeatureCollection",
"features": [
{
"id": 1,
"type": "Feature",
"geometry": {
"coordinates": [
9.84375,
53.665466308594
],
"type": "Point"
},
"properties": {
"date_created": "2014-10-05T20:08:43.565Z",
"body": "Hi",
"author": 1,
"expired": false,
"anonymous": false,
"input_device": 1,
"image": "",
"lat": 0.0,
"lng": 0.0
}
}
]
}
While ember expects something like:
[{"id":1,
"date_created":"2014-10-05T20:08:43.565Z",
"body":"Hi",
"author":1,
"expired":false,
"anonymous":false,
"input_device":1,
"image":"",
"lat":0,
"lng":0
}
]
My take on this was to write my own Serializer:
import Ember from "ember";
import DS from "ember-data";
export default DS.DjangoRESTSerializer.extend({
extractArray: function(store, type, payload) {
console.log(payload);
//console.log(JSON.stringify(payload));
var features = payload["features"];
var nPayload = [];
for (var i = features.length - 1; i >= 0; i--) {
var message = features[i];
var nmessage = {"id": message.id};
for(var entry in message.properties){
var props = message.properties;
if (message.properties.hasOwnProperty(entry)) {
var obj = {}
nmessage[entry]=props[entry];
}
}
nPayload.push(nmessage);
};
console.log(nPayload); //prints in the format above
this._super(store, type, nPayload);
},
})
But I receive the following error:
The response from a findAll must be an Array, not undefined
What am I missing here? Or is this the wrong approach? Has anyone ever tried to get this to work?
An alternative would be to handle this on the serverside and simply output a regular restframework response and set lat and long in the backend.
This is not a valid answer for the question above. I wanted to share my solution anyways,
just in case anyone ever gets into the same situation:
I now do not return a valid geoJSON, but custom lat, lng values. The following is backend code for django-rest-framework:
Model:
#models/message.py
class Message(models.Model):
def lat(self):
return self.location.coords[1]
def lng(self):
return self.location.coords[0]
And in the serializer:
#message/serializer.py
class MessageSerializer(serializers.ModelSerializer):
lat = serializers.Field(source="lat")
lng = serializers.Field(source="lng")
Ember can easily handle the format.

Facebook API (javascript) getting latest school education info

I'm very new to the facebook api for my website, and I am using the javascript sdk. I want to get the users latest school information, including school name, course and year of study. This is what I have so far but it breaks the login script and returns 'response.education.school is undefined'. I'm guessing I'll need some kind of for loop to go through the education array as most users have more than one school listed?
function login() {
FB.login(function(response) {
if(response.authResponse) {
// connected
FB.api('/me', function(response) {
fbLogin(response.id, response.name, response.firstname, response.email,
response.education.school.name, response.education.concentration.name, response.education.year.name);
});
} else {
// cancelled
}
}, {scope: 'email, user_education_history, user_hometown'});
}
response.education.school is undefined
This is because responce.education is an array of objects. This would be an example for me (actual information removed)
"education": [
{
"school": {
"id": "",
"name": ""
},
"year": {
"id": "",
"name": ""
},
"concentration": [
{
"id": "",
"name": ""
}
],
"type": ""
},
...
]
You need to iterate over it and process each educaional step e.g.
for(ed in response.education) {
var school = response.education[ed].school;
var schoolName = school.name;
...
}
And so on; you are currently passing an aobject structure to your fbLogIn that can't handle it. If you want the latest school education, you simply pick the one that has the most recent year.name value.