Undefined Index on Empty Form - foreach

This error is only on my local development system where errors are enabled and otherwise the programming works fine but how can I get rid of the error?
This snippet is part of the code that generates a form semi-dynamically from the column names and the error is coming from addslashes($row[$val]) when an empty form is initially opened. Once the form has been populated with data, the error is gone but until then, each field gives the error at the top of the page.
// Build WHERE clause to prevent errors when loading page with no values
$Where = (isset($PostID)) ? "WHERE `ID`='$PostID'" : "";
// Open record for viewing
$sqlView = "SELECT * FROM $TableName $Where";
$row = DBConnect($sqlView, "Select", $siteDB);
// Attempt to eliminate Undefined Index errors
if (!is_array($row)) $row = [];
// Get array of column names from tableaddslashes($row[$val])
$FieldNames = ListColumns($TableName, $siteDB);
// Create variable variables from table column names and populate on post or from existing entry
foreach ($FieldNames as $val) :
$$val = (isset($_POST[$val])) ? safeData($_POST[$val]) : addslashes($row[$val]);
endforeach;
$FieldNames, in this case, contains:
Array
(
[0] => ID
[1] => PageTitle
[2] => MenuTitle
[3] => PageText
[4] => DateUpdated
[5] => ShowPage
)
The actual errors are:
Notice: Undefined index: ID in /var/www/html/form.php on line 88
Notice: Undefined index: PageTitle in /var/www/html/form.php on line 88
Notice: Undefined index: MenuTitle in /var/www/html/form.php on line 88
Notice: Undefined index: PageText in /var/www/html/form.php on line 88
Notice: Undefined index: DateUpdated in /var/www/html/form.php on line 88
Notice: Undefined index: ShowPage in /var/www/html/form.php on line 88

Your $row is empty array:
$$val = (isset($_POST[$val])) ? safeData($_POST[$val])
: (isset($row[$val]) ? addslashes($row[$val]) : '');

Related

Getting Google Ads API keyword_plan_idea_error: The input has an invalid value

$requestOptionalArgs = [];
$requestOptionalArgs['keywordSeed'] = new KeywordSeed(['keywords' => $keywords]);
$keywordPlanIdeaServiceClient->generateKeywordIdeas([
'language' => ResourceNames::forLanguageConstant(1000), // English
'customerId' => $customerId,
'geoTargetConstants' => $geoTargetConstants,
'keywordPlanNetwork' => KeywordPlanNetwork::GOOGLE_SEARCH
] + $requestOptionalArgs);
The above code is working fine if the $keywords array size is not more than 20. If I add the 21st keyword to the $keywords array then it's throwing the below error.
keyword_plan_idea_error: The input has an invalid value.

How can I access an array inside a hash?

I have a hash within an array:
values = {}
values.merge!(name => {
"requested_amount" => #specific_last_pending_quota.requested_amount,
"granted" => #specific_last_pending_quota.granted,
"pending_final" => pending_final
})
#o_requests[request.receiving_organization][request.program_date][:data] = values
I send it to the view and then when I get it so:
= quota[:data].inspect
# {"theme"=>{"requested_amount"=>2, "granted"=>false, "pending_final"=>0}}
I want to fetch the object like this:
= quota[:data]["theme"].inspect
But I got this error
can't convert String into Integer
I guess quota[:data] may return array of hash
Try:
= quota[:data][0]["theme"]
Here I tried case to get same error and check:
> h[:data]
#=> [{"theme"=>{"requested_amount"=>2, "granted"=>false, "pending_final"=>0}}]
> h[:data]["theme"]
TypeError: no implicit conversion of String into Integer
from (irb):10:in `[]'
from (irb):10
from /home/ggami/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'
> h[:data][0]["theme"]
#=> {"requested_amount"=>2, "granted"=>false, "pending_final"=>0}
Try convert it to proper hash I guess it should work fine.
values = {}
values.merge!(name => {:requested_amount => #specific_last_pending_quota.requested_amount, :granted => #specific_last_pending_quota.granted, :pending_final => pending_final})
#o_requests[request.receiving_organization][request.program_date][:data] = values

How do I add hash elements to another hash?

I do not seem to be able to add items to a hash.
I have the following method that has a hash passed in and the intent is to pass out a new hash made from the original. I have verified that the key is a string and the other two elements are floats. b_name, lat and lng all print to the logs when I request.
def construct_paint_hash(list)
full_list = Hash.new
num = 100
list.each do |thing|
puts num
b_name = thing["name"]
puts b_name
lng = thing["longitude"]
lat = thing["latitude"]
full_list["#{b_name}"]=[lng, lat]
# full_list[:dsfsd] = "dsfdsfds"
num +=100
end
return full_list
end
Here is the error I am getting:
Completed 500 Internal Server Error in 377ms (ActiveRecord: 0.0ms)
TypeError (no implicit conversion of String into Integer):
app/controllers/welcome_controller.rb:42:in `[]'
app/controllers/welcome_controller.rb:42:in `block in construct_paint_hash'
app/controllers/welcome_controller.rb:39:in `each'
app/controllers/welcome_controller.rb:39:in `construct_paint_hash'
app/controllers/welcome_controller.rb:11:in `index'
What the heck am I doing wrong here?
Your code seems okay, but you can use the following code snippet. I assume your list params as following
list = [{"name" => "dhaka", "longitude" => 23.44, "latitude" => 24.55}, {"name" => "usa", "longitude" => 23.44, "latitude" => 24.55}]
Then rewrite your construct_paint_hash as following
def self.construct_paint_hash(list)
data = list.collect { |l| {l["name"] => [l["longitude"], l["latitude"]]} }
return data.inject(:merge)
end

Ruby or Rails: PG Data Query Error,

I'm trying to update a few records based on a user entered string - it won't let me and produces this error:
PGError: ERROR: invalid input syntax for type boolean: "ian"
LINE 1: UPDATE "subjects" SET treatment_group = 'ian' AND pref_rand ...
I double checked the type from the rails console:
Subject.column_hash["treatment_group"].type
=> :string
And the input method is:
Group Name: <%= text_field_tag(:treatment_group_name) %>
Finally, within the controller I have this logic:
#group_to_randomize = Subject.where("study_site = ? AND treatment_group is null", params[:site_input].to_i).order("created_at ASC").limit(params[:group_size_input].to_i)
flash[:notice] = "We are at the database level. #{#group_to_randomize.inspect}"
if params[:treatment_group_name] != '' and params[:site_input] != '' and params[:group_size_input] != ''
#group_to_randomize.update_all(["treatment_group = ? AND pref_rand = ?", params[:treatment_group_name, #treatment.to_i])
flash[:notice] = "Subjects randomized, and assigned to group #{params[:treatment_group_name]}"
else
flash[:notice] = "Nothing saved, please fill in the form completely."
end
So that it's easier to read, the error stems from this line:
#group_to_randomize.update_all(["treatment_group = ? AND pref_rand = ?", params[:treatment_group_name], #treatment.to_i])
So I can't figure out why it thinks the input is a boolean, and why it won't save as a string anyway. Any help would be greatly appreciated.
because of syntax error, modify this line
#group_to_randomize.update_all(treatment_group:params[:treatment_group_name], pref_rand: #treatment.to_i)

Ruby on Rails array delete_if block, string is "missing translation: no key" inside but fine outside

My problem is that the print t inside the delete_if block prints 'translation missing: en.no key'
This is strange. The error message in the browser shows me my pages parameters.
Here is what is says for tutor_id:
"tutor_id"=>["1", "2"].
I also tried the following inside the block to make sure it was right, and it did indeed return String.
print t.class # => returns 'String'
Also making a call to the following inside the block yields an error
Integer(t) # => yields error: invalid value for Integer(): "translation missing: en.no key"
Likewise, a call to .to_i is not helpful. It always returns 0. Note: this is the behavior o any non-numerical string such as 'hello'.to_s
print t.to_i # always prints '0'
The following is the troublesome code:
#get an array of all tutors' IDs
tutorIds = params[:tutor_id]
tutorIds.delete_if { [t]
print t
Schedule.exists?(["tutor_id = ?", Integer(t)])
}
Update I left out a bit of information so if the delete_if block is
tutorIds.delete_if { [t]
print t
Schedule.exists?(["tutor_id = ?", t ])
}
The error I get is:
PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "translation missing: en.no key" LINE 1: ...ECT 1 AS one FROM "schedules" WHERE (tutor_id = 'translati... ^ : SELECT 1 AS one FROM "schedules" WHERE (tutor_id = 'translation missing: en.no key') LIMIT 1
Well it was right under my nose. Such a simple mistake. Notice the [] -> ||
tutorIds.delete_if { [t]
print t
Schedule.exists?(["tutor_id = ?", t ])}
Should have been
tutorIds.delete_if { |t|
print t
Schedule.exists?(["tutor_id = ?", t ])}
Can you try
Schedule.where("tutor_id = ?", t.to_i).exists?
instead?

Resources