Ember saving one to one, using promises - ember.js

im trying to save a few models with one to one relation which initializes on a single controller action. Ive split things into small functions to use promises. I've been trying to make it work for almost a week and cant find the solution. I've also made a jsbin:
http://jsbin.com/enoYONAv/1/edit

Instead of valueBinding you can use selectionBinding in your Ember.Select, to retrieve the selected model directlly instead of your id. For example:
{{
view Ember.Select
prompt="Gender"
contentBinding="genders"
optionValuePath="content.id"
optionLabelPath="content.type"
selectionBinding="selectedGender"
}}
So in you action you can do:
var gender = this.get('selectedGender');
...
var hash = {
name : personName,
gender : gender,
organization : organization
};
this.savePerson(hash).then(this.saveAgentAssociation(agentAddress));
This is your updated jsbin please give a look http://jsbin.com/efeReDer/1/edit

Related

Simple search with Emberjs not working

I am trying to implement a simple search feature, which will filter the results and update the listing.
I tried almost every single tutorial out there, every tutorial seems to be working with its jsfiddle but when I apply the same thing on my project, it does not work at all.
Here is what I am having as a first problem, my search field does not seems to be bound with computed property in controller.
I also tried it as a component but again same issue, if I type anything in search field it does not reflect anything.
Let me share my code here,
input type="text" value=searchText placeholder="Search..."
searchResults: ( ->
console.log "On every key press it should come here.."
model = #get('model')
searchText = #get('searchText')
filterByPath = #get('filterByPath')
visualPath = #get('visualPath')
if searchText
searchText = searchText.toLowerCase()
model = model.filter(item) ->
Ember.get(item, filterByPath).toLowerCase().indexOf(searchText)>= 0
model.getEach(visualPath)
).property('searchText')
Tried almost the same thing with component, but no luck so far. I am not using handlebars but Emblemjs.
You actually need to use computed property in template if you want it to be compiled, then recompiled etc. It is somewhat lazily evaluated so you can't debug that without using this in template first or calling from JavaScript code. So basically you need to use searchResults in your template first.
In demo there was model instead of searchResults. I guess in your application you have similiar setup and same bug.
Fix:
{{#each searchResults as |item|}}
<li>{{item}}</li>
{{/each}}
Working demo.

Django ManyToMany field using through with relational value

I have a model with many to many field, the field it linked through a table with Boolean value.
I got this in different scenario, lets take user as the main model, interest as the many to many field and user_interest model as the through model, inside user_interest I have a Boolean field which I want user to specify when selecting each of his many to many value,
At the moment am stuck trying to find an appropriate form interface to cater for my need, currently am using MultipleSelect widget which only show selection of interest, is there any example for field control that would allow me to choose the interest and specify the value of the Boolean field? If not, what is best practice to follow in my situation?
Best regards,
Update question with code samples
class Interest(models.Model):
name = models.CharField(_('Name'), max_length=200, )
class UserInterest(models.Model):
interest = models.ForeignKey(Interest, )
user = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL'), )
join_mail_list = models.BooleanField(default=False)
class User(models.Model):
name = models.CharField(max_length=100)
interest = models.ManyToManyField(Interest, through='UserInterest', related_name='user_interest')
Now based on the models above, when I try to create a ModelForm from User model, I will get interest as MultiSelect field which is perfectly correct. But, in my case, I want the form to collect user interests + for each interest if he wants to join_mail_list for that particular interest. Please advise?
I'll just assume that you want a list of all interests with a checkbox next to them.
Let's assume those models:
class Ressource(models.Model):
name = models.CharField(max_length=255)
class Ressource2Village(models.Model):
ressource = models.ForeignKey(Ressource)
village = models.ForeignKey(Village)
amount = models.FloatField()
class Village(MapObject):
name = models.CharField(max_length=255)
And this form:
class Ressoure2VilllageForm(forms.Form):
name = forms.CharField()
# you would use a BooleanField
value = forms.IntegerField()
Now you can create a formset (https://docs.djangoproject.com/en/1.5/topics/forms/formsets/):
from django.forms.formsets import formset_factory
r2v_formset = formset_factory(Ressoure2VilllageForm)
# use boolean for your case, if you want to edit these values later use n2m to initialize value
# [{'name': r2v.ressource.name, 'value': r2v.value} for r2v in your_village.ressource2village.all()]
init_values = [{'name': r.name, 'value': 0} for r in Ressource.objects.all()]
r2v_formset = r2v_formset(initial=init_values)
Which in your template will give you:
<label for="id_form-0-name">Name:</label><input type="text" name="form-0-name" value="Kohle" id="id_form-0-name">
<label for="id_form-0-value">Value:</label><input type="text" name="form-0-value" value="0" id="id_form-0-value">
<label for="id_form-1-name">Name:</label><input type="text" name="form-1-name" value="Eisenerz" id="id_form-1-name">
<label for="id_form-1-value">Value:</label><input type="text" name="form-1-value" value="0" id="id_form-1-value">
<label for="id_form-2-name">Name:</label><input type="text" name="form-2-name" value="Golderz" id="id_form-2-name">
[...]
The association to the specific user can be done during processing under consideration of his authentication details.
Displaying, validating and processing this should be pretty straightforward, feel free to ask follow up questions.
The question is kind of general, but I'd say that since it's a boolean field, instead of one multiselect field, you have two - one for "Things I'm interested in..." (True) and one for "Thing's I'm not interested in..." (False). Both fields would be multiselect from the same list of items, but the seperation allows the user to apply the boolean field without even noticing. Also, I strongly recommend jQuery UI autocomplete, seems like the best choice here.
Updated answer:
So seeing your code helps clear a few things. The way I would do it is like I suggested in the first place but with a little tweak.
Having a newsletter checkbox for each 'interest' is clumsy, because it requires the user to check the 'interest' twice - once because he's interested in it and once because he wants emails about it. So you have to automatically assume that the user wants to get an email for the subjects he is interested in, but allow them to prevent it if they want.
With that in mind, you build two long text inputs, and implement both of them with a tagging system (here's a good one, here are some more). The first input is "I'm interest in", and the second is "I want to recieve emails about...". Then you add an event listner with jQuery that makes sure that for every tag added to the first input it is automatically added to the second one as well. Then, if the user doesn't want to get emails for a specific subject (or all of them) he can easily take it off the second input (which doesn't have any effect on the first one).
To give you an example, here's a jsfiddle that shows how to make that happen with the chosen-jQuery library. I used Countries and Shipping because I had a pre-made list at the chosen library website, so I just copied it from there. As you can see, it's a pretty simple jQuery code, which you can easily applicate for any other tagging system (and many thanks to the fine Raúl Juárez who helped me work that out myself):
$(".chosen-select").chosen({disable_search_threshold: 10});
$('#countries').on('change', function(e) {
var selected = $(this).val();
$.each(selected, function(index, value) {
$('#shipping option[value="'+value+'"]:first').prop('selected',true);
});
$(".chosen-select").trigger('chosen:updated');
});

EmberJS - How to display subset of a model in a view

I am very new (started today) to Ember and cannot figure how how to set this up in a correct manner.
Models:
Post, Comment
On the 'show' template for Post, I want to display only the comments that are not blocked (isBlocked is a attribute of Comment model). Should I use a View and pass in a param to filter out the comments?
I cannot find an useful example or tutorial that explains this. Is there a way similar to how this would be done in Rails with partials and locals or something?
You can use a computed property that uses filterProperty to filter your model inside your controller. Then use that computed property to display in your template.
Assuming your Comment model has an isBlocked attribute, you can set up a computed property like,
comments: function() {
return this.filterProperty('isBlocked', false);
}.property('#each.isBlocked')
Then in the template use comments as the collection to iterate over. The comments collection will have all comments except those where isBlocked is true.

Setting selected entry using helper.options?

Im am using Play 2.0.4 and
helper.options(myitems)
in my template (inside of a helper.select)
In this case, how can I define the default selected entry, which shall be one entry out of myitems? Thanks for any hint!
A little bit more about my case:
Imagine a news archive, showing all news titles. This news archive uses pagination, pagination uses GET to pass the next/previous page number.
The play framework however will only correctly select the currently selected "select" item (here: news category) when a POST request was used - while pagination uses GET!
Intended behaviour: While a filter is applied / a specific news category is selected, this shall always be visible to the user by preselecting the currently selected news category in the "select" form.
A "screenshot" for illustration:
So, anyone having a good idea on how to cope with this problem? Any way to tell Play manually which entry from the "select" form it shall select? '_default always adds a new entry instead of selecting one out of the given options ): Would be great, if one wouldn't have to build the complete "select" form manually.
Try passing '_default option to select helper:
#import views.html.helper._
#select(form("email"), options(List("first", "third")), '_default -> "second")
It seems, unfortunately, the only way to figure it out is to look up the source.
Update:
Specifying _default property doesn't set selected attribute on option tag. It looks like the only way to preselect entry is to pass prefilled form to the template. For example, suppose you have following form:
case class RegInfo(email: String, color: String)
private val registrationForm = Form(
mapping(
"email" → email,
"color" → nonEmptyText(minLength = 5, maxLength = 32)
)(RegInfo.apply)(RegInfo.unapply)
)
Then in the action prefill form before passing to the view:
def create = Action {
Ok(html.create(registrationForm.fill(RegInfo("user#qwe.com", "blue"))))
}
Then in template use helper:
#select(form("color"), options(List("red", "green", "blue")))
And value will be preselected.
Ended up with the pragmatic approach:
<select id="myfield" name="myfield" >
<option class="blank" value="">-- All items --</option>
#for((key, value) <- MyModel.options) {
#if(key == GETValuePassedToTemplate) {
<option value="#key" selected>#value</option>
} else {
<option value="#key">#value</option>
}
}
</select>
Still wondering if there is a better option / way to do it.
Actually, there is a nicer solution to it. If you call the template having the form partially bound you will achieve your goal. Here's the code for your controller:
Ok(views.html.myForm(myForm.bind(
Map("fieldName1" -> "value1",
"fieldName2" -> "value2"))))
Make sure you map fieldnames to the values of the options you want pre-selected.
Still wondering if there is a better option / way to do it.
Well, if your not hell-bent on using play to solve this particular problem, you could always solve it using JavaScript and jQuery:
$(function () {
$('#yourSelect_id').val(5);
}
Where your select options each has values and the one option you whish to pre select has value 5.

Ember Data: Proper Way to Use findAll

I am trying to use ember-data using https://github.com/emberjs/data as a reference.
Specifically, I am trying to use an array controller to display all of the 'Person' objects in my database. I also want to allow the user to create a new 'Person'.
I have the following code which works:
App.peopleController = Em.ArrayController.create
content: App.store.findAll(App.Person)
newPerson: (name) ->
App.store.create App.Person,
name: name
#set('content', App.store.findAll(App.Annotation))
However, it seems inefficient to reset the content property every time a new person is created. If I remove the last line and change the code to the following:
App.peopleController = Em.ArrayController.create
content: App.store.findAll(App.Person)
newPerson: (name) ->
App.store.create App.Person,
name: name
A new view is still created on ever newPerson call, but the same object is duplicated. Essentially what is happening is all of the new templates use the first object created instead of a new one each time. I think this is related to the following bug: https://github.com/emberjs/data/issues/11.
For reference, my template logic is as follows:
{{#each App.peopleController}}
{{#view App.PersonView contentBinding="this"}}
{{#with content}}
Client id is {{clientId}}
{{/with}}
{{/view}}
{{/each}}
When I use the second version of my code-- the one with the #set('content', App.store.findAll(App.Annotation)) line-- the clientId is duplicated for every Person object. In the first version, the client ids are correct.
Can anyone shed some light here? Am I doing this correctly? My instincts are telling me this is a bug but I am not sure.
I think it is a bug. I posted a related issue that illustrates this issue.
Try using the #collection view instead.
See code of ToDo example. Also see http://guides.sproutcore20.com/using_handlebars.html section 5 for some documentation.
Hope this helps.