Unexpected notice: undefined index when null - symfony

I've written a little script that is supposed to create an array that looks something like this:
array(1 => array( 'month' => 'Jan',
'salary' => '01/31/2013',
'bonus' => '02/15/2013'),
2 => array('month' => '',...));
You get the basic idea: the index in the main array are the months (numerically), each holding an array that is to be filled dynamically. The month key depends on the language the user requested, the salary and bonus are assigned the dates when the salary and or bonus was payed. So far no surprizes.
To get the basic structure of that array, I thought this would be the easiest:
$this->months = array_fill_keys(range(1,12), array( 'month' => null,
'salary' => null,
'bonus' => null));
I then fill the array, and things run smoothly all the same, right up until the point where I want to write the data to a file, which I did like so:
private function writeFile()
{
foreach($this->months as $key => $vals)
{
if ($vals['month'] === null)
{//Only filled from date x to date y, some months can be empty
continue;
}
//this seems to raise notices?
if ($vals['salary'] === null)
{
$vals['salary'] = 'Does not apply';
}
fwrite($this->file, implode(',', $vals).PHP_EOL);
}
fclose($this->file);
return $this;
}
The line where I check if the salary is null raises notices: "Warning: Undefined index salary". At the moment I've had to add this to the code:
if (!array_key_exists('salary', $vals) || $vals['salary'] === null)
{
if (!array_key_exists('bonus', $vals) || $vals['bonus'] === null)
{
break;
}
$vals['salary'] = 'Does not apply';
}
To get to the result I need. I have googled this, and stumbled across this bug report, which was last modified 4 years ago (2009-05-08), but the status is still set to "no feedback".
Has anyone else encountered a similar glitch/bug? Or am I missing something here? How can I avoid this issue without the need for all too many if's and function calls without changing my settings (E_STRICT | E_ALL, as it should be).
BTW: I'm running PHP 5.4.7, on Slackware 14. For this little application, I'm using 2 Symfony components (ClassLoader and Console), but since this is part of an object that has nothing to do with Symfony, apart from being loaded through UniversalClassLoader I don't think that's relevant.
Since the bug is said to be PDO related: yes, I am using PDO, but in another class.

I am not sure , but try to use
$this->months = array_fill(1,12, array( 'month' => null,
'salary' => null,
'bonus' => null));

After a couple of var_dumps, I found out what the cause was: The array keys were range(1,12), to determine the which month was I was processing. For that I used a DateTime object in the following fashion:
$date->modify('+ '.$diff.' days');
$key = $date->format('m');
The problem was that the format call returns a string. The goal was to list when the salary and bonus are to be paid. The bonus has to be paid each 15th, or the following Wednesday, if the 15th was a Saturday or Sunday. The salary is to be paid the last day of the month, or the last Friday.
In other words, the bonus pay date is assigned like so:
$key = $date->format('m');
$this->months[$key]['month'] = $date->format('M');
if ($date->format('d') == 15)
{
//find find week-day (15th or following Wednesday)
$this->months[--$key]['bonus'] = $date->format('m/d/Y');
$key++;
//set date to end of month
}
//check week-day, and modify date if required
$this->months[$key]['salary'] = $date->format('m/d/Y');
Because the keys of the $this->months array are numeric, but the format used for $key is a 2-digit string, with leading zeroes, I was having problems.
Each 15th of the month, the $key value is coerced to an integer (decrement/increment operators), but the month is assigned using a string.
The information I provided in my original question was insufficient, sorry for that, but I had just put in an all-nighter. The fix, in the end was pretty easy:
$key = (int) $date->format('m');//cast
I sincerely appreciate all responses, and everyone contributing to the SO community. I would've deleted this question, but if nobody objects, I think I might leave it be as a testimony to my stupidity.

Related

Cakephp 3: Collections getting to middle array entities

I'm trying to build a view that shows the most recent (now four but eventually five) years of data in a chart. I'm able to pull the data successfully in a variable the shows the most recent 4 years(I don't have the fifth year in the database yet). In order to break it down for the view and add some calculations on associated arrays, I have created a collection. I can get to the first and last array entity but can not figure out how to break out the middle two arrays.
public function viewAsuFiveYear()
{
$asuFiveYearEnrollments = $this->Enrollments->find('all', [
'contain' => ['Azinstitutions', 'FallFtes', 'FallHeadcounts', 'ProjectedEnrollments',
'FallHeadcounts.Locations', 'FallHeadcounts.StudentTypes', 'FallHeadcounts.ResidentStatuses', 'FallHeadcounts.Campuses',
'FallFtes.Locations', 'FallFtes.StudentTypes', 'FallFtes.ResidentStatuses', 'FallFtes.Campuses']
], ['limit' => 5])->where(['azinstitution_id' => 1])->order(['enrollment_year' => 'DESC']);
$collection = new Collection($asuFiveYearEnrollments);
$yearone = $collection->first();
$yearTwo = $collection->take(1, 1);
$yearFour = $collection->last();
$collection1HC = new Collection($yearone->fall_headcounts);
$onCampusesHc1 = $collection1HC->match(['location_id' => 1 ])->match(['campus_id' => NULL]);
$collection4HC = new Collection($yearFour->fall_headcounts);
$onCampusesHc4 = $collection4HC->match(['location_id' => 1 ])->match(['campus_id' => NULL]);
$this->set(compact('asuFiveYearEnrollments', 'azinstitutions', 'yearone', 'yearTwo', 'yearFour', 'onCampusesHc1', 'onCampusesHc4'));
}
I tried ->take (one array, second position) but it times out with that. Not sure what filter I can use to get to the 2nd or 3rd entity array.
I believe I've figured it out. May not be the best answer but it works. for the second year I skipped the 1st array and grabbed the first array in what was left.
and the same with the third year.
$yearTwo = $collection->skip(1)->first();
$yearThree = $collection->skip(2)->first();

How do I get value of datetime object in drupal 8?

There is a Datetime object as following and I want to get the date value
Array
(
[0] => Array
(
[value] => Drupal\Core\Datetime\DrupalDateTime Object
(
[formatTranslationCache:protected] =>
[inputTimeRaw:protected] =>
[inputTimeAdjusted:protected] =>
[inputTimeZoneRaw:protected] =>
[inputTimeZoneAdjusted:protected] =>
[inputFormatRaw:protected] =>
[inputFormatAdjusted:protected] =>
[langcode:protected] => en
[errors:protected] => Array
(
)
[dateTimeObject:protected] => DateTime Object
(
[date] => 2018-01-05 01:30:00.000000
[timezone_type] => 3
[timezone] => UTC
)
[stringTranslation:protected] =>
)
)
)
I don't want to get this value by $node->get("field_id")->value;
Because I need dynamic value that means the value should change after I changed date field.
Is it possible?
Figured it out
$date = $form_state->getValue('field_id')[0]['value']->format('Y-m-d H:i:s')
it returns string !!
The point is locate the Object.
The values in the array are of type Drupal\Core\Datetime\DrupalDateTime, check the API on Drupal.org DrupalDateTime Doc.
In order to get value from the object you must use the __toString method as mentioned.
Proceed as :
$dateTime = YourArray[0]['value'];
$date = $dateTime->_toString();
Else
$date = $dateTime->format('Y-m-d h::i::s');
For more date formats check the PHP doc PHP DATE
Edit 1:
The following Code works correctly :
$temp = new \Drupal\Core\Datetime\DrupalDateTime();
echo $temp->__toString();
echo $temp->format('Y-m-d h::i'); die;
I found that in browsers that do no support
<input type="time">
(i.e. Safari) the value is not of type "Drupal\Core\Datetime\DrupalDateTime" but array.
Here is what i did inside a drupal 8 module to get formatted date from DrupalDateTime
I. If you have a date and want format it, just pass it to the static method of the class (DrupalDateTime) as follows. You can replace the string with your date variables.
Below shows both using the static version and non static version of DrupalDateTime
$date = DrupalDateTime::createFromFormat('j-M-Y', '20-Jul-2019');
// Using the static method prints out: 20-Jul-2019:11:am
$date = new DrupalDateTime('now'); // grab current dateTime using NON static
$date->format('l, F j, Y - H:i'); // format it
// prints out nicely formatted version: Tue, Jul 16, 2019 - 11:34:am
// you can remove H:i and what's after it if you don't want hours or am pm
$date = new DrupalDateTime('now'); // grab current dateTime
// Or print $date->format('d-m-Y: H:i A');
// prints out: 16-07-2019: 11:43 AM
More examples:
$date = new DrupalDateTime();
$date->setTimezone(new \DateTimeZone('America/Chicago'));
print $date->format('m/d/Y g:i a');
// The above prints current time for given Timezone
// prints : 07/16/2019 10:59 am
// Another variations of the above except it takes specific date and UTC zone
$date = new DrupalDateTime('2019-07-31 11:30:00', 'UTC');
$date->setTimezone(new \DateTimeZone('America/Chicago'));
print $date->format('m/d/Y g:i a');
// prints 07/31/2019 6:30 am
To use these in your module/code you need to include the following at the top of your file;
use Drupal\Core\Datetime\DrupalDateTime;
Also note that the DrupalDateTime extends DateTimePlus() which it self "wraps the PHP DateTime class with more flexible initialization parameters.... as per docs..."
How to test it with Drush.
Save the above code in a php script, then let drush run the srcipt after it bootstraps drupal like:
drush -r /path-to-your-drupal-documentRoot -l example.com scr ~/path-to your-script
For multisites make sure you use ... drush -l http.... like above
Note:
I posted similar answer to: https://drupal.stackexchange.com/questions/252333/how-to-get-formatted-date-string-from-a-datetimeitem-object/283529#283529
in my case I use date range with duration
in your case you need the bold one
date('Y-m-d\TH:i:s', strtotime($date->get('field')->getValue()[0]['value']))
date('Y-m-d\TH:i:s', strtotime($date->get('field')->getValue()[0]['end_value']))

In controller part ASP.NET MVC 4 Survey project

In the code below I have a problem:
List<SurveyContext> surveys = (from s in DbContext.Surveys
where s.userName == s.userName
select s.ID).ToList();
if(surveys.Count() > 0)
{
int id = 0;
int.TryParse(Surveys.First(), id);
return id;
}
return 0;
Error : ToList()
Error 1 A local variable named 's' cannot be declared in this scope because it would give a different meaning to 's', which is already used in a 'parent or current' scope to denote something else
and here:
int.TryParse(Surveys.First(), id);
The name 'Surveys' does not exist in the current context
But this name exist in context... Can anyone help me??
Error 1
Use == instead of =
where s.userName == userName
Error 2
Try naming s variable on your linq query in a different way, maybe su or survey. But it seems to me that error is on code that you're not showing.
List<SurveyContext> surveys = (from su in DbContext.Surveys
where su.userName == su.userName
select su.ID).ToList();
Error 3
I think you meant surveys instead of Surveys and you need to use out when passing idparam
int.TryParse(surveys.First(), out id);
And since you're not evaluating parse result I'd say you should use int.Parse
id = int.Parse(surveys.First());
And you have to use a property of survey, you're trying to convert the entire survey instance to int
id = int.Parse(surveys.First().Property);

Smarty Math Function Foreach Loop

I am using smarty templating engine and am encountering a math issue. I am trying to create a total amount (sum) based on amounts in the array. (Normally I would do this at the server level, but do to the way that I create the array, dont think that is possible.) I am merging two arrays into one, but each array shares an 'Amount' which I am trying to determine the 'Total Amount'
Here are the steps I am taking two arrays pushing into one array:
foreach ($data_main1 as $transaction_main1) {
$json_decoded = json_decode($transaction_main1['NewObject']);
$amount = $transaction_main1['Amount'];
$mycart1[] = array('ParentType' => $ParentType, 'Amount' => $amount);
}
$mycart2=array();
foreach ($data_main2 as $transaction_main2) {
$json_decoded = json_decode($transaction_main2['NewObject']);
$amount = $transaction_main2['Amount'];
$mycart2[] = array('ParentType' => $ParentType, 'Amount' => $amount);
}
$mycart = array_merge((array)$mycart1, (array)$mycart2);
$smarty->assign('cart', $mycart);
Here is my Smarty along with the math equation that does not show the value:
{assign var=last value=$cart[cart].Amount+1}
(I am certainly open to the idea of creating a total amount on the array_merge, just unsure how to do that, or even if it is possible)
Do you know about the {math} Smarty bult-in function?
{math equation="x + 1" x=$cart[cart].Amount}
Let me know if it works.

Drupal filter is not working properly

I'm not sure how to ask it, so if you need anymore additional information, please ask for it!
Situation
I've got a website in three languages. I got a lot of customer cases online each connected to a sector (depending in which sector they belong). Each sector and reference has it's own unique nid.
In my template.php it's stated like this:
if ('sector' == $vars['node']->type) {
$lang = '/'.$vars['language'].'/';
$key_path = $_SERVER['REQUEST_URI'];
$key_path = substr_count($key_path, $lang) ? substr($key_path, strlen($lang)) : $key_path;
if (strpos($key_path, '?')) $key_path = substr_replace($key_path, '', strpos($key_path, '?'));
if (strpos($key_path, 'sectors-references') === 0) {
$view = views_get_view('references');
if (!empty($view)) {
$view->set_arguments((int)$vars['node']->nid);
$vars['content']['suffix'] = $view->render();
}
}
}
And yet, every sector shows me the same references... What do I have to change to get the correct reference under the right sector?
Usually arguments are passed to set_arguments using an array, if you pass a non-array the argument will probably be ignored which is why you're always getting the same result. Try:
$view->set_arguments(array((int)$vars['node']->nid));

Resources