I am trying to display error messages by assigning the SMARTY variable $error in the form of:
function validate1() {
$error['title'] = "Title contains illegal characters...";
$this->smarty->append('error', $error);
}
function validate2() {
$error['time'] = "Please enter a time in 12 hour clock (12:30 PM) format.";
$this->smarty->append('error', $error);
}
My HTML looks like:
<p class="message-error">{$error['title']}</p>
<p class="message-error">{$error['time']}</p>
I had recently been using the code below, which works; is there any way that I can modify the first block of code to work the same as the code below?
$error['title'] = "Title contains illegal characters...";
$error['time'] = "Please enter a time in 12 hour clock (12:30 PM) format.";
$this->smarty->assign("error", $error);
Does it work if you define the array this way and include the merge option (3rd param to append())
function validate1() {
$error = array('title' => "Title contains illegal characters...");
$this->smarty->append('error', $error, TRUE);
// -------------------------------------^^^^
}
EDIT Forgot to include the merge parameter.
Read smarty manual, correct syntax for associative arrays is:
{$error.title}
Related
Attached is code that reads an excel file and returns a value to be used in a page through a WordPress short code. The code comes from here http://metinerbek.com/article/get-data-from-excel-with-php
<?php
add_shortcode( 'tpmcme', function ($attr) {
$args = shortcode_atts( array(
'course' => 'A',
), $attr );
require("reader.php");
$file="TPM.xls";
$connection=new Spreadsheet_Excel_Reader();
$connection->read($file);
if ($args['course'] == 'AM1') {
$startrow=6;
$endrow=7;
$col1=10;
for($i=$startrow;$i<$endrow;$i++){
$value = $connection->sheets[0]["cells"][$i][$col1];
return $value;
}
} else if ($args['course'] == 'ANAdvanced') {
$startrow=12;
$endrow=13;
$col1=10;
for($i=$startrow;$i<$endrow;$i++){
$value = $connection->sheets[0]["cells"][$i][$col1];
return $value;
}
} else if ($args['course'] == 'ANBasic') {
$startrow=14;
$endrow=15;
$col1=10;
for($i=$startrow;$i<$endrow;$i++){
$value = $connection->sheets[0]["cells"][$i][$col1];
return $value;
}
}
}
?>
Now here is the problem. The code works just as intended but when I insert the short code into a page with an argument and save the page it will then say that a critical error has occurred. I can use my browser’s back button and go back to the page and everything will be fine.
A couple of things of note.
1 – the version of WordPress I am using is current and up to date.
2 – the version of PHP I am using is current and up to date.
3 – I am using the code snippets plugin to store the code.
4 – I did get the following error sent to me : An error of type E_COMPILE_ERROR was caused in line 6 of the file /nas/content/live/tpm20/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code. Error message: require(): Failed opening required 'reader.php' (include_path='.:/usr/share/pear/php:/usr/share/php')
Any help is very much appreciated.
Thank you all in advance.
I am new in this site, and i found some questions that are connected to my system error but unfortunately they can't fix the error. I am creating an offline web-based information system for my capstone project and I don't understand why P_Bday is undefined.. Here is my code
This is my code for inputting Birthdate:
input type="text" id = "P_Bday" name = "P_Bday" class="form-control" data-inputmask="'alias': 'dd/mm/yyyy'" data-mask placeholder="dd/mm/yyyy" required
And here's my code for calculating age:
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}
$dob = $_POST["P_Bday"];
And I call my function here, where it should display the calculated age depending on the inputted birthdate:
input type='text' name = 'P_Age' id='disabledTextInput' class='form-control' value='".ageCalculator($dob)."' readonly
Every time I ran my code it says:
Notice: Undefined index: P_Bday in
C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php on line
47
If the line $dob = $_POST["P_Bday"]; is being run on the page before anything is sent via POST, then $_POST[foo] is invalid.
Change the line to:
if(isset($_POST["P_Bday"])) $dob = $_POST["P_Bday"];
else $dob = null;
Or:
$dob = isset($_POST["P_Bday"]) ? $_POST["P_Bday"] : null;
An Undefined index error is pretty simple to debug. You start at the file mentioned in the error message C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php and go to the line mentioned in the error message line 47 and find the undefined index in question on that line P_Bday and know with absolute certainty that up to this point in your code you have not defined that index for that variable. You can work your way backwards through the code to try and figure out your mistake. The mistake can be a typo (you used the wrong case/variable name) or it can be that you just forgot to initialize the variable properly.
The best way to avoid undefined variable/index errors is to initialize always and initialize early. In the few cases where you cannot be sure that variables are properly initialized (for example with $_POST/$_GET or other external variables under control of client input) you want to use isset to avoid the error and that way you can coalesce null values or write logic that prevents the code from continuing with an uninitialized value in case of user error.
Example
if (!isset($_POST['P_Bday'])) {
die("You forgot to fill out your birthday!");
} else {
echo "Yay!";
}
Some good initialization techniques with $_POST/$_GET
A good best practice for "initialize always and initialize early" when dealing with user input is to setup a default set of values for the expected input from your form and initialize from that in order not to fall into this trap.
Example
$defaultValues = [
'P_Bday' => null,
'Option1' => 'default',
'Option2' => 1,
];
/* Let's say the user only supplied Option1 */
$_POST = ['Option1' => 'foo'];
/* This makes sure we still have the other index initialized */
$inputValues = array_intersect_key($_POST, $defaultValues) + $defaultValues;
/**
* Now you can pass around $inputValues safely knowing all expected values
* are always going to be initialized without having to do isset() everywhere
*/
doSomething(Array $inputValues) {
if (!$inputValues['P_Bday']) { // notice no isset() check is necessary
throw new Exception("You didn't give a birthday!!!");
}
return (new DateTime)->diff(new DateTime($inputValues['P_Bday']))->y;
}
You are declaring the variable $dob after calling function. You have to declare your variable before function call and also use conditional statement like following:
Please write your code as follows:
if(isset($_POST["P_Bday"])){
$dob = $_POST["P_Bday"];
} else {
$dob ="";
}
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}
I am using Kohana's validation methods to ascertain that certain mandatory values are present inside a form. While validating confirm_password the 'errors' method of ORM_Validation_Exception is returning array in the following format
array(1) (
"_external" => array(1) (
"password_confirm" => string(45) "password confirm must be the same as password"
)
)
How can i make it follow the same convention as rest of the errors so that i can do the following and just iterate through the errors in the view file.
$Errors = $e->errors('user'); // inside the controller
<?php if ($Errors): ?>
<p class="message">Some errors were encountered, please check the details you entered.</p>
<ul class="errors">
<?php
echo Debug::vars($Errors);
foreach ($Errors as $message): ?>
<li><?php echo $message ?></li>
<?php endforeach ?>
<?php endif;
I have tried adding an _external file under messages(also tried placing it in /messages/model) folder, but it doesn't seem working. Should I call $Errors = $e->errors('_external') to load the error messages, in that case all how can i load messages from 'User' file which contains rest of the error messages?
Even if you translate the errors using a message file (which in your case should go in messages/user/<model>/_external.php), your $Errors array will still have the same structure i.e. external error messages will be in their own sub-array, $Errors['_external'].
If you need it 'flattened' I think you'll have to do that manually, e.g.:
// The next line is from your question
$Errors = $e->errors('user'); // inside the controller
// If there are any '_external' errors, we place them directly into $Errors
if (isset($Errors['_external']))
{
// Keeps track of a possible edge case in which the _external
// array has a key '_external'
$double_external = isset($Errors['_external']['_external']);
// Move the elements of the sub-array of external errors into the main array
$Errors = array_merge_recursive($Errors, $Errors['_external']);
// Remove the '_external' subarray, except in the edge case
if (!$double_external)
{
unset($Errors['_external']);
}
}
You should merge them, as far ar I know there is no function or whatsoever in the framework which does this for you. Unfortunately.
$errors = $e->errors('user');
$errors = Arr::merge($errors, Arr::get($errors, '_external'));
unset($errors['_external']);
Notice (8): Use of undefined constant inList - assumed 'inList' [CORE\Cake\Utility\ClassRegistry.php, line 168]
This notice has been bugging me for a while know, and I do not know how to fix it.. It was not really affecting my project earlier since its just a notice msg, but now, it is not letting me show an error message which I am trying to display to the user.
Iv got this function
public function validate_form(){
if($this->RequestHandler->isAjax()){
$this->request->data['Donor'][$this->params['form']['field']] = $this->params['form']['value'];
$this->Donor->set($this->data);
if($this->Donor->validates()){
$this->autoRender = FALSE;
}else{
$error = $this->Donor->validationErrors;
$this->set('error',$error[$this->params['form']['field']]);
}
}
}
The above is the action to which my post request submits to. Then it executes the following to display the error
if (error.length > 0) {
if ($('#name-notEmpty').length == 0) {
$('#DonorName').after('<div id="name-notEmpty" class="error-message">' + error + '</div>');
}
}else{
$('#name-notEmpty').remove();
}
The problem is that instead of the relevant error in my newly created div... I get that notice 8 from cake! Please if anyone knows why this is happening, I appreciate your aid on this one..
TLDR:
Do a project-wide find for 'inList' and find the spot where it either doesn't have quotes around it, or, if it's supposed to be a variable, is missing it's $.
Explanation:
You get that error when you try to use a PHP Constant that doesn't exist. Usually you're not actually TRYING to use a constant, but instead just forgot to wrap quotes around something or forgot to add the $ before a variable.
Examples:
$name = "Dave";
echo name; // <-- WOAH THERE, there is no Constant called name (missing $)
$people = array('Dave' => 'loves pizza');
echo $people[Dave]; // <-- WOAH THERE, no Constant called Dave (missing quotes)
Most likely somewhere else in your code you are using 'inList' as an array key but you don't have it quoted.
Example: $value = $myArray[inList];
It still works without quoting inList but it causes the notice message you're seeing.
My post data is from Captcha adapter is as following:
["ffck"] => array(2) {
["id"] => string(32) "661db3996f5e60e71a60671496ec71a9"
["input"] => string(3) "dys"
}
My code is trying to validate now, but always failing:
Zend_Loader::loadClass('Zend_Captcha_Image');
$captcha = new Zend_Captcha_Image();
$captchaArray = array(
'id' => $post['ffck']['id'], // valid id
'input' => $post['ffck']['input'] // valid input
);
if ($captcha->isValid($captchaArray)) { // FAILs!!!!
echo "working";
} else {
echo "fails";
}
Zend_Debug::dump($post) ; // 100% valid ....
exit;
How to fix it? Or whats causing this to fail?
Check the generated html, you should only have two inputs: name="captcha[id]" and name="captcha[input]", if you have a third one with name="captcha", then you have to remove the viewhelper from the captcha element before rendering.
Ex.:
$form->getElement('captcha')->removeDecorator("viewhelper");
The array you pass to the CAPTCHA object should just contain the two keys, so try:
$captchaArray = $post['ffck']
instead of what you are currently doing.
But the code you've posted is not valid anyway since you never generate the CAPTCHA image. I imagine you've cut down the code sample to keep the question short, so if the above fix doesn't work please edit your example to include how and where the CAPTCHA image is generated.