how to remove Attachment for specific model in openrp? - python-2.7

I'm developing my own model. I installed Document model. This model is giving attachment button on top of the form. but i want this attachment button in only my module. I want to hide other that button in other form (other model).
so I'm getting following code for removing "create and save" for specific model. but this coding is not working my side. please tell me how to use attachment button for specific model? and how to hide other models?.
openerp.web_smile_hide_buttons = function(openerp) {
// Models for which we'll hide create and duplicate buttons
var MODELS_TO_HIDE = ['kit.lab'];
// Hide the create button on all list views, which affect tree views and many2one pop-up search view
openerp.web.ListView.include({
start: function() {
var self = this;
var ret = this._super.apply(this, arguments);
var res_model = this.dataset.model;
if ($.inArray(res_model, MODELS_TO_HIDE) != -1) {
self.options.addable = false;
};
return ret;
},
});
// Hide the save button on form views
openerp.web.FormView.include({
on_loaded: function(data) {
var self = this;
var ret = this._super.apply(this, arguments);
var res_model = this.dataset.model;
// if ($.inArray(res_model, MODELS_TO_HIDE) != -1) {
this.$element.find('button.oe_dropdown_toggle.oe_dropdown_arrow').remove();
this.$element.find('button.oe_form_button_save').remove();
//};
return ret;
},
});
// Hide the create and duplicate button on all page views (i.e. read-only form views)
openerp.web.PageView.include({
on_loaded: function(data) {
var self = this;
var ret = this._super.apply(this, arguments);
var res_model = this.dataset.model;
if ($.inArray(res_model, MODELS_TO_HIDE) != -1) {
this.$element.find('button.oe_form_button_create').remove();
this.$element.find('button.oe_form_button_duplicate').remove();
};
return ret;
},
});
};

This question is older, but I had the same problem and figured it out. Its most likely not the best solution, but it works. I assume you know how to write a custom module, so just add a dependency to "document" and create an own javascript (e.g. static/src/js/document.js, don't forget to include it in your openerp.py) with the following content:
openerp.document = function (instance) {
_t = instance.web._t;
instance.web.Sidebar.include({
init : function(){
this._super.apply(this, arguments);
if (window.location.href.indexOf('&model=res.partner') === -1)
this.sections.splice(1, 0, { 'name' : 'files', 'label' : _t('Attachment(s)'), });
this.items['files'] = [];
},
});
};
In this example the "Attachment" button will be hidden in the res.partner form view.
Maybe someone else knows a better way to look for the current model compared to my solution to look for the string in window.location.href

Related

How can I port a bound date input helper to HTMLBars?

I'm trying to port a 'DateInputView' TextField extension with a bound helper to HTMLBars. It appears that 'call()' has been removed from 'Handlebars.helpers.view' so the helper doesn't work anymore. I've tried several syntax changes based on forums I've read but nothing works. The field is a datepicker which switches to the native calendar picker when using a mobile device. I see an example where the bound helper is integrated into the view helper code, so uses one js file rather than two, so am trying to go that route now. Code is below. If anyone who knows to to rework it for HTMLBars please let me know.
// ../templates/avail/navigation.hbs
{{date-input id="checkin" valueBinding="controllers.avail.arrival" class="form-control date-picker"}}
// ../views/date-input.js
var DateInputView = Ember.TextField.extend({
didInsertElement: function(){
Ember.run.scheduleOnce('afterRender', this, this._setupDateInput);
},
_setupDateInput: function(){
var _this = this;
var type = Ember.$(this.get('element')).attr('type');
// Set up Date Picker for object
if( type === "input" ) {
Ember.$(this.get('element')).datepicker({
format: "yyyy-mm-dd",
autoclose: true
});
}
}
});
export default DateInputView;
// ../helpers/date-input.js
import DateInputView from '../views/date-input';
export default Ember.Handlebars.makeBoundHelper(function(options) {
Ember.assert('You can only pass attributes to the `input` helper, not arguments', arguments.length < 2);
var hash = options.hash,
types = options.hashTypes,
inputType = hash.type,
onEvent = hash.on;
delete hash.type;
delete hash.on;
hash.type = "input";
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
hash.type = "date";
}
hash.onEvent = onEvent || 'enter';
return Ember.Handlebars.helpers.view.call(this, DateInputView, options);
});
I wound up re-working this viewHelper as a Component.

Save previous state URL when transition to another route

When I transition to a new route, is there any way to store previous state with all the parameters?
Browser back button kinda work so I guess window.history.back() instead of link-to helper would work for me, but I am curious is there any Ember way to save a state and transition to it later?
Thanks
Not sure, if this case works for you but I have saved the previous state and then make the transition to that state in a tab menu which needed to save the state for each specific menu.
App.MenuRoute = Em.Route.extend({
actions: {
willTransition: function(transition) {
var handlers = this.router.router.targetHandlerInfos;
var handler = handlers[handlers.length-1];
this.controller.set('lastHandler', handler);
},
selectMenu: function(value) {
var handler = this.controllerFor(value).get('lastHandler');
var routeName = (handler) ? handler.name : value;
var model;
if ( handler && handler.isDynamic ) {
model = handler.context;
}
if ( model ) {
this.transitionTo(routeName, model);
} else {
this.transitionTo(routeName);
}
}
}
}
});

How to dynamically add and remove views with Ember.js

I am trying to create an interface for traversing tables in a relation database. Each select represents a column. If the column is a foreign key, a new select is added to the right. This keeps happening for every foreign key that the user accesses. The number of selects is dynamic.
I made a buggy implementation that has code that manually adds and removes select views. I think it probably can be replaced with better Ember code (some kind of array object maybe?), I'm just not sure how to best use the framework for this problem.
Here's my JSBin http://jsbin.com/olefUMAr/3/edit
HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Ember template" />
<meta charset=utf-8 />
<title>JS Bin</title>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://builds.emberjs.com/handlebars-1.0.0.js"></script>
<script src="http://builds.emberjs.com/tags/v1.1.2/ember.js"></script>
</head>
<body>
<script type="text/x-handlebars" data-template-name="my_template">
{{view fieldSelects}}
</script>
<div id="main"></div>
</body>
</html>
JavaScript:
App = Ember.Application.create();
var TemplatedViewController = Ember.Object.extend({
templateFunction: null,
viewArgs: null,
viewBaseClass: Ember.View,
view: function () {
var controller = this;
var viewArgs = this.get('viewArgs') || {};
var args = {
template: controller.get('templateFunction'),
controller: controller
};
args = $.extend(viewArgs, args);
return this.get('viewBaseClass').extend(args);
}.property('templateFunction', 'viewArgs'),
appendView: function (selector) {
this.get('view').create().appendTo(selector);
},
appendViewToBody: function () {
this.get('view').create().append();
}
});
var DATA = {};
DATA.model_data = {
"Book": {
"fields": [
"id",
"title",
"publication_year",
"authors"
],
"meta": {
"id": {},
"title": {},
"publication_year": {},
"authors": {
"model": "Author"
}
}
},
"Author": {
"fields": [
"id",
"first_name",
"last_name",
"books"
],
"meta": {
"id": {},
"first_name": {},
"last_name": {},
"books": {
"model": "Book"
}
}
}
};
var Controller = TemplatedViewController.extend({
view: function () {
var controller = this;
return this.get('viewBaseClass').extend({
controller: controller,
templateName: 'my_template'
});
}.property(),
selectedFields: null,
fieldSelects: function () {
var filter = this;
return Ember.ContainerView.extend({
controller: this,
childViews: function () {
var that = this;
var selectedFields = filter.get('selectedFields');
var ret = [];
var model = 'Book';
selectedFields.forEach(function (item, index, enumerable) {
var selection = item;
if (model) {
var select = that.makeSelect(model, that.getPositionIndex(), selection, true).create();
ret.pushObject(select);
model = DATA.model_data[model].meta[selection].model;
}
});
return ret;
}.property(),
nextPositionIndex: 0,
incrementPositionIndex: function () {
this.set('nextPositionIndex', this.get('nextPositionIndex') + 1);
},
getPositionIndex: function () {
var index = this.get('nextPositionIndex');
this.incrementPositionIndex();
return index;
},
setNextPositionIndex: function (newValue) {
this.set('nextPositionIndex', newValue+1);
},
makeSelect: function (modelName, positionIndex, selection, isInitializing) {
var view = this;
return Ember.Select.extend({
positionIndex: positionIndex,
controller: filter,
content: DATA.model_data[modelName].fields,
prompt: '---------',
selection: selection || null,
selectionChanged: function () {
var field = this.get('selection');
// Remove child views after this one
var lastIndex = view.get('length') - 1;
if (lastIndex > this.get('positionIndex')) {
view.removeAt(this.get('positionIndex')+1, lastIndex-this.get('positionIndex'));
view.setNextPositionIndex(this.get('positionIndex'));
}
if (! isInitializing && DATA.model_data[modelName].meta[field].model) {
var relatedModel = DATA.model_data[modelName].meta[field].model;
view.pushObject(view.makeSelect(relatedModel, view.getPositionIndex()).create());
}
// Reset ``isInitializing`` after the first run
if (isInitializing) {
isInitializing = false;
}
var selectedFields = [];
view.get('childViews').forEach(function (item, index, enumerable) {
var childView = item;
var selection = childView.get('selection');
selectedFields.pushObject(selection);
});
filter.set('selectedFields', selectedFields);
}.observes('selection')
});
}
});
}.property()
});
var controller = Controller.create({
selectedFields: ['authors', 'first_name']
});
$(function () {
controller.appendView('#main');
});
Approach:
I would tackle this problem using an Ember Component.
I have used a component because it will be:
Easily reusable
The code is self contained, and has no external requirements on any of your other code.
We can use plain javascript to create the view. Plain javascript should make the code flow easier to understand (because you don't have to know what Ember is doing with extended objects behind the scenes), and it will have less overhead.
Demo:
I have created this JSBin here, of the code below.
Usage
Add to your handlebars template:
{{select-filter-box data=model selected=selected}}
Create a select-filter-box tag and then bind your model to the data attribute, and your selected value array to the selected attribute.
The application:
App = Ember.Application.create();
App.ApplicationController = Ember.ObjectController.extend({
model: DATA.model_data,
selected: ['Author','']
});
App.SelectFilterBoxComponent = Ember.Component.extend({
template: Ember.Handlebars.compile(''), // Blank template
data: null,
lastCount: 0,
selected: [],
selectedChanged: function(){
// Properties required to build view
var p = this.getProperties("elementId", "data", "lastCount", "selected");
// Used to gain context of controller in on selected changed event
var controller = this;
// Check there is at least one property. I.e. the base model.
var length = p.selected.length;
if(length > 1){
var currentModelName = p.selected[0];
var type = {};
// This function will return an existing select box or create new
var getOrCreate = function(idx){
// Determine the id of the select box
var id = p.elementId + "_" + idx;
// Try get the select box if it exists
var select = $("#" + id);
if(select.length === 0){
// Create select box
select = $("<select id='" + id +"'></select>");
// Action to take if select is changed. State is made available through evt.data
select.on("change", { controller: controller, index: idx }, function(evt){
// Restore the state
var controller = evt.data.controller;
var index = evt.data.index;
var selected = controller.get("selected");
// The selected field
var fieldName = $(this).val();
// Update the selected
selected = selected.slice(0, index);
selected.push(fieldName);
controller.set("selected", selected);
});
// Add it to the component container
$("#" + p.elementId).append(select);
}
return select;
};
// Add the options to the select box
var populate = function(select){
// Only populate the select box if it doesn't have the correct model
if(select.data("type")==currentModelName)
return;
// Clear any existing options
select.html("");
// Get the field from the model
var fields = p.data[currentModelName].fields;
// Add default empty option
select.append($("<option value=''>------</option>"));
// Add the fields to the select box
for(var f = 0; f < fields.length; f++)
select.append($("<option>" + fields[f] + "</option>"));
// Set the model type on the select
select.data("type", currentModelName);
};
var setModelNameFromFieldName = function(fieldName){
// Get the field type from current model meta
type = p.data[currentModelName].meta[fieldName];
// Set the current model
currentModelName = (type !== undefined && type.model !== undefined) ? type.model : null;
};
// Remove any unneeded select boxes. I.e. where the number of selects exceed the selected length
if(p.lastCount > length)
for(var i=length; i < p.lastCount; i++)
$("#" + p.elementId + "_" + i).remove();
this.set("lastCount", length);
// Loop through all of the selected, to build view
for(var s = 1; s < length; s++)
{
// Get or Create select box at index s
var select = getOrCreate(s);
// Populate the model fields to the selectbox, if required
populate(select);
// Current selected
var field = p.selected[s];
// Ensure correct value is selected
select.val(field);
// Set the model for next iteration
setModelNameFromFieldName(field);
if(s === length - 1 && type !== undefined && type.model !== undefined)
{
p.selected.push('');
this.notifyPropertyChange("selected");
}
}
}
}.observes("selected"),
didInsertElement: function(){
this.selectedChanged();
}
});
How it works
The component takes the two parameters model and selected then binds an observer onto the selected property. Any time the selection is changed either through user interaction with the select boxes, or by the property bound to selected the view will be redetermined.
The code uses the following approach:
Determine if the selection array (selected) is greater than 1. (Because the first value needs to be the base model).
Loop round all the selected fields i, starting at index 1.
Determine if select box i exists. If not create a select box.
Determine if select box i has the right model fields based on the current populated model. If yes, do nothing, if not populate the fields.
Set the current value of the select box.
If we are the last select box and the field selected links to a model, then push a blank value onto the selection, to trigger next drop down.
When a select box is created, an onchange handler is hooked up to update the selected value by slicing the selected array right of the current index and adding its own value. This will cause the view to change as required.
A property count keeps track of the previous selected's length, so if a change is made to a selection that decreases the current selected values length, then the unneeded select boxes can be removed.
The source code is commented, and I hope it is clear, if you have any questions of queries with how it works, feel free to ask, and I will try to explain it better.
Your Model:
Having looked at your model, have you considered simplifying it to below? I appreciate that you may not be able to, for other reasons beyond the scope of the question. Just a thought.
DATA.model_data = {
"Book": {
"id": {},
"title": {},
"publication_year": {},
"authors": { "model": "Author" }
},
"Author": {
"id": {},
"first_name": {},
"last_name": {},
"books": { "model": "Book" }
}
};
So field names would be read off the object keys, and the value would be the meta data.
I hope you find this useful. Let me know if you have any questions, or issues.
The Controller:
You can use any controller you want with this component. In my demo of the component I used Ember's built in ApplicationController for simplicity.
Explaination of notifyPropertyChange():
This is called because when we are inserting an new string into the selected array, using the push functionality of arrays.
I have used the push method because this is the most efficient way to add a new entry into an existing array.
While Ember does have a pushObject method that is supposed to take care of the notification as well, I couldn't get it to honour this. So this.notifyPropertyChange("selected"); tells Ember that we updated the array. However I'm hoping that's not a dealbreaker.
Alternative to Ember Component - Implemented as a View
If you don't wish to use it in Component format, you could implement it as a view. It ultimately achieves the same goal, but this may be a more familiar design pattern to you.
See this JSBin for implementation as a View. I won't include the full code here, because some of it is the same as above, you can see it in the JSBin
Usage:
Create an instance of App.SelectFilterBoxView, with a controller that has a data and selected property:
var myView = App.SelectFilterBoxView.create({
controller: Ember.Object.create({
data: DATA.model_data,
selected: ['Author','']
})
});
Then append the view as required, such as to #main.
myView.appendTo("#main");
Unfortunately your code doesn't run, even after adding Ember as a library in your JSFiddle, but ContainerView is probably what you're looking for: http://emberjs.com/api/classes/Ember.ContainerView.html as those views can be dynamically added/removed.
this.$().remove() or this.$().append() are probably what you're looking for:
Ember docs.

How can I programmatically add/remove models to a controller?

This shouldn't be too hard.
I have a datepicker UI widget, and each time the user clicks on a month, I want to add or remove that month from the MonthsController (an ArrayController). The MonthsController is not associated with a route, so in my ApplicationTemplate I simply have
{{render months}}
A simplified version of my datepicker view is
App.DatepickerView = Ember.View.extend({
click: function(e) {
var id = $(this).datepicker().data('date').replace(" ", "-");
this.get('controller.controllers.months').toggleMonth(id);
}
});
and I handle the event in my MonthsController:
App.MonthsController = Ember.ArrayController.extend({
toggleMonth: function(id) {
var month = App.Month.find(id),
index = this.indexOf(month);
if (index === -1) {
this.pushObject(month);
} else {
this.removeAt(index);
}
}
});
I thought I had this working, but then I realized that month in the last snippet wasn't really an App.Month, it was just (I suppose) an anonymous object.
How can I programmatically add/remove models to a controller?
Your App.Month.find(id) will return a promise. If that month hasn't loaded yet you would also be loading this data from the server. You need to wrap your code in the promise's then.
toggleMonth: function(id) {
var _this = this;
App.Month.find(id).then(function(month) {
var index = _this.indexOf(month);
if (index === -1) {
_this.pushObject(month);
} else {
_this.removeAt(index);
}
});
}

Ember - how to create and bind a Checkbox controller?

This question is linked to the answer given here.
Having a checkbox in a view
App.RoleCheckbox = Em.Checkbox.extend({
userRolesBinding: 'parentView.user.roles', // Points to the roles of the user
checked: function () {
var userRoles = this.get('userRoles');
return userRoles.contains(this.get('content'));
}.property('content', 'userRoles.#each'),
click: function (evt) {
//do something
var controller = this.get("controller");
controller.clicked(evt);
}
});
I would like that the click function calls the clicked function from the RoleCheckboxController:
App.RoleCheckboxController = Em.Controller.extend({
clicked: function(evt){
//Really do the thing
}
});
But this does not work. How could I fix this ?
JSFiddle: http://jsfiddle.net/3fMpD/
You can instantiate and associate the controller to the view using the correct naming conventions.
For example, this would associate the controller to the view:
// Instead of App.RoleCheckBoxController
App.ApplicationController = Ember.Controller.extend( /* ... */ );
App.ApplicationView = Ember.View.extend( /* .. */ );
JSFiddle: http://jsfiddle.net/YL5rQ/
#c4p is definitely right and the problem there is that your controller is not being created, and furthermore App.RoleCheckbox has no way of knowing it should use App.RoleCheckboxController as its controller.
I am not quite sure if this is the most Ember-y way of doing this but you can set the controller in the init (constructor function) of the Checkbox view, and then just make sure you send to the controller all the properties it needs to work with:
App.RoleCheckbox = Em.Checkbox.extend({
init: function(){
this._super();
this.set('controller', new App.RoleController());
},
userRolesBinding: 'parentView.user.roles',
checked: function () {
var userRoles = this.get('userRoles');
return userRoles.contains(this.get('content'));
}.property('content', 'userRoles.#each'),
click: function (evt) {
this.get('controller').send('clicked',this.checked, this.content);
}
});
And the controller's code (just changing the parameters used in the function);
App.RoleCheckboxController = Em.ObjectController.extend({
clicked: function(checked,role){
var userRoles = App.User.roles;
console.log("userRoles = ", userRoles);
console.log("role = ", role);
console.log("will be: ", !checked ? "removed" : "added");
if (checked) {
userRoles.pushObject(role);
} else {
userRoles.removeObject(role);
}
console.log("updated userRoles = ", userRoles);
}
});
Working fiddle here: http://jsfiddle.net/cfSwq/3/
Hope this helps!
Your App.RoleCheckboxController is never created. The way you have things set up there will only be an instance of ApplicationController.
You can move the logic back into the view's click event to have everything work:
App.RoleCheckbox = Em.Checkbox.extend({
userRolesBinding: 'parentView.user.roles',
checked: function () {
var userRoles = this.get('userRoles');
return userRoles.contains(this.get('content'));
}.property('content', 'userRoles.#each'),
click: function (evt) {
console.log("event triggered:", evt);
//var controller = this.get("controller");
//controller.clicked(evt);
var isPresent = this.get('checked'),
userRoles = this.get('userRoles'),
role = this.get('content');
console.log("userRoles = ", userRoles);
console.log("role = ", role);
console.log("will be: ", isPresent ? "removed" : "added");
if (!isPresent) {
userRoles.pushObject(role);
} else {
userRoles.removeObject(role);
}
}
});
Updated JSFiddle