Rails jqgrid column background color dynamic - ruby-on-rails

I'm using jqgrid with ruby on rails and as per my requiremnet in jqgrid listing page i need background color as dynamic for a particular column values.
Here is my code for helper,
include JqgridsHelper
def colors_jqgrid
options = {:on_document_ready => true, :html_tags => false}
grid = [{
:sortable => true,
:url => '/colors',
:datatype => 'json',
:mtype => 'GET',
:colNames => ['colors_id','ID','External ID','name','Color Swatch','Actions'],
:colModel => [
{ :name => 'colors_id', :index => 'colors_id',:hidden => true},
{ :name => 'ID', :index => 'ID', :width => 180 ,:searchoptions => {
:sopt => ['eq','ne','bw','ew','cn'],
}},
{ :name => 'External ID', :index => 'color_id',:search=>false, :width => 180 ,:searchoptions => {
:sopt => ['eq','ne','bw','ew','cn'],
} },
{ :name => 'name', :index => 'name', :width => 180 ,:searchoptions => {
:sopt => ['eq','in'],
} },
{ :name => 'color_id', :index => 'Color Swatch',:search=>false, :width => 180},
{name:'Actions',index:'action',align:'center',sortable:false,formatter: 'function(cellvalue, options, rowObject) {
edit = "<span class=\"ui-icon ui-icon-pencil\" title=\"Edit\" style= \"cursor:pointer;float:left;\" onclick=\"window.location.href = '"'colors/edit?id="'"+options.rowId+"'"'"';\"></span>";
edit += "<span class=\"ui-icon ui-icon-trash\" title=\"Delete\" style= \"cursor:pointer;\" onclick=\"jQuery.fn.fmatter.rowactions.call(this,'"'del'"');\"></span>";
return edit;
}'.to_json_var },
],
:editurl => '/colors/grid_update',
:pager => '#colors_pager',
:rowNum => 10,
:rowList => [10, 20, 30],
:caption => 'Colors',
:autowidth => true,
:navigator=>true,
:excel=>true,
:viewrecords=>true,
:ondblClickRow => "function(rowId, iRow, iCol, e) { window.location = 'colors/edit?id='+ rowId; }".to_json_var
}]
pager = [:navGrid, "#colors_pager", { :del => false,:search=>true,:edit => false,:add => false},
{:closeAfterEdit => true, :closeOnEscape => true}, {}, {}, {:multipleSearch => true}, {}]
options = [:navButtonAdd, "#colors_pager", {caption: "Columns", title: "Reorder Columns", onClickButton: "function() { jQuery('#colors_list').jqGrid('columnChooser'); }".to_json_var }]
jqgrid_api 'colors_list', grid, pager, options
end

Add following line anywhere in grid variable section.
:afterInsertRow => "function(rowId, data) { $(\"#colors_list\").setCell(rowId, 'color_id', '', {'background-color':'#'+data.color_id }); }".to_json_var
it requires 2 parameters. First is rowId which is identifier of row. second is data which is content of that row with all fields. so i used data.color_id for fetching color code which u want to use to set background color.

Related

Rails replace one hash by another if keys exists

I don't know what's going on but I've got two hashes:
first_hash
{
'Ids' => ['string_first_hash'],
'Description' =>
{
'Url' => 'some_path',
'EventCallback' => {
'Url' => 'some_path',
'WhiteList' => ['string'],
},
'Steps' => [{
'OrderIndex' => 1,
'Recipients' => [
{
'Email' => 'email#first.hash',
'FirstName' => 'first_hash_name',
'LastName' => 'first_hash_last_name',
'LanguageCode' => 'en',
},
],
}],
},
}
And the second one:
template_hash
{
'Ids' => ['template_stirng'],
'Description' => {
'Name' => 'Template_name',
'Subject' => 'template_subject',
'Finish' => false,
'Steps' => [{
'OrderIndex' => 1,
'Recipients' => [
{
'Email' => 'Placeholder =>',
'FirstName' => '',
'LastName' => '',
'LanguageCode' => '',
'DisableEmail' => false,
'IdentificationMethods' => [],
},
],
'RecipientType' => 'Signer',
}],
},
}
Now I want to add first_hash to the template_hash and override only those key/value which exist in both and leave the rest from second_hash unchanged (should be added in the result). I thought all I want to do is:
test = first_hash.merge(template_hash)
But the result is surprising - nothing change, it prints second hash unchanged:
> test
{"SspFileIds"=>["7fcf6021-386d-4f31-a871-a89afb8fb36e"],
"SendEnvelopeDescription"=>
{"Name"=>"1 Recipient",
"EmailSubject"=>"Please sign the enclosed envelope",
"EmailBody"=>"Dear #RecipientFirstName# #RecipientLastName#\n\n#PersonalMessage#\n\nPlease sign the envelope #EnvelopeName#\n\nEnvelope will expire at #ExpirationDate#",
"DisplayedEmailSender"=>"",
"EnableReminders"=>true,
"FirstReminderDayAmount"=>5,
"RecurrentReminderDayAmount"=>3,
"BeforeExpirationDayAmount"=>3,
"DaysUntilExpire"=>28,
"StatusUpdateCallbackUrl"=>"",
"LockFormFieldsAtEnvelopeFinish"=>false,
"Steps"=>
[{"OrderIndex"=>1,
"Recipients"=>
[{"Email"=>"Placeholder:",
"FirstName"=>"",
"LastName"=>"",
"LanguageCode"=>"",
"DisableEmail"=>false,
"AddAndroidAppLink"=>false,
"AddIosAppLink"=>false,
"AddWindowsAppLink"=>false,
"AllowDelegation"=>true,
"AllowAccessFinishedWorkstep"=>false,
"SkipExternalDataValidation"=>false,
"AuthenticationMethods"=>[],
"IdentificationMethods"=>[]}],
"RecipientType"=>"Signer"}]}}
What's going on, am I misunderstand something? I'm using Rails 7 and Ruby 3.
[EDIT]
expected_result
{
'Ids' => ['string_first_hash'],
'Description' => {
'Name' => 'Template_name',
'Subject' => 'template_data_string',
'Finish' => false,
'Steps' => [{
'OrderIndex' => 1,
'Recipients' => [{
'Email' => 'email#first.hash',
'FirstName' => 'first_hash_name',
'LastName' => 'first_hash_last_name',
'LanguageCode' => 'en',
}],
'RecipientType' => 'Signer',
}],
'Url' => 'some_path',
'EventCallback' => {
'Url' => 'some_path',
'WhiteList' => ['string'],
},
},
}
Have you tried using deep_merge? https://apidock.com/rails/Hash/deep_merge
What you want is
test = first_hash.deep_merge(second_hash)

Why am I getting singleton cant be dumped err?

When I try to add a variable value into session, I am getting singleton cant be dumped err.
Here is the value in the varibale
[
[0] {
:id => "574ecb43a7a5bb44c000443b",
:_id => "574ecb43a7a5bb44c000443b",
:active => true,
:capabilities => {
:network_connections => [
[0] {
:type => "ethernet-wan",
:name => "wan"
},
[1] {
:type => "ethernet-lan",
:name => "lan"
},
[2] {
:type => "wifi",
:name => "wlan"
},
[3] {
:type => "cellular",
:name => "wwan"
}
]
},
:commander_ids => [],
:created_at => "2016-05-11T15:46:12+00:00",
:deleted_at => nil,
:firmware_upgradable => true,
:ingestor_ids => [],
:last_known_translator_port => nil,
:long_description => "this is a liong desc",
:manufacturer => "test_sushant",
:model => "sushant_test",
:name => "zxc",
:parent_gateway_data_source_type_id => nil,
:rule_ids => [],
:software => "qwe",
:translator => "edge",
:type => "asd",
:updated_at => "2016-05-11T15:46:12+00:00",
:user_id => "572adee5a7a5bb320b000852"
},
The variable is an array of objects. I do not know why this is causing an err.

What is causing Aws::CloudFront::Errors::MalformedInput: Unexpected list element termination

I'm attempting to create a new AWS Cloudfront Distribution with v2 of the ruby AWS SDK and cannot figure out what is causing this error.
Aws::CloudFront::Errors::MalformedInput: Unexpected list element termination
client = Aws::CloudFront::Client.new
resp = client.create_distribution({
distribution_config: {
caller_reference: Time.now.to_i.to_s,
:aliases => {
:quantity => 1,
:items => [Name.generate_name]
},
:origins => {
:quantity => 1,
:items => [
{
:id => "#{self.id}-distribution",
:domain_name => "example-static.s3-website-us-east-1.amazonaws.com",
:origin_path => "/#{self.id}",
:custom_headers => {
:quantity => 0,
:items => []
},
:custom_origin_config => {
:http_port => 80,
:https_port => 443,
:origin_protocol_policy => "http-only",
:origin_ssl_protocols => {
:quantity => 3,
:items => ["TLSv1","TLSv1.1","TLSv1.2"]
}
}
}
]
},
:default_cache_behavior => {
:target_origin_id => "Custom-example-static.s3-website-us-east-1.amazonaws.com/#{self.id}",
:forwarded_values => {
:query_string => true,
:cookies => {
:forward => "none"
},
:headers => {
:quantity => 1,
:items => ["Origin"]
}
},
:trusted_signers => {
:enabled => false,
:quantity => 0
},
:viewer_protocol_policy => "allow-all",
:min_ttl => 0,
:allowed_methods => {
:quantity => 3,
:items => ["HEAD","GET","OPTIONS"],
:cached_methods => {
:quantity => 3,
:items => ["HEAD","GET","OPTIONS"]
}
},
:smooth_streaming => false,
:default_ttl => 86400,
:max_ttl => 31536000,
:compress => true
},
:cache_behaviors => {
:quantity => 0
},
:custom_error_responses => {
:quantity => 0
},
:comment => "",
logging: {
enabled: true, # required
include_cookies: false, # required
bucket: "example-logs", # required
prefix: "#{self.id}", # required
},
:price_class => "PriceClass_100",
:enabled => true,
:restrictions => {
:geo_restriction => {
:restriction_type => "none",
:quantity => 0
}
}
}
})
I compared the results I got back from an existing instance with
client = Aws::CloudFront::Client.new(:http_wire_trace => true)
resp = client.get_distribution_config({
:id => '<ID>'
})
Changing the payload from
:custom_headers => {
:quantity => 0,
:items => []
},
to
:custom_headers => {
:quantity => 0
},
seemed to fix the same error message for me.

Active resource param serialization issue

I'm trying to pass the following ruby hash into an active resource(3.0.9) find(:from) call.
my_hash = {
:p => {:s => 100, :e => 2},
:k => "blah",
:f => [
{
:fl => :bt,
:tp => :trm,
:vl => "A::B"
},
{
:fl => :jcni,
:tp => :trm,
:vl => [133, 134]
},
{
:mnfl => :bmns,
:mxfl => :bmxs,
:tp => :rfstv,
:vl => 1e5
},
{
:fl => :bpo,
:tp => :rftv,
:op => :eta,
:vl => 1.months.ago.strftime("%Y-%m-%d")
}
]
}
Resource.find_by_x_and_y(:all, :from => :blah, params: my_hash)
On the server side action, when I print the params hash, its all messed up. ( last 3 hashes in the array mapped to :f )
{
"f" => [
{
"fl" => "bt",
"tp" => "trm",
"vl" => "A::B"
},
{
"fl" => "jcni",
"tp" => "trm",
"vl" => [
"133",
"134"
],
"mnfl" => "bmns",
"mxfl" => "bmxs"
},
{
"tp" => "rfstv",
"vl" => "100000.0",
"fl" => "bpo",
"op" => "eta"
},
{
"tp" => "rftv",
"vl" => "2013-01-25"
}
],
"k" => "blah",
"p" => {
"e" => "2",
"s" => "100"
},
"action" => "blah",
"controller" => "x/Y",
"format" => "json"
}
my_hash.to_query gives me
f[][fl]=bt&f[][tp]=trm&f[][vl]=A%3A%3AB&f[][fl]=jcni&f[][tp]=trm&f[][vl][]=133&f[][vl][]=134&f[][mnfl]=bmns&f[][mxfl]=bmxs&f[][tp]=rfstv&f[][vl]=100000.0&f[][fl]=bpo&f[][op]=eta&f[][tp]=rftv&f[][vl]=2013-01-25&k=blah&p[e]=2&p[s]=100
which doesn't have indices, hence the mixup.
Is there a name for this type of serialization using "[]" ? Is this guaranteed to serialize/deserialize arbitrarily nested hashes/arrays/primitives faithfully ? How do I make active resource behave sanely ?

Rails 2 and ajax - few select lists

I can't figure what i do wrong. I have few select lists:
Regions
Towns
Organizations
How it should works:
User selects region.
List of towns loads.
User selects town.
List of organizations loads.
User chooses organization.
I use ajax for that and i realized only auto-loading for list of towns and i can't do same thing for organization. Second select list DOESN'T POST at all!
Here is my code:
View
%div
%br/
= select 'ajax', :region_id, [['Choose your region...', -1]] + Region.all.map{|region| [region.name, region.id]}.sort
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
= observe_field :ajax_region_id, :url => { :controller => :organizations, :action => :list_towns, :preselect => (defined?(preselect) && !preselect.nil?) }, :with => 'region_id', :update => 'select_organization_idd', :loading => '$("ajax-progress").show();', :complete => 'if (Ajax.activeRequestCount == 1) $("ajax-progress").hide();'
%br/
= select 'ajax2', :o_id, [], {}, {:id => 'select_organization_idd', :style => 'width: 60em;'}
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
= observe_field :ajax_region2_id, :url => { :controller => :organizations, :action => :list_region, :preselect => (defined?(preselect) && !preselect.nil?) }, :with => 'o_id', :update => 'select_organization_idd2', :loading => '$("ajax-progress").show();', :complete => 'if (Ajax.activeRequestCount == 1) $("ajax-progress").hide();'
= f.select :organization_id, [], {}, {:id => 'select_organization_idd2', :style => 'width: 60em;'}
Controller
def list_region
render :text => ActionController::Base.helpers.options_for_select((params[:preselect] ? [['Choose organization', -1]] : []) + Organization.map{|org| [ActionController::Base.helpers.truncate(org.name, :length => 155), org.id]})
end
def list_towns
region = Region.find(params[:region_id])
towns = Kladr.find(:all, :conditions => ['code LIKE ?', "#{region.code}%"])
render :text => ActionController::Base.helpers.options_for_select([['Choose town', -1]] + towns.map{ |t| ["#{t.socr}. #{t.name}", t.id] })
end
What do i do wrong? Also i use Rails 2, that why observe_field is not deprecated.
Do you use rails 3? The method observe_field is deprecated.
With rails 3 you must do something like this :
view
%div
%br/
= select 'ajax', :region_id, [['Choose your region...', -1]] + Region.all.map{|region| [region.name, region.id]}.sort, {}, {:id => 'ajax1'}
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
%br/
= select 'ajax2', :o_id, [], {}, {:id => 'select_organization_idd', :style => 'width: 60em;'}, {}, {:id => 'ajax2'}
= image_tag('ajax-loader.gif', :id => 'ajax-progress', :style => 'display: none;')
= f.select :organization_id, [], {}, {:id => 'select_organization_idd2', :style => 'width: 60em;'}
javascript.js.coffee
$('#ajax1').change = () ->
$.post(
url: '/organizations/list_towns'
data: {value: $('#ajax1').val()}
success: () ->
if (Ajax.activeRequestCount == 1)
$("ajax-progress").hide()
)
$('#ajax2').change = () ->
$.post(
url: '/organizations/list_regions'
data: {value: $('#ajax2').val()}
success: () ->
if (Ajax.activeRequestCount == 1)
$("ajax-progress").hide()
)
The implementation is probably wrong and could be refactored. I didn't test it. But you've got the idea.

Resources