I have the following code:
sql = "select Board_Name AS 'Board Name', COUNT(Board_Name) AS 'Count' from dbo.TABLE GROUP BY Board_Name"
result = client.execute(sql)
result.each do |row|
binfo = [ label: row['Board Name'], value: row['Count'] ]
send_event('ticketsbyboard', { items: binfo })
end
I'm trying to get all of the rows passed to the send_event as one array, instead of just one row at a time.
Try a map:
binfo = result.map do |row|
{ label: row['Board Name'], value: row['Count'] }
end
send_event('ticketsbyboard', { items: binfo })
If your result object doesn't respond directly to map, just use result.to_a.map
Related
I like to change the Type field drop down option depending on the inputs of Year and Level fields.
I am able to trigger an event when Level is change.
But how do I get the value of the Year field?
Portion of the code are as follows
colModel:[
{name:'Year',index:'Year', width:70,sortable:false,editable:true,align:'center',editoptions:{size:15, maxlength:4}, formoptions:{ rowpos:1, label: "Year (*)"},editrules:{required:true}},
{name:'Level',index:'Level', width:70,sortable:false,editable:true,align:'center',edittype: "select", editoptions: { value: '1:1;2:2;3:3;4:4;5:5;6:6', defaultValue:'1', dataEvents : [
{
'type' : 'change',
'fn' : function ( el ) {
// get the newly selected value from the user
var levelz = $(el.target).val(), yearz ;
var row = $(el.target).closest('tr.jqgrow');
var rowid = row.attr('id');
//yearz = ??
if (parseInt(levelz)==5 || parseInt(levelz)==6)
{
if (parseInt(yearz)>2017)
{
$("#gridmain").jqGrid('setColProp','Term', {editoptions: { value: '1:Sem 1;4:Sem 2;6:EY;9:OVR', defaultValue:'Sem 1'}} );
}else{
$("#gridmain").jqGrid('setColProp','Term', {editoptions: { value: '', defaultValue:''}} );
}
}else{
$("#gridmain").jqGrid('setColProp','Term', {editoptions: { value: '1:TA1/CT1;2:TA2-before 2013;3:MY/TA2/CT2;4:TA3/CT3;5:TA4-before 2013;6:EY/TA4/CT4;9:OVR;D:CW1;E:CW2;F:CW3;G:CW4', defaultValue:'TA1'}} );
}
}
}]}, formoptions:{ rowpos:2, label: "Level (*)"},editrules:{required:true}},
{name:'Term',index:'Term', width:70, sortable:false,editable: true,align:'center',edittype: "select", editoptions: { value: '1:TA1/CT1;2:TA2-before 2013;3:MY/TA2/CT2;4:TA3/CT3;5:TA4-before 2013;6:EY/TA4/CT4;9:OVR;D:CW1;E:CW2;F:CW3;G:CW4', defaultValue:'TA1'}, editrules: { required: true }, formoptions:{ rowpos:3, label: "Type"}},
The codes are from piecing together what I read from google search...
I face 2 issues:
1) I don't know how to get the Year value
2) The drop down option list doesn't seems to change. - hmm it seems that if I close the edit form and open again, the Type field drop down option changes. What I need is to change the option on the fly - wonder how this can be done...
After much googling, managed to get the ans from Oleg's post as shown here
Also from his example, I derive the year value:
var yearz = $("#Year.FormElement", form[0]).val();
I have a button in a form that when clicked is supposed to update the current model mrl with data from the spray.action model. Then I do further processing but it raises the error
ValueError("Expected singleton: %s" % self) ValueError: Expected singleton: spray.action(1, 2)
#api.multi
def mrlCreateSprayRecords(self):
spray_ids = []
vals = []
spray_obj = self.env['spray.action'].search([])
print("spray_obj \n\n\n\t %s ", spray_obj)
for obj in spray_obj:
print("Spray Action Objects \n\n %s \n\t ", obj)
vals = {
'ref': obj.ref,
'farm': obj.farm.farm,
'block': obj.block.block,
'valves': obj.valves.valve,
}
print("Spray Action Data Browse , \n\n\t %s ", vals)
res = super(Mrl, self).create(vals)
res.update(vals)
print("object in mrlCreateSprayRecords \n\n\t %s", res)
return {
'name': 'Update Mrl Operations',
'type': 'ir.actions.act_window',
'view_type': 'form',
'view_mode': 'form',
'res_model': 'mrl',
'views': [(spray_obj.id, 'form')],
'view_id': spray_obj.id,
# 'target': 'new',
'res_id': self.id,
'context': self.env.context,
}
I think you are getting the error in the row 'view_id': spray_obj.id, you must write the view id there. The spray_obj recordset has many record, so you cannot use it like that (spray_obj.id). You can also remove the view_id parameter in order to user the default view.
#api.multi
def mrlCreateSprayRecords(self):
self.ensure_one()
spray_obj = self.env['spray.action'].search([]) # recordset of all records of the model????
for obj in spray_obj:
vals = {
'ref': obj.ref,
'farm': obj.farm.farm,
'block': obj.block.block,
'valves': obj.valves.valve,
}
self.create(vals)
view_id = self.env.ref('module.xml_view_id').id
return {
'name': 'Update Mrl Operations',
'type': 'ir.actions.act_window',
'view_type': 'form',
'view_mode': 'form',
'res_model': 'mrl',
'view_id': view_id,
'res_id': self.id,
'context': self.env.context,
}
I have added self.ensure_one() because res_id has to be only one id as well.
I have remove the res.update(vals) line because it does not make any sense to me haha
More things
Instead of print you should use the logger:
import logging
_logger = logging.getLogger(__name__)
_logger.info('Hello')
Instead the line res = super(Mrl, self).create(vals) I think you should use this one
res = self.create(vals) # if you are in the mrl model
In short you get this kind of error when you acces a field direclty of a recordSet that contains more than one record.
You performed a search on the spray.action that search returnd 2 record (1, 2)
So when you do spray_obj.id odoo will be confused what id he should return 1 or 2. And here odoo throw this error.
So dont access a field a search result, or a x2many fiels they may have more than one record inside.
#ChesuCR has improved your code and corrected it
I'm using this to add a bunch of records to the elasticcache index:
def self.index_trends(trend_hashes)
formatted_trends = trend_hashes.map do |trend_hash|
{
index: {
_index: 'trends',
_type: 'trend',
_id: trend_hash["id"],
data: trend_hash
}
}
end
elasticsearch.bulk({
body: formatted_trends
})
end
Now I need to update a record (given its id). I want to just add one key-val to the data hash, not replace the whole state. How can I do this using elasticsearch-ruby?
I dont know how to do this with ruby, but in ES there is update API.
Which look like this
POST test/type1/1/_update
{
"script" : "ctx._source.new_field = \"value_of_new_field\""
}
From example with ruby should be
client.update index: 'myindex', type: 'mytype', id: '1',
body: { script: 'ctx._source.tags += tag', params: { tag: 'x' } }
I am trying to upload products via ruby (not with rails). I have uploaded 100 + products via API, although I cannot upload a product with more than one option value. Even if I assign three option values, it will not populate the other two.
Here is the script:
require 'shopify_api'
require 'open-uri'
require 'json'
begin_time = Time.now
shop_url = "*https*(yes I know the * are their)://-YouWish-:-I'dShareNakedPics-#dev-tactical.myshopify.com/admin/products.json"
include ShopifyAPI
ShopifyAPI::Base.site ="*https*://-YouWish-:-I'dShareNakedPics-#dev-tactical.myshopify.com/admin/"
raw_product_data = JSON.parse(open('omg.json') {|f| f.read }.force_encoding('UTF-8'))
raw_product_data_size = raw_product_data.size
puts '========================================================================='
puts "#{raw_product_data_size} seconds till explosion. assistance
needed..."
puts '-------------------------------------------------------------------------'
single_product_begin_time = Time.now
# Create new product
new_product = ShopifyAPI::Product.new
new_product.title = "Variants Suck"
new_product.body_html = "So"
new_product.product_type = "Much"
new_product.vendor = "Please"
new_product.tags = "Help"
new_product.variants = [
{
"option1" => "This One Works",
"option2" => "Lost Cause",
"option3" => "/wrist",
"postion" => "1",
"price" => "10.00",
"sku" => "12345",
"inventory_management" => "shopify",
} ]
new_product.images = [
{
src: "https://cdn.shopify.com/s/files/1/0750/0067/files/Pro-Tapes.jpg?11603036243532110652"
} ]
new_product.save
creation_time = Time.now - single_product_begin_time
puts '-------------------------------------------------------------------------'
puts "Sorry About the mess babe, atleast it only took #{begin_time - Time.now} minutes."
puts '========================================================================='
I am testing this on a dev shop, but I am attempting to rebuild something previously built on magento, where I can have people convert my csv data entry to json, then array/hash the data.
Please don't link me to the (shopify)/API info. I have read it. I don't understand the formatting of it. If I were to shopify-cli console, and paste the api example in irb, it won't execute properly. I am sure I am just lacking the required knowledge of working with APIs, although if you can help me just slightly it would be much appreciated.
This node.js script adds item with variants. The difference here is that it includes a list of options on the product element. Note that if you comment out the options element then I get the same problem you are reporting in that only the first option is imported.
var https = require('https');
var cred = new Buffer(privateAppAPIKey +":"+ privateAppPassword).toString('base64');
var headers = {Authorization: "Basic "+cred, "Content-Type": "application/json"};
var options = {
host: 'kotntest1.myshopify.com',
port: 443,
path: '/admin/products.json',
method: 'POST',
headers: headers
};
// Setup the request. The options parameter is
// the object we defined above.
var req = https.request(options, function(res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function(data) {
responseString += data;
console.log(data);
});
res.on('end', function() {
var resultObject = JSON.parse(responseString);
});
});
req.on('error', function(e) {
// TODO: handle error.
console.log(e);
});
var product = {
product:{
title:'My First Test Product',
options : [
{name : "First"},
{name : "Second"},
{name : "Third"}
],
variants: [
{
title:'v1',
option1: 'Red',
option2: "Honda",
option3: 'Prelude'
},
{
title:'v2',
option1 :'Blue',
option2 :'Ford',
option3 :'Escort'
}
]
}
};
req.write(JSON.stringify(product));
req.end();
I used #bknights code as a reference and got my code to work in ruby. You just have to set the option names on the product level first:
new_product = ShopifyAPI::Product.new
new_product.options = [{"name" => "Size"}, {"name" => "Color"}]
Then adding variants work:
new_product.variants = [
{
"option1" => "S",
"option2" => "Black",
"position" => "1",
"price" => "10.00"
},
{
"option1" => "M",
"option2" => "Black",
"position" => "1",
"price" => "10.00"
}
]
new_product.save
I'm trying to create a List in Dashing and I've managed to bring in my external JSON, but I'm having problems iterating through it to create the new JSON array to post it out to my List widget. Here's the current code:
require 'rubygems'
require 'json'
require 'pp'
name_list = Hash.new({ value: 0 })
SCHEDULER.every '10s' do
json = File.read('/Users/research/inoutdash/sweet_dashboard_project/jobs/list.json')
response = JSON.parse(json)
name_list[response] = {label: response.keys, value: response.values}
send_event('whosHere', { items: name_list.values })
puts response.keys
puts response.values
end
Here's my JSON file it's reading from:
{
"Mike":"Here",
"Jon": "Out"
}
The output to the widget currently looks like this:
MikeJon Here,Out
How to I properly iterate through the parsed json response and pass it to the send_event?
Just in reply to Matt's question:
So what I need is one 'whosHere' event with all the values from the JSON file formatted for the List widget - which needs JSON formatted as label: X, value: Y.
So what I need it to do is format it as a json array with:
label: "Mike", value: "Here"
label: "Jon", value: "Out"
where now it's storing as:
label: Mike,Jon, value:Here,out
You can use collect to accomplish this. It iterates over a collection and returns an Array where each element is the result of a block.
name_list = response.collect { |(name, status)| { :label => name, :value => status } }
# [{:label=>"Mike", :value=>"Here"}, {:label=>"Jon", :value=>"Out"}]