kohana - how to get _external error messages from a file - php

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']);

Related

Fatal error: Cannot use object of type PDO as array

Here is the error Log
Fatal error: Cannot use object of type PDO as array in /Applications/XAMPP/xamppfiles/htdocs/php/blog/single.php on line 13
Here is 13 number line
$post = DB\query('SELECT * FROM posts WHERE id = :id LIMIT 1', array('id' => $_GET['id']), $conn [0] );
i got this error when i try to get post title.
<?= $post['title'];?>
Full Code
<?php
require 'functions.php';
use blog\DB;
// Connect to the DB
$conn = DB\connect($config);
if( !$conn ) die('Problem Connecting to the DB');
// Fetch all the posts
$post = DB\query('SELECT * FROM posts WHERE id = :id LIMIT 1', array('id' => $_GET['id']), $conn [0] );
// Filter throgh and display in the view
$view_path = 'views/single.view.php';
include 'views/layout.php';
Instead of $conn[0], Try using $conn.
For future issues, always remember you can output the datatypes, content, and structures of variables in php.
Use the following to output the content in human readable format.
echo "<pre>";
print_r($variable);
echo "</pre>";
die();
Use the following to output the content with datatype and extra info
echo "<pre>";
var_dump($this);
echo "</pre>";
die();
Remember functions like gettype() etc.
Also based on your further comments, I'd recommend that you first grab a book or an online course of the language.
About your next error, remember that in php the variable needs to be defined before you can call/use it.
So on the line, where you care calling $post['title']; remember to first make sure that that variable is defined and has the index that you intend to call. Also use the above snippets to verify and you should be writing the handling code if that index is not set.
something like..
if(isset($post) && !empty($post) && isset($post['title'])) {
....

$write_result->errors throws "Undefined Property" when there are no errors

Using pre-written code from Bronto, it builds a soap client, calls a function on it, then parses the results. The parsing code looks like this:
if ($write_result->errors) {
print "There was a problem adding or updating the contact:\n";
print_r($write_result->results);
exit;
} elseif ($write_result->results[0]->isNew == true) {
print "The contact has been added. Id: " . $write_result->results[0]->id . "\n";
} else {
print "The contact's information has been updated. Id: " . $write_result->results[0]->id . "\n";
}
Whenever there ARE errors, they get caught and printed by the first if statement. But when there AREN'T errors, the console gets an "Notice: Undefined property: stdClass::$errors" message printed out. Is this right? Is there a way to turn off the notice? It doesn't cause any problems, but I can see how it would confuse a non-techy reading the output logs.
Check if the property exists instead of accessing it directly:
if (isset($write_result->errors))
Or to check if it exists and not empty at once (just to be sure in case the API changes and provides an actual empty array or empty string if no errors occured):
if (!empty($write_result->errors))
You could check first if the property exists:
if (property_exists($write_result, 'errors'))
Check that the property exists first:
if (property_exists($write_result, 'errors') && $write_result->errors)
{
// ...
}
See: property_exists.

ZendFramework - Why the results of isValid always failing?

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.

PHP & SMARTY => Can't access appended variables in .tpl file

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}

PHP: are switch-case statements with strings inefficient?

In my PHP layer I'm receiving error codes as strings ("NOT_FOUND", "EXPIRED", etc). It's a small list of possible strings, perhaps a dozen.
What's the most efficient way of dealing with these? Using switch-case against string constants stored in a class, or should I parse them to numbers (or something) first? Or is PHP smart enough so it doesn't really matter?
You might want to consider using constants? Let's say you have a class Error and define all error codes there like this:
class Error {
const NOT_FOUND = 0;
const EXPIRED = 1;
// and so forth
}
And then you can use them in your code by accessing them like Error::NOT_FOUND and a switch statement wouldn't need to compare strings but has plain ints without downgrading readability.
It really depends on what you want to do with the strings. Do you want to output error messages? Then instead of a case statement you could use a lookup table like this:
$messages = array(
'NOT_FOUND' => 'The file was not found',
'EXPIRED' => 'The cookie expired'
// ETC
);
echo empty($messages[$error]) ? "Unknown error" : $messages[$error];
With PHP 5.3 you could also store code in the array to handle the error situations:
$handlers = array(
'NOT_FOUND' => function() { /* Error handling code here */ },
'EXPIRED' => function() { /* Other error handling code */ }
);
if(!empty($handlers[$error])) {
$handler = $handlers[$error];
$handler();
}
else {
echo "Could not handle error!"; die();
}
With a technique like this you avoid case statements that go over several pages.
With PHP < 5.3 you might look into call_user_func for dynamic dispatching of error handling functions.
Strings can't be recognised as class constants. But the answer on your question is that it doesnt really matter if you do it like this:
switch (className::{$errorCode}) { // $errorCode == name of the constant, like NOT_FOUND
// Cases here.
}

Categories