odoo, how to reload widget on every db record form view? - odoo

Hi this question is related with my own answer here the thing is that the widget run only once, when the first database record object is show on the form view, but when I change to another record, the view its not updated with the actual record. I think that is because I run all the code in the ´start´ but I dont know how and where put he code to do this.
the code again:
(function (instance) {
var _t = instance.web._t,
_lt = instance.web._lt;
var QWeb = instance.web.qweb;
openerp.chess_base = function (instance, local) {
local.ShowBoard = instance.web.form.FormWidget.extend({
start: function () {
this.$el.append('<div id="board" style="width: 300px">BOARD GOES HERE</div>');
this.show_board();
},
show_board: function () {
var Game = new instance.web.Model("chess.game"),
record_id = this.field_manager.datarecord.id,
record_name = this.field_manager.datarecord.name,
self = this;
self.el_board = self.$('#board');
Game.query(['pgn']).filter([['id', '=', record_id], ['name', '=', record_name]]).all().then(function (data) {
console.log(data);
self.cfg = {
position: data[0].pgn,
orientation: 'white',
pieceTheme: '/chess_base/static/img/chesspieces/wikipedia/{piece}.png'
};
ChessBoard(self.el_board, self.cfg);
});
}
});
instance.web.form.custom_widgets.add('board', 'instance.chess_base.ShowBoard');
}
})(openerp);

In your start function:
this._ic_field_manager.on('view_content_has_changed', this, function() {
'put your code here'
})
EDIT:
Actually there's another event you could listen, 'load_record'.
Because 'view_content_has_changed' is triggered every time a single field in the view is modified, and you maybe don't want this behavior.

Related

Odoo: open full model page from add line in a one2many field

I made a custom model and i have a one2many field where i click on "add new line" then "search more" to look for the item i want to add just like the picture below
What I want is to click on "add new line", and the whole products page appear without having to go throw the previous process
You can extend ListRenderer and override _onAddRecord to open a search more view using a condition in context.
The following code adds a new widget to open search more... link and select many records.
odoo.define('stack_overflow.open_list_view', function (require) {
"use strict";
var pyUtils = require('web.py_utils');
var dialogs = require('web.view_dialogs');
var core = require('web.core');
var _t = core._t;
var fieldRegistry = require('web.field_registry');
var ListRenderer = require('web.ListRenderer');
var AddManyFieldOne2ManyRenderer = ListRenderer.extend({
/**
* It will returns the first visible widget that is editable
*
* #private
* #returns {Class} Widget returns first widget
*/
_getFirstWidget: function () {
var record = this.state.data[this.currentRow];
var recordWidgets = this.allFieldWidgets[record.id];
var firstWidget = _.chain(recordWidgets).filter(function (widget) {
var isLast =
widget.$el.is(':visible') &&
(
widget.$('input').length > 0 || widget.tagName === 'input' ||
widget.$('textarea').length > 0 || widget.tagName === 'textarea'
) &&
!widget.$el.hasClass('o_readonly_modifier');
return isLast;
}).first().value();
return firstWidget;
},
add_rows: function (lines, field_name) {
var self = this;
if (lines.length > 0) {
self.trigger_up('add_record', {
context: [{ [field_name]: lines[0] }],
forceEditable: "bottom",
allowWarning: true,
onSuccess: function () {
self.unselectRow();
lines.shift(); // Remove the first element after adding a line
self.add_rows(lines, field_name);
}
});
}
},
_onAddRecord: function (ev) {
// we don't want the browser to navigate to a the # url
ev.preventDefault();
// we don't want the click to cause other effects, such as unselecting
// the row that we are creating, because it counts as a click on a tr
ev.stopPropagation();
var self = this;
// but we do want to unselect current row
this.unselectRow().then(function () {
var context = ev.currentTarget.dataset.context;
if (context && pyUtils.py_eval(context).open_list_view) {
// trigger add_record to get field name and model
// you do not need to trigger add_record if you pass the field name and model in context
self.trigger_up('add_record', {
context: [{}],
onSuccess: function () {
var widget = self._getFirstWidget();
var field_name = 'default_' + widget.name;
var model = widget.field.relation;
self.unselectRow();
self._rpc({
model: model,
method: 'search',
args: [[]],
}).then(
function (result) {
return new dialogs.SelectCreateDialog(self, _.extend({}, self.nodeOptions, {
res_model: model,
context: context,
title: _t("Search: add lines"),
initial_ids: result,
initial_view: 'search',
disable_multiple_selection: false,
no_create: !self.can_create,
on_selected: function (records) {
self.add_rows(records.map(product => product.id), field_name);
}
})).open();
});
}
});
} else {
self.trigger_up('add_record', { context: context && [context] });
}
});
},
});
var AddManyFieldOne2Many = fieldRegistry.map.section_and_note_one2many.extend({
/**
* We want to use our custom renderer for the list.
*
* #override
*/
_getRenderer: function () {
if (this.view.arch.tag === 'tree') {
return AddManyFieldOne2ManyRenderer;
}
return this._super.apply(this, arguments);
},
});
fieldRegistry.add('add_many_one2many', AddManyFieldOne2Many);
});
To use it define the widget attribute of the one2Many field to
<field name="field_name" widget="add_many_one2many"...
And add the following option to the tree view of the one2Many field
<create string="Open list view" context="{'open_list_view': True}"/>
Salam Ahmed
you can create a function that take you directly to product page and assigned to a button like in wizard's when you click to create a new view or get data from another view or page

Jqgrid change nav properties on callback function

i try to change the navbar properties on a jqgrid in a callback function without succes.
The grid is display afeter user is chosing a period. Depend on either the period is open or close user can or cannot edit, add, delete rows. So the navbar need to change properties dynamically.
My code look like that:
$('#mygrid').jqGrid({
// some properties of my grid that works fine
pager : '#gridpager'
});
$("#mygrid").bind("jqGridLoadComplete",function(){
$.ajax({
url: 'checkifperiodopen.php',
data: {
$("#period").val()
},
success: function(data){
if(period==='open'){
jQuery("#mygrid").jqGrid('navGrid','#gridpager',{add:false,edit:false,del:true,search:true,refresh:true});
}
if(period==='close'){
jQuery("#mygrid").jqGrid('navGrid','#gridpager',{add:true,edit:true,del:true,search:true,refresh:true});
}
}
});
});
$('#validChossenPeriod').click(function () {
ajax call to get data on choosen period
success:function(data){
$("#mygrid").jqGrid('clearGridData');
$("#mygrid").jqGrid('setGridParam', { datatype: 'local'});
$("#mygrid").jqGrid('setGridParam', { data: data});
$("#mygrid").trigger('reloadGrid');
}
});
I finally found the answer by show or hide the div that include the navgrid button:
grid = $("#mygrid");
gid = $.jgrid.jqID(grid[0].id);
var $tdadd = $('#add_' + gid);
var $tdedit = $('#edit_' + gid);
var $tddel = $('#del_' + gid);
$("#mygrid").jqGrid('navGrid','#gridpager',{add:true,edit:true,del:true,search:true,refresh:true});
condition if false =
$tdadd.hide();
$tdedit.hide();
$tddel.hide();
if true =
$tdadd.show();
$tdedit.show();
$tddel.show();
Why so complex? There is a other clear way to do this
var view_buttons = true;
if(condition_to_hide) {
view_buttons = false;
}
$("#mygrid").jqGrid('navGrid','#gridpager', { add:view_buttons, edit:view_buttons, del:view_buttons, search:true, refresh:true});

How to put edited record on first position in grid after saveing chnages?

I am using Extjs 4.2.1 and I ask myself a while how to put an edited and saved record on top of the grid after the save process has taken place. So the user can see the effect of the saved change.
I tried to put some code between the success callback method of the save method of the store. It looks like this:
store.save({
success : function(rec, op, success) {
var selectionModel = Ext.getCmp('grid').getSelectionModel();
var selection = selectionModel.getSelection();
selectionModel.select(selection);
billRecordStore.insert(0, selection);
billRecordStore.reload();
Ext.getCmp('grid').getView().refresh();
}
But i have no idea how to get the changed record on top of the table....
Any ideas and helpful posts are very welcome!
Thanks for your help in advance!
when I edit a record, I do not use the load() or reload() method.
I use only the sync () method.
This way the edited register remain highlighted in the grid.
Something like this:
var values = form.getValues();
var record = form.getRecord();
record.set(values);
var store = grid.getStore();
store.sync({
success: function(){...},
failure: function(){...}
});
When I create a new record, I have the grid records sorted so that the last inserted record is displayed on the first line.
So when it does the load (), or loadPage(1), is always selected the first row of the grid that corresponds to the last inserted record.
Edited 26/06/2015
var form = Ext.ComponentQuery.query('#formitemId')[0];
var grid = Ext.ComponentQuery.query('#griditemId')[0];
var values = form.getValues();
var record = form.getRecord();
record.set(values);
var store = grid.getStore();
store.sync({
callback: function(){
var record1 = grid.getSelectionModel().getLastSelected(record);
form.loadRecord(record1);
},
scope: this,
success: function(){
var windowInfoCNrecord = Ext.MessageBox.show({
title:'INFO',
msg: 'Success...',
closable: true,
modal: false,
iconCls: 'msg_success',
icon: Ext.MessageBox.INFO
});
},
failure: function(){
var windowInfoErrorEdit = Ext.Msg.alert({
title: 'Error',
message:'Error...!',
icon: Ext.Msg.ERROR,
button: Ext.Msg.CANCEL,
buttonText:{
cancel: 'Close'
},
});
}
}); //sync

TableView 'click' listener being ignored

I am dynamically building a TableView in my controller, which works fine: The initial table displays the initial collections data as expected.
The problem is that the TableView's 'click' event listener is ignored when I click on the table rows. I am testing in the browser, and I never even see the console event file (see comments in controller file). All relevant code snippets below:
In my alloy.js I setup a backbone collection:
function defaultTodo(name) { return {name: name, done: false}; }
function doneTodo(name) { return {name: name, done: true}; }
Alloy.Collections.todos = new Backbone.Collection();
Alloy.Collections.todos.reset([
defaultTodo('Apples'), // create not yet done todo
defaultTodo('Banana'),
defaultTodo('Paper Towels'),
defaultTodo('Broccoli'),
doneTodo('Beans'), // create already done todo
doneTodo('Water'),
doneTodo('Blueberries'),
doneTodo('Stir Fry')
])
Here is my index.js controller:
var todos = Alloy.Collections.todos;
function redrawTable() {
// clear all the old data
// See http://developer.appcelerator.com/question/49241/delete-all-rows-in-a-tableview-with-a-single-click
$.table.setData([]);
// Create and add the TableViewSections
var alreadyDone = Ti.UI.createTableViewSection({ headerTitle: "Already Done" });
var needsDoing = Ti.UI.createTableViewSection({ headerTitle: "Needs Doing" });
$.table.appendSection(needsDoing);
$.table.appendSection(alreadyDone);
// Add the todo to the appropriate sections
todos.forEach(function(todo) {
var section = todo.get('done') ? alreadyDone : needsDoing;
addEntry(todo, section);
});
// Add the click listener
// THIS LISTENER IS IGNORED ********************************
$.table.addEventListener('click', function(e) {
console.log(e);
todos.at(e.index).set('done', true);
todos.trigger('change');
});
// Helper function to add a row to a section
function addEntry(todo, section) {
var row = Ti.UI.createTableViewRow({
title: todo.get('name'),
className: "row"
});
section.add(row);
}
}
// Redraw our table each time our todos collection changes
todos.on('change', redrawTable);
// Trigger a change event to draw the initial table
todos.trigger('change');
$.index.open();
And here is index.xml view file:
<Alloy>
<Window class="container">
<Label id="test" class="header">My Grocery List</Label>
<TextField id="newItem"/>
<TableView id="table">
</TableView>
</Window>
</Alloy>
UPDATE: Working Code
In addition to the changes below, I also added onClick="markDone" to the xml.
function markDone(e) {
console.log(e.row.todo);
e.row.todo.set('done', true);
todos.trigger('change');
}
function redrawTable() {
// clear all the old data
// See http://developer.appcelerator.com/question/49241/delete-all-rows-in-a-tableview-with-a-single-click
$.table.setData([]);
var rows = [];
var done = [];
var doing = [];
// Add the todo to the appropriate sections
todos.forEach(function(todo) {
var row = Ti.UI.createTableViewRow({
title: todo.get('name'),
className: "row"
});
row.todo = todo;
todo.get('done') ? done.push(row) : doing.push(row);
});
// Create and add the TableViewSections
rows.push(Ti.UI.createTableViewSection({ headerTitle: "Needs Doing" }));
rows = rows.concat(doing);
rows.push(Ti.UI.createTableViewSection({ headerTitle: "Already Done" }));
rows = rows.concat(done);
$.table.setData(rows);
};
I created brand new project using files which you provided and eventListener is working perfectly fine. However there are couple other bugs:
Creating listener inside redrawTable() function, which is executed every time you click on something in TableView. As a result at the beginning you have one eventListener but after every click all listeners are duplicated.
Using index property in event handler to find index of Backbone model object to update. index property is indicating at which place given row was displayed in your TableView. When you are moving rows between sections their index are changing. In your case it's better to check e.row.name property and use Backbone.Collection.findWhere() method. If user can have two items with the same name on the list, then you have to create additional property to determine which object in model should be changed.
You should add rows to section before section are added to table. In your case table is very simple so instead of doing loops you can just create one simple array of objects (with title and optional header properties) and pass it to $.table.setData().
It's good to wait for postlayout event triggered on main view before triggering any custom events to make sure that the whole view was created and all objects are initiated.
Check rewrote index.js code below to see how it could be done.
var todos = Alloy.Collections.todos;
function redrawTable() {
var done = todos.where({done: true}).map(function(elem) {
return { title: elem.get('name') };
});
if (done.length > 0) {
done[0].header = 'Already Done';
}
var notdone = todos.where({done: false}).map(function(elem) {
return { title: elem.get('name') };
});
if (notdone.length > 0) {
notdone[0].header = 'Needs Doing';
}
$.table.setData( done.concat(notdone) );
}
$.table.addEventListener('click', function(e) {
todos.where({ name: e.row.title }).forEach(function(elem){
elem.set('done', !elem.get('done'));
});
todos.trigger('change'); // Redraw table
});
// Redraw our table each time our todos collection changes
todos.on('change', redrawTable);
// Trigger a change event to draw the initial table
$.index.addEventListener('postlayout', function init(){
todos.trigger('change');
// Remove eventListener, we don't need it any more.
$.index.removeEventListener('postlayout', init);
})
$.index.open();
redrawTable() could have a little more refactor but I left it so it's easier to read.
To read more about manipulating TableView check this Appcelerator documentation page.

set AfterLabelTextTpl after form render

I have a form with dynamic fields. In the afterrender event of the form I want to set the afterLabelTextTpl property. I can set this property but I can't see it change in my form. How can I achieve this?
Snippet:
listeners: {
beforerender: function () {
var fields = me.getForm().getFields();
Ext.each(fields.items, function (f, idx) {
f.afterLabelTextTpl = requiredTpl;
console.log(f.afterLabelTextTpl);
}); //eo Ext.each
}
}
Edit:
I was looking for the beforerender method
Try
f.labelEl.dom.innerHTML = "LABEL:<span style='color:red;font-weight:bold' data-qtip='Required'>*</span>";
You can not use this property after the component is already rendered.
The initRenderTpl (which makes use of the label templates) method is run only if the component is not yet rendered. Once its rendered it will not run again.
You will need to update the DOM directly.
I would recomend something like this in your form:
setRequired: function(field, index) {
field.afterLabelTextTpl = requiredTpl;
},
initComponent: function(arguments) {
var me = this;
this.on('beforeadd', function(me, field){
var fields;
if (field.isXType('fieldset')) {
fields = field.query('field');
Ext.each(fields, me.setRequired);
} else {
me.setRequired(field);
}
});
// rest of logic
me.callParent(arguments);
},