django-autocomplete-light add parameter to query url - django

I'm trying to pass some data along to the autocomplete_light.AutocompleteModelBase so I can exclude some models from the search. I'm trying to use the Dependencies info in the docs here
but I can seem to get it.
The id of the input is id_alternate_version-autocomplete, so I'm trying:
$("#id_alternate_version-autocomplete").yourlabsWidget().autocomplete.data = {'id': 'foo'};
But the url called looks like http://127.0.0.1:8000/autocomplete/FooAutocomplete/?q=bar
I want: http://127.0.0.1:8000/autocomplete/FooAutocomplete/?q=bar&id=foo
How can I do something like that?

DAL provides a way to do this with "forwarding" of another rendered form field's value.
See http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#filtering-results-based-on-the-value-of-other-fields-in-the-form

This is how I did it:
$(document).ready(function() {
$('form#recipe').on('change propertychange keyup input paste', function() {
var ingredient_item_type = $("form#recipe input[type='radio']:checked").val();
var widget = $("form#recipe input#id_ingredients_text").parents('.autocomplete-light-widget');
if(ingredient_item_type) {
widget.yourlabsWidget().autocomplete.data['hello'] = 'world';
}
});
});
Javascript acrobatics aside, the key observation is thus:
anything you put in the .data object of the autocomplete widget will
automatically be made part of the GET request. HTH.

Related

A proper way to separate concerns?

My app allows the users to manage their documents. When creating one, a user has to either enter the document content manually or select a file from their computer (which would convert many formats to HTML for the user).
Currently, I have a simple FileUploaderView which is basically an <input type="file"> that listens to file changes, and updates the value property of the view with an object like { file: { type: SOME_TYPE' }, content: SOME_CONTENT }.
Then, DocumentsNewController listens to changes in it and converts supported files to HTML, and puts the result into the document body.
However, doing it this way feels simply wrong and does not allow for simple reuse (which I want to be able to do).
App.DocumentsNewController = Ember.ObjectController.extend
# ... stuff ...
handleDocumentUpload: (->
doc = #get 'documentUpload'
return unless doc
Ember.run =>
#set 'uploadError', false
#set 'unsupportedFile', false
#set 'processingUpload', true
type = doc.file.type
text = ''
try
if type.match /^text\//
text = doc.content
# Convert new lines to br's and paragraphs
text = '<p>' + text.replace(/\n([ \t]*\n)+/g, '</p><p>').replace('\n', '<br />') + '</p>'
else if type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
text = new DOCX2HTML(doc.content).convert()
else
#set 'unsupportedFile', true
catch error
#set 'uploadError', true
finally
#set 'text', text
Ember.run => #set 'processingUpload', false
).observes 'documentUpload'
And the template is something like
... stuff ...
{{view App.FileUploaderView valueBinding="documentUpload" accept="text/*"}}
What would be the proper way to refactor file converting stuff out of the controller?
I want to be able to do something like:
{{documentHandler resultBinding="documentUpload"}}
and in controller
App.DocumentsNewController = Ember.ObjectController.extend
# ... stuff ...
handleDocumentUpload: (->
if doc = #get 'documentUpload'
#set 'text', doc
).observes 'documentUpload'
My first thought was to make a DocumentHandlerView which would display the input field, show the spinner, show the errors, parse the document and assign the result to result (and since controller's template has resultBinding="documentUpload", the HTML would trigger the controller's observer).
Using a view for that would allow for easier reuse but I still feel it's not the view's job to parse the document.
Is there a better way?
After reading closely your question the best thing that comes in mind would be to create a Ember.Mixin and then use it for all the controllers that need the same functionality.
Example taken from the ember API docs:
App.Editable = Ember.Mixin.create({
edit: function() {
console.log('starting to edit');
this.set('isEditing', true);
},
isEditing: false
});
// Mix mixins into classes by passing them as the first arguments to
// .extend.
App.CommentView = Ember.View.extend(App.Editable, {
template: Ember.Handlebars.compile('{{#if isEditing}}...{{else}}...{{/if}}')
});
commentView = App.CommentView.create();
commentView.edit(); // outputs 'starting to edit'
The example is only conceptual, but it will be easy to create a mixin yourself and put all the common logic in there.
Hope it helps.

Passing a list in a url inside a TokenInput with Django, he only pass the last one

I am using jquery-tokeninput as an autocomplete to retrieve some objects in my app.
My js code to initialize the autocomplete is this:
function initialize_search(model, input_busca) {
var url = reverse('autocomplete.'+model) + "?tipos[]=almoxarifado&tipos[]=estoque";
var data = $(input_busca).data('tokeninput');
$(input_busca).tokenInput(url, {
hintText: 'Start to type',
preventDuplicates: true,
queryParam: 'name',
noResultsText: 'No results',
searchingText: 'Search',
prePopulate: data
});
}
All I want is to receive the parameter 'tipos[]' in my view, like this:
types = request.GET.getlist('tipos[]')
And receive this:
[u'almoxarifado', u'estoque']
But when i do this, he only gives me the last one and not all the list, in this case:
[u'estoque']
This is how I call the autocomplete function inside the js:
inicializa_busca('endereco', $("#id_enderecos"));
You must be aware that, ajax is to pass small data, check the size of this list, maybe is better an full post submission!

Ember.Controller array content filtering

I have a fiddle http://jsfiddle.net/kristaps_petersons/9wteJ/2/ it loads 3 objects and shows them in a view. Data is shown alright, but i can not filter it before i show it.
This
nodes: function(){
this.get('controller.content').filter(function(item, idx, en){
console.log('should log this atleast 3x')
})
return this.get('controller.content')
}.property('controller.content')
method is called when template iterates over array of values, but it never goes in to the loop and print console.log('should log this atleast 3x') why is that?
You are trying to replace controller.content while also binding to it. You need to define another property, such as filteredContent and bind it to controller.content. Take a look at how Ember.SortableMixin computes the variable arrangedContent for controllers with a sortProperties variable defined. Using that method as a template I would implement it like this:
filteredContent: Ember.computed('content', function() {
var content = this.get('content');
return this.filter(function(item, idx, en) {
console.log('should log this atleast 3x');
});
}).cacheable()
This should be implemented in the controller, not the view. The controller is the place for data manipulation, computed properties, and bindings.
Then bind the view layout to filteredContent instead of content to show the filtered data. Then both the original content and the filtered content are available.
Ok i got it working, but it feels a bit strange. First i moved method to Controller class and changed it to look like this:
nodes: function(){
console.log('BEFORE should log this atleast 3x', this.get('content.length'))
this.get('content').forEach(function(item, idx, en){
console.log('should log this atleast 3x')
})
console.log('AFTER should log this atleast 3x', this.get('content.length'))
return this.get('content')
}.property('content').cacheable()
as it should be same as buuda's recomedation, because as i understand from docs .poperty() is the same as Ember.computed. As it was still not working, i changed .property('content') to .property('content.#each') and it was working. Fiddle: http://jsfiddle.net/kristaps_petersons/9wteJ/21/ . I guess, that tempate first creates a binding to controller.content and as content itself does not change does not notify this method again, instead template pulls data as it becomes available.

Proper design of REST-powered list in Ember.js

I'm having difficulty wrapping my head around the following:
There's a view that displays the list of items
I take the list of items from the backend via RESTful interface in JSON using ember-data and hand-crafted adapter
In my view I do something like this:
{{#collection contentBinding="App.recentAdditionsController"}}
...
{{/collection}}
App.recentAdditionsController is defined like this:
App.recentAdditionsController = Em.ArrayController.create({
refresh: function(query) {
var items = App.store.findAll(App.Item);
this.set('content', items);
}
});
And... this doesn't work. The reason being App.store.findAll() returning ModelArray which is much like ArrayController itself.
I saw people doing something like this:
App.recentAdditions = App.store.findAll(App.Item);
I could imagine doing it like that, but how would I refresh the list at will (checking if there's anything new).
Hope all is clear more or less.
I've verified that you can use a ModelArray inside an ArrayController. Here's a jsFiddle example: http://jsfiddle.net/ebryn/VkKX2/
"Now the question is how to make the list update itself if there are new objects in the backend?"
Use App.Model.filter to keep your recordArray in sync. Add the query hash when the filter is invoked to ensure than an initial query was made.
model: ->
App.Model.filter {page: 1}, (data) ->
data
edit: Just saw how old the question was, but leaving it here in case it helps someone.

Adding a search box to filter a list of results in Symfony?

I need to put a search box within a list of objects as a result of a typical indexSuccess action in Symfony. The goal is simple: filter the list according to a criteria.
I've been reading the Zend Lucene approach in Jobeet tutorial, but it seems like using a sledge-hammer to crack a nut (at least for my requirements).
I'm more interested in the auto-generated admin filter forms but I don't know how to implement it in a frontend.
I could simply pass the search box content to the action and build a custom query, but is there any better way to do this?
EDIT
I forgot to mention that I would like to have a single generic input field instead of an input field for each model attribute.
Thanks!
I'm using this solution, instead of integrating Zend Lucene I manage to use the autogenerated Symonfy's filters. This is the way i'm doing it:
//module/actions.class.php
public function executeIndex(sfWebRequest $request)
{
//set the form filter
$this->searchForm = new EmployeeFormFilter();
//bind it empty to fetch all data
$this->searchForm->bind(array());
//fetch all
$this->employees = $this->searchForm->getQuery()->execute();
...
}
I made a search action which does the search
public function executeSearch(sfWebRequest $request)
{
//create filter
$this->searchForm = new EmployeeFormFilter();
//bind parameter
$fields = $request->getParameter($this->searchForm->getName());
//bind
$this->searchForm->bind($fields);
//set paginator
$this->employees = $this->searchForm->getQuery()->execute();
...
//template
$this->setTemplate("index");
}
It's important that the search form goes to mymodule/search action.
Actually, i'm also using the sfDoctrinePager for paginate setting directly the query that the form generate to get results properly paginated.
If you want to add more fields to the search form check this :)
I finally made a custom form using the default MyModuleForm generated by Symfony
public function executeIndex {
...
// Add a form to filter results
$this->form = new MyModuleForm();
}
but displaying only a custom field:
<div id="search_box">
<input type="text" name="criteria" id="search_box_criteria" value="Search..." />
<?php echo link_to('Search', '#my_module_search?criteria=') ?>
</div>
Then I created a route named #my_module_search linked to the index action:
my_module_search:
url: my_module/search/:criteria
param: { module: my_module, action: index }
requirements: { criteria: .* } # Terms are optional, show all by default
With Javascript (jQuery in this case) I append the text entered to the criteria parameter in the href attribute of the link:
$('#search_box a').click(function(){
$(this).attr('href', $(this).attr('href') + $(this).prev().val());
});
And finally, back to the executeIndex action, I detect if text was entered and add custom filters to the DoctrineQuery object:
public function executeIndex {
...
// Deal with search criteria
if ( $text = $request->getParameter('criteria') ) {
$query = $this->pager->getQuery()
->where("MyTable.name LIKE ?", "%$text%")
->orWhere("MyTable.remarks LIKE ?", "%$text%")
...;
}
$this->pager->setQuery($query);
...
// Add a form to filter results
$this->form = new MyModuleForm();
}
Actually, the code is more complex, because I wrote some partials and some methods in parent classes to reuse code. But this is the best I can came up with.