Get active_id in javascript Odoo 10 - javascript

Hello I'm trying to pass my active_id from my res.partner to the JS.
But no luck.
I tried with dataset active_id but it's always undefined.
and i can't find any solution in the docs.
Here's my JS File:
odoo.define('melax_category.my_dialog_partner', function(require){"user strict";
var core = require('web.core');
var session = require('web.session');
var qweb = core.qweb;
var mixins = core.mixins;
// var Widget = require('web.Widget');
var Model = require('web.Model');
var Dialog = require('web.Dialog');
var model_category = new Model('res.partner');
// var dataset = this.dataset;
// var active_id = dataset.ids[dataset.index];
function ActionBuildTreeBuyerPartner(parent, action){
console.log(this.id)
var dialog = new Dialog(document.body, {
title: "Categories Web Acheteur",
subtitle: '<input id="search-tree-buyer" type="text">',
size: 'big',
$content: '\
<div id="tree-buyer-container"></div>\
',
});
TREE = $('#tree-buyer-container')
dialog.open();
DESTROY_TREE($('#tree-buyer-container'))
BUILD_TREE_PARTNER_MODE(model_category, $('#tree-buyer-container'))
}
function ActionBuildTreeSellerPartner(parent, action){
var dialog = new Dialog(document.body, {
title: "Categories Web Vendeur",
// subtitle: "Tree Builder Partner Sub Title!",
size: 'big',
$content: '<div id="tree-seller-container"></div>',
});
TREE = $('#tree-seller-container')
dialog.open();
// DESTROY_TREE($('#tree-seller-container'))
// BUILD_TREE_PARTNER_MODE(model_category, $('#tree-buyer-container'))
}
core.action_registry.add("build_tree_buyer_partner", ActionBuildTreeBuyerPartner);
core.action_registry.add("build_tree_seller_partner", ActionBuildTreeSellerPartner);
});
and here's my python file where for example i'm trying to pass my active_id(self.id):
#api.multi
def build_tree_buyer_partner(self):
_logger.error(self)
# My active Id
_logger.error(self.id)
return {
'type':'ir.actions.client',
'tag': 'build_tree_buyer_partner'
}

yeah, you can get the current id by using:
var dataset = this.dataset;
var active_id = dataset.ids[dataset.index];
Python
#api.model
def _get_active_id(self):
return self._context.get('active_id')
deploy_config_id = fields.Many2one('res.partner', string='Customer', required=True, default=_get_active_id)

Related

How to save mxworkflow editor as Xml using javascript

Iam using mxWorkflow -Editor to draw workflow process
then i tried to save the workflow as xml but it is not working
i tried this
function GetXML(container)
{
var graph = new mxGraph(container);
var enc = new mxCodec();
var node = enc.encode(graph.getModel());
var model = graph.getModel();
try
{
// var graph = new mxGraph(container);
graph.model.addListener(mxEvent.CHANGE, function (sender, evt) {
var changes = evt.getProperty('edit').changes;
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change instanceof mxChildChange &&
change.change.previous == null) {
graph.startEditingAtCell(change.child);
break;
}
}
});
}
finally
{
// Updates the display
model.endUpdate();
// graph.getModel().endUpdate();
}
// Adds an option to view the XML of the graph
document.body.appendChild(mxUtils.button('View XML', function()
{
var encoder = new mxCodec();
var node = encoder.encode(graph.getModel());
mxUtils.popup(mxUtils.getXml(node), true);
}));
I've looked at few posts & documentation , but didn't find anything
use function mxUtils.getPrettyXml
var button = mxUtils.button('View XML', function() {
var encoder = new mxCodec();
var node = encoder.encode(graph.getModel());
mxUtils.popup(mxUtils.getPrettyXml(node), true);
});
document.appendChild(button);

Live update highcharts-gauge from dweet

I would like to have the gauge chart update live dweet data, which is success.
The problem is that every time a new data is pushed to the array humidityData, a new pointer is added in the gauge chart as shown here:
guage chart Though I'd like to have one live-updating-pointer instead.
Could this be done by pop() the prev data?
<script language="JavaScript">
//Array to store sensor data
var humidityData = []
<!--START-->
$(document).ready(function() {
//My Dweet thing's name
var name = 'dweetThingName'
//Humidity chart
var setupSecondChart = function() {
var chart2 = {
type: 'gauge'
};
var title = {...};
var pane = {...};
var yAxis = {...};
var tooltip = {
formatter: function () {
return '<b>' + "Humidity: " + Highcharts.numberFormat(this.y, 2) + "%";
}
};
//Series_Humidity
humiditySeries = [{
name: 'Humidity %',
data: humidityData,
tooltip: {
valueSuffix: '%'
}
}]
//Json_Humidity
var humJson = {};
humJson.chart = chart2;
humJson.title = title;
humJson.tooltip = tooltip;
humJson.xAxis = xAxis;
humJson.yAxis = yAxis;
humJson.legend = legend;
humJson.exporting = exporting;
humJson.series = humiditySeries;
humJson.plotOptions = plotOptions;
console.log("Sereies: : " +humJson)
//Container_Humidity
$('#containerHumidity').highcharts(humJson);
}
var humiditySeries = [] ....
dweetio.get_all_dweets_for(name, function(err, dweets){
for(theDweet in dweets.reverse())
{
var dweet = dweets[theDweet];
//Dweet's variables' names
val2 = dweet.content["Humidity"]
//Add the vals into created arrayDatas
humidityData.push(val2)
console.log("HumidityData: " + humidityData)
}
//Call other charts
setupSecondChart()
});
When you initialize/update your chart make sure that data array contains only one element. The dial is created for every point in this array (to visualize it on the plot).

Add Dropdown list to custom sharepoint Ribbon TAB via javascript

I am trying to add a DropDown list to a custom sharepoint ribbon bar tab using javascript, I know that this is not the recommended way and that I should use the declarative approach. I have managed to create Tabs, Groups and add buttons to them, but for some reason createing a dropdown does nothing and gives no errors.
here are the functions that I use to create the tab elements
function CreateCustomTab(tabName, tabTitle, tabGroup, tabToolTip) {
var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
var tab;
if (ribbon !== null) {
tab = new CUI.Tab(ribbon, tabName + ".Tab", tabTitle, tabToolTip, tabName + ".Tab.Command", false, '', null);
ribbon.addChild(tab);
}
return tab
}
function CreateTabGroup(tab, tabName, groupTitle, groupToolTip) {
var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
var group = new CUI.Group(ribbon, tabName + ".Tab.Group", groupTitle, groupToolTip, tabName + ".Group.Command", "test");
tab.addChild(group);
return group;
}
function CreateLayout(group, tabName, LayoutTitle) {
var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
var layout = new CUI.Layout(ribbon, tabName + ".Tab.Layout", LayoutTitle);
group.addChild(layout);
return layout;
}
function CreateDropDownList(tabName, layout, layoutTitle, listName, toolTip, listLabel, ToolTipTitle) {
var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
var section = new CUI.Section(ribbon, tabName + ".Tab.Section", 2, "Top"); //2==One Row
layout.addChild(section);
var controlProperties = new CUI.ControlProperties();
controlProperties.Command = listName + ".DropDown.Command";
controlProperties.Id = listName + ".ControlProperties";
controlProperties.TemplateAlias = "o1";
controlProperties.ToolTipDescription = toolTip;
// controlProperties.Image32by32 = (Image32by32RelativePath ? Image32by32RelativePath : '_layouts/15/images/placeholder32x32.png');
controlProperties.ToolTipTitle = ToolTipTitle;
controlProperties.LabelText = listLabel;
var dropDown = new CUI.Controls.DropDown(ribbon, listName + ".DropDown", controlProperties, ["Test1","Test2","Test3"]);
var controlComponent = dropDown.createComponentForDisplayMode('Large');
var row1 = section.getRow(1);
row1.addChild(controlComponent);
}
function CreateButton(tabName, layout, layoutTitle, buttonName, toolTip, buttonText, ToolTipTitle, Image32by32RelativePath) {
var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
var section = new CUI.Section(ribbon, tabName + ".Tab.Section", 2, "Top"); //2==One Row
layout.addChild(section);
var controlProperties = new CUI.ControlProperties();
controlProperties.Command = buttonName + ".Button.Command";
controlProperties.Id = buttonName + ".ControlProperties";
controlProperties.TemplateAlias = "o1";
controlProperties.ToolTipDescription = toolTip;
controlProperties.Image32by32 = (Image32by32RelativePath ? Image32by32RelativePath : '_layouts/15/images/placeholder32x32.png');
controlProperties.ToolTipTitle = ToolTipTitle;
controlProperties.LabelText = buttonText;
var button = new CUI.Controls.Button(ribbon, buttonName + ".Button", controlProperties);
//var controlComponent = new CUI.ControlComponent(ribbon, buttonName + ".MenuItem.Button", "Large",button)
var controlComponent = button.createComponentForDisplayMode('Large');
var row1 = section.getRow(1);
row1.addChild(controlComponent);
}
and here is how these are called
SP.SOD.executeOrDelayUntilScriptLoaded(function () {
var pm = SP.Ribbon.PageManager.get_instance();
pm.add_ribbonInited(function () {
var tab = CreateCustomTab("SomeTab", "Some Tab", "View Format", "Use this tab");
var group = CreateTabGroup(tab, "SomeTab", "View Format", "Switch between");
var layout = CreateLayout(group, "SomeTab", "SomeTabLayout");
CreateButton("SomeTab", layout, "SomeTabLayout", "ListViewButton", "Switch to list view, this displays a grid with the items ungrouped in an editable table!", "List View", "Table List View");
CreateButton("SomeTab", layout, "SomeTabLayout", "HierarchyButton", "Switch to tree view, this displays a grid with the items grouped in a parent child relationship!", "Tree View","Hierarchy view");
var hierarchyEditGroup = CreateTabGroup(tab, "SomeTab", "Hierarchy Edit", "Edit hierarchy");
var hierarchyLayout = CreateLayout(hierarchyEditGroup, "SomeTab", "HierarchyLayout");
CreateButton("SomeTab", hierarchyLayout, "HierarchyLayout", "EditHierarchyButton", "Edit current hierarchy", "Edit Tree", "Edit current hierarchy");
var ViewsGroup = CreateTabGroup(tab, "ISSQeueuListTab", "Views", "Change data views");
var ViewsLayout = CreateLayout(ViewsGroup, "SomeTab", "ViewsLayOut");
CreateDropDownList("SomeTab", ViewsLayout, "Current View", "DataViewList", "Change the the current view from the available public and private views", "Current View", "View Selection");
group.selectLayout("SomeTabLayout");
hierarchyEditGroup.selectLayout("HierarchyLayout");
SelectRibbonTab("SomeTab.Tab", true);
SelectRibbonTab("Ribbon.Read", true);
$("#Ribbon\\.WebPartPage-title").hide();
var Commands = [];
Commands.push({ name: "SomeTab.Tab.Command", enabled: true, handler: function (a, b, c) { } });
Commands.push({ name: "SomeTab.Group.Command", enabled: true, handler: function (a, b, c) { } });
Commands.push({ name: "DataViewList.DropDown.Command", enabled: true, handler: function () { }});
Commands.push({
name: "HierarchyButton.Button.Command", enabled: true, handler: function (CommandID, properties, seq) {
AppFrame.contentWindow.postMessage("ShowTreeView()", "*");
var Ribbon = SOMESpAppSPPage.get_instance();
var button = Ribbon.GetCommand("EditHierarchyButton.Button.Command");
button.enabled = true;
RefreshCommandUI();
}
});
Commands.push({
name: "ListViewButton.Button.Command", enabled: true, handler: function (CommandID, properties, seq) {
AppFrame.contentWindow.postMessage("ShowListView()", "*")
var Ribbon = SOMESpAppSPPage.get_instance();
var button = Ribbon.GetCommand("EditHierarchyButton.Button.Command");
button.enabled = false;
RefreshCommandUI();
}
});
Commands.push({
name: "EditHierarchyButton.Button.Command", enabled: false, handler: function (CommandID, properties, seq) {
AppFrame.contentWindow.postMessage("ShowHierarchyEdit()", "*");
}
});
SOMESpAppSPPage.initializePageComponent(Commands);
});
var ribbon = null;
try {
ribbon = pm.get_ribbon();
}
catch (e) { }
if (!ribbon) {
if (typeof (_ribbonStartInit) == "function")
_ribbonStartInit(_ribbon.initialTabId, false, null);
}
else {
CreateCustomTab("SomeTab", "SOMESpApp List", "SOMESpAppTabGroup", "Use this tab to intertact with the ISS Queue");
}
}, "sp.ribbon.js");
I had to change some of the names of the variables, but this is exact code I am using. the buttons and tabs work but the Drop down will not any one have an idea.
Change the TemplateAlias for the control in "function CreateDropDownList" from "o1" to "o2" and I speculate this will start working:
controlProperties.TemplateAlias = "o2";

How to generate snapshot of amCharts without visiting browser

I am using amCharts library on my website. On the side block I am displaying chart snapshots (thumbnails) and if clicked it goes to the chart itself. To display these snapshots they should be pre-generated but only way I can do it when I am on a chart page. Also I need to update these snapshots by schedule every day. I need a way (if possible) to generate these snapshots without visiting a webpage, ideally through command line.
At the moment I am saving charts as images on the server-side:
<script src="/static/amcharts/amcharts.js" type="text/javascript"></script>
<script src="/static/amcharts/serial.js" type="text/javascript"></script>
<script src="/static/amcharts/amstock.js" type="text/javascript"></script>
<script src="/static/amcharts/exporting/amexport.js" type="text/javascript"></script>
<script src="/static/amcharts/exporting/rgbcolor.js" type="text/javascript"></script>
<script src="/static/amcharts/exporting/canvg.js" type="text/javascript"></script>
<script src="/static/amcharts/exporting/filesaver.js" type="text/javascript"></script>
<script>
var cdata = {{ chartData|safe }};
AmCharts.ready(function () {
generateChartData();
createStockChart();
});
var chartData = [];
function generateChartData() {
for (var i = 0; i < cdata.length; i++)
{
chartData.push({
date: new Date(cdata[i]["date"]),
value: cdata[i]["value"],
volume: cdata[i]["volume"]
});
}
}
var chart;
function createStockChart() {
chart = new AmCharts.AmStockChart();
chart.exportConfig = {
menuItems: []
};
chart.addListener('rendered', function (event) {
chart.AmExport.output({format:"png", output: 'datastring'},
function(data) {
$.post("/charts/save_chart_snapshot/", {
imageData: encodeURIComponent(data)
});
});
});
chart.pathToImages = "/static/amcharts/images/";
var categoryAxesSettings = new AmCharts.CategoryAxesSettings();
categoryAxesSettings.minPeriod = "DD";
chart.categoryAxesSettings = categoryAxesSettings;
// DATASETS //////////////////////////////////////////
var dataSet = new AmCharts.DataSet();
dataSet.color = "#9cc11a";
dataSet.fieldMappings = [{
fromField: "value",
toField: "value"
}, {
fromField: "volume",
toField: "volume"
}];
dataSet.dataProvider = chartData;
dataSet.categoryField = "date";
// set data sets to the chart
chart.dataSets = [dataSet];
// PANELS ///////////////////////////////////////////
// first stock panel
var stockPanel1 = new AmCharts.StockPanel();
stockPanel1.showCategoryAxis = false;
stockPanel1.title = "Value";
stockPanel1.percentHeight = 70;
// graph of first stock panel
var graph1 = new AmCharts.StockGraph();
graph1.valueField = "value";
graph1.type = "smoothedLine";
graph1.lineThickness = 2;
graph1.bullet = "round";
graph1.bulletBorderColor = "#FFFFFF";
graph1.bulletBorderAlpha = 1;
graph1.bulletBorderThickness = 3;
stockPanel1.addStockGraph(graph1);
// create stock legend
var stockLegend1 = new AmCharts.StockLegend();
stockLegend1.valueTextRegular = " ";
stockLegend1.markerType = "none";
stockPanel1.stockLegend = stockLegend1;
// second stock panel
var stockPanel2 = new AmCharts.StockPanel();
stockPanel2.title = "Volume";
stockPanel2.percentHeight = 30;
var graph2 = new AmCharts.StockGraph();
graph2.valueField = "volume";
graph2.type = "column";
graph2.cornerRadiusTop = 2;
graph2.fillAlphas = 1;
stockPanel2.addStockGraph(graph2);
// create stock legend
var stockLegend2 = new AmCharts.StockLegend();
stockLegend2.valueTextRegular = " ";
stockLegend2.markerType = "none";
stockPanel2.stockLegend = stockLegend2;
// set panels to the chart
chart.panels = [stockPanel1, stockPanel2];
// OTHER SETTINGS ////////////////////////////////////
var scrollbarSettings = new AmCharts.ChartScrollbarSettings();
scrollbarSettings.graph = graph1;
scrollbarSettings.updateOnReleaseOnly = true;
scrollbarSettings.usePeriod = "WW"; // this will improve performance
scrollbarSettings.position = "top";
chart.chartScrollbarSettings = scrollbarSettings;
var cursorSettings = new AmCharts.ChartCursorSettings();
cursorSettings.valueBalloonsEnabled = true;
chart.chartCursorSettings = cursorSettings;
// PERIOD SELECTOR ///////////////////////////////////
var periodSelector = new AmCharts.PeriodSelector();
periodSelector.position = "top";
periodSelector.dateFormat = "YYYY-MM-DD";
periodSelector.inputFieldWidth = 150;
periodSelector.periods = [{
period: "DD",
count: 1,
label: "1 day"
}, {
period: "DD",
count: 2,
label: "2 days"
}, {
period: "DD",
count: 5,
label: "5 days"
}, {
period: "DD",
count: 12,
label: "12 days"
}, {
period: "MAX",
label: "MAX"
}];
chart.periodSelector = periodSelector;
var panelsSettings = new AmCharts.PanelsSettings();
panelsSettings.usePrefixes = true;
chart.panelsSettings = panelsSettings;
chart.write('chartdiv');
}
</script>
And this is how I save it on server-side:
def save_chart_snapshot(request):
if request.POST:
data = urllib.unquote(request.POST['imageData'])
imageData = data.split(';')[1].split(',')[1]
filename = "static/temp/charts/snapshots/" + request.POST['isin'] + ".png"
if not os.path.exists(filename):
try:
fh = open(filename, "wb")
fh.write(imageData.decode('base64'))
except IOError:
logger.error("Cannot find file or read data: " + filename)
else:
fh.close()
logger.debug("Chart snapshot is generated: " + filename)
return HttpResponse("done")
This is a bit late but I ran into a similar situation recently where I needed export report capabilities at the server-side and wanted to use amcharts.js. As I was exploring, I found that it is possible to run amcharts using puppeteer that provides a headless browser.
Below article explains it in detail:
https://www.amcharts.com/docs/v4/tutorials/automating-report-generation-using-puppeteer/
There's also a downloadable example here.
Hope this helps someone looking for similar functionality.
You can probably automate this process by visiting your charts page using a WebKit "browser" in a virtual framebuffer using a tool like uzbl-core or netserf or wkhtmltopdf or similar (all of those support JS).
Then just add the above task to a script in a cron job that's kicked-off every day.
Technically you're still visiting the page in a browser with this solution, but at least it can be reasonably automated from a headless server in a datacenter.

Javascript reloading list each time event is fired - Google Drive Realtime API

I have a collaborative list in google's realtime api, which is displayed in a select tab.
Currently I have this.
var managment = (function($) {
var deadline1 = undefined;
// the name of the authenticated user - once authentication has succeeded
var username = "unkown";
var realtimeLoader = undefined;
var initializeModel = function(model) {
var deadline1 = model.createList();
model.getRoot().set('deadline1', deadline1);
}
var onProjectsLoaded = function(doc) {
deadline1 = doc.getModel().getRoot().get('deadline1');
deadline1.addEventListener(gapi.drive.realtime.EventType.VALUES_ADDED, updateUi);
deadline1.addEventListener(gapi.drive.realtime.EventType.VALUES_REMOVED, updateUi);
deadline1.addEventListener(gapi.drive.realtime.EventType.VALUES_SET, updateUi);
$("#inviteId").removeAttr("disabled");
var inviteButton = $("#invite");
inviteButton.removeAttr("disabled");
inviteButton.click(inviteUser);
var saveButton = $("#save");
saveButton.click(addProject);
var updateButton = $("#demoListSet");
updateButton.click(onSetItems);
var selector = $("#demoListInput");
selector.change(onSelect);
}
var addProject = function() {
var title = $("#title").val();
var date = $("#datepicker").val();
var priority = $("#priority").val();
var description = $("#description").val();
deadline1.push( {
title : title,
date : date,
description : description,
priority : priority,
} );
}
var updateUi = function(evt) {
/*$("#demoListInput").empty();*/
var projectList = $("#demoListInput");
for (var index in evt.values) {
var deadline1 = evt.values[index];
var newOption = $("<option>").val(deadline1.title).text("Title: " + deadline1.title + " Date:" + deadline1.date + " Priority: " + deadline1.priority)
}
projectList.append(newOption);
}
My problem is with the updateUI function.
The list is called deadline1. When an item is added to the list, it updates the list but the view of this list in the select tab, This is because I am only looping through the evt.values when displaying new items. What I would like to do it delete the current view of the list each time an event is fired (see the line currently in comment), however, every time I try and call deadline1 to loop through the length of it, it comes back saying deadline1 is undefined. Is there a way to get around this? Thank you.

Categories