CodeIgniter set_message() - codeigniter

When I am trying to set the custom message for an error under from_validation library in CodeIgniter using the following statement..
$this->form_validation->set_message("is_unique", "%s already registered. Try a different %s");
Instead of getting Username already registered. Try a different Username I'm getting Username already registered. Try a different users.username
While the documentation says If you include %s in your error string, it will be replaced with the "human" name you used for your field when you set your rules.
Please get me out of the trap.

Looking at your problem it seems that the language file you are using does not have an index user.username. Define it in the user language file and see what happens.
Here is the Reference to language
Codeigniter Language Class
And
Codeigntier Language Helper

I faced same problem , while i am searching i found this answer which mentioned the line in Codeigniter that builds the error message (located in file system/libraries/form_validation.php) near line 673:
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
I edited it to :
// Build the error message
if($rule == 'is_unique') { //my code here
$vars_num = substr_count($line, '%s'); //my code here
for($i = 0; $i < $vars_num; $i++){ //my code here
$params[] = $this->_translate_fieldname($row['label']); //my code here
} //my code here
$message = vsprintf($line, $params); //my code here
} else { //my code here
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
}
and it works fine for me .
i know it is not best practice to edit system libraries but maybe it will help you.

Try this:
$this->form_validation->set_message("is_unique", "{field} already registered. Try a different {field}");

You can set Custom Message with Message library of codigniter
For Example
in Model Coding Like this
if(duplicate_user_name ==true){
$this->messages->add('$user already registered. Try a different $user ', 'error');
}
and Print this message with following View
$messages = $this->messages->get();
if (is_array($messages)):
foreach ($messages as $type => $msgs):
if (count($msgs > 0)):
foreach ($msgs as $message):
echo ('<div class="' . $type .'">' . $message . '</div>');
endforeach;
endif;
endforeach;
endif;

Related

Infinite loop error when using header in observer

I'm just trying to set up terms and conditions page after a successful login. All seems to to working well. I am getting the post data through the form which I have placed in CMS Page with identifier 'general-conditions'. The problem is only in the
header('Location: '.Mage::getUrl('general-conditions'));
If I comment out this line.. page loads properly but if I don't it gets caught in infinite loop.
Could anyone please help me, that's the only thing left and I've spent a lot of time on it.
Thanks in advance.
<?php
Class Rik_Terms_Model_Observer{
public function checkGeneralTerms(){
if (Mage::helper('customer')->isLoggedIn()) {
$id = Mage::getModel('customer/session')->getId();
$customer = Mage::getModel('customer/customer')->load($id);
$customerData = $customer->getData();
$groupId = Mage::helper('customer')->getCustomer()->getGroupId();
$groupName = Mage::getModel('customer/group')->load($groupId)->getCode();
$storeId = Mage::app()->getStore()->getId();
if($customer->getGeneralTerms()=='0'){
$pageIdentifier = Mage::getModel('cms/page')->checkIdentifier("general-conditions", $storeId);
if ($pageIdentifier){
header('Location: '.Mage::getUrl('general-conditions')); // problem
die();
}
}
}
}
}
Found later, it was actually conflicting with extended version of my CMS Module.

Could not instantiate mail function in joomla 2.5.4

I am trying to send mail from my component when the user registers. I tried all three i.e PHPMail, Sendmail and SMTP but none works. I am testing it in localhost (WampServer 2.2) and the Joomla version is 2.5.4. I am not sure this is WampServer problem or Joomla or my own code. This is my code:
function postmail($name, $receiver){
jimport('joomla.mail.helper');
$mailer =& JFactory::getMailer();
$config =& JFactory::getConfig();
$sender = array($config->getValue( 'config.mailfrom'),$config->getValue( 'config.fromname' ) );
$mailer->setSender($sender);
$recipient = $receiver;
$mailer->addRecipient($recipient);
$body = "<body><br><p>";
$body .= "<strong>$name,</strong> ";
$body .= "</p><br></body>";
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setBody($body);
$send =& $mailer->Send();
if ( $send != true ) {
//echo 'Error sending email: ' . $send->message;
return false;
} else {
//echo 'Mail sent';
return true;
}
}
It gets the error 'could not instantiate mail function'.
i am sure there are many reasons causing this problem. but to test you can always create a mail server of your own by installing this tool here http://www.toolheap.com/test-mail-server-tool/
you don't have to change anything except that you put localhost as the smtp host in joomla mail settings and then in your webserver's php.ini, add the smtp=localhost. thats it, it should work.
this is just to test whether your code is correct and you are using the correct mail settings in joomla. if this doesn't work then, i am sure the problem is not in your code but in your mail settings.
To understand what the problem is you really need to get the error message.
Change
//echo 'Error sending email: ' . $send->message;
to
echo 'Error sending email:'.$send->get('message');
then run it again. The error that you get should tell us why it isn't instantiating. Let us know what it says so we can help you out.

Codeigniter catch database errors

I'm looking for a way to catch all the database errors (if and when they occur) and sent an error report my email. For regular php error I extended the CI_Exceptions class and added my email sending code in addition to logging. But the database errors don't go trough CI_Exceptions but instead are logged directly from CI_DB_Driver->query() and I don't want to modify any file in the System folder.
Also I don't want to write logging code around every query the app does.
I'd be tempted to extend CI_Exceptions show_error method to catch any errors passed with the 'error_db' template rather than hunting through the db driver.
As you've already extended CI_Exceptions with email code this would seem like the best practice.
function show_error($heading, $message, $template = 'error_general', $status_code = 500)
{
set_status_header($status_code);
$message = '<p>'.implode('</p><p>', ( ! is_array($message)) ? array($message) : $message).'</p>';
if ($template == 'error_db')
{
// do email send here with $message
}
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include(APPPATH.'errors/'.$template.'.php');
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}

displaying page with value with error message in codeigniter

Hi guys I make my code simplier just to display the error message but still now showing.
public function check_profile_ifexist($id)
{
if($this->input->post('edit')){
$this->form_validation->set_rules('email','Email','trim|valid_email|is_unique[user_details.email]');
$this->form_validation->set_rules('username','Username','trim|min_length[6]|max_length[20]|is_unique[user_details.username]|xss_clean'); $this->form_validation->set_message('is_unique',"That %s already exists!");
$this->form_validation->set_message('max_length', 'the maximum characters for %s is 20');
$this->form_validation->set_message('min_length', 'the minimum characters for %s is 6');
if ($this->form_validation->run())
{
$this->load->model('model_user_manage');
$em=$this->model_user_manage->update_all($id);
}
else
{
$this->view_profile($id);
}
}
}
Instead of echoing out all of your errors just store them all to a property:
First initiate an empty property so you know it exists - you could do this at the beginning of check_profile_ifexist() method:
$this->profile_errors = '';
Then within your check_profile_ifexist() method just add the errors to the property as you go rather than echoing them e.g.
if (MD5($username)==$pass){
echo "username cannot be the same as password";
}
becomes:
if (MD5($username)==$pass){
$this->profile_errors .= "username cannot be the same as password\n";
}
This property will then be available to all your methods so you could add it to your data array in view_profile() like so:
if(isset($this->profile_errors)){
$data['errors'] = $this->profile_errors;
}else{
$data['errors'] = '';
}
and the errors are available in your view as $errors, so you could echo $errors; to print out all of the errors.
NOTE Obviously you will have to make sure that the property always exists or check for its existence to avoid errors of your own. I have also added newlines to your errors so that they will look a bit neater when printed out in bulk if more than one.
SECOND NOTE You seem to have a lot of stuff I would put in a model in this code, which I presume is a controller. You should probably keep all your db stuff in models or the MVC police will come for you.

CodeIgniter flashdata

I'm running into a problem I just can't seem to fix. I'm working on kind of a CMS kind of thing. And one of the functions is making image slideshows.
In one controller, I check if a slideshow with a certain ID exists, and if it exists, it should take the data and work with it, otherwise, set an error message (CodeIgniter flashdata) and redirect to the homepage.
The code I use for this is the following:
if($this->Mslideshow->slideshowExists($showid) === FALSE){
echo 'I\'m getting here';
$this->session->set_flashdata('error',$showid);
redirect('admin/index','refresh');
}else{
echo 'Slideshow exists';
}
And the code of the slideshowExists() function is:
public function slideshowExists($showid)
{
$this->db->where('id',$showid)
->limit(1);
$query = $this->db->get('slideshows');
if($query->num_rows() < 1){
return FALSE;
}
$this->currentquery = $query;
return TRUE;
}
And the problem is this, very strange actually. If the result I get back is FALSE, everything goes as planned. Error message gets set and redirect goes to 'admin/index'.
But if what I get back is TRUE, then the stange thing happens. I do get an echo with 'Slideshow exists', but I also get the error message.
I've tried everything, deleted cookies. Reset all sessions etc.
And even stranger is that when I tried to put the $showid I use to check into the error message, all of a sudden $showid is ' img '. While everywhere else is '1' or '2'...
Hope someone can help. Thanks!
=====EDIT=====
I tried to edit the code and simplify it. Right now I have this code in my Controller:
public function slideshow($showid){
$query = $this->db->where('id',$showid)->get('slideshows');
if($query->num_rows() < 1){
$this->session->set_flashdata('error','Slideshow doesn\'t exist.');
redirect('admin/index','refresh');
}
$data['page'] = 'slideshow';
$data['title'] = 'Slideshows';
$this->scripts->load_scripts(array());
$this->scripts->load_functions(array());
$this->load->view('admin/dashboard_template.php',$data);
}
When I run this with a $showid, that doesn't exist, I get the error message after being redirected to 'admin/index'. When I use a $showid that does exist, I do get the error, but no redirect but just the rest of the code.
I think you have to read your flash data in your view:
$error = $this->session->flashdata('error');
var_dump($error);
or in your Controller:
$error = $this->session->flashdata('error');
if(isset($error)) {
var_dump($error);
}
Also you can read this question: CodeIgniter "flashdata" doesn't work
you can get the flash data by following way
$error = $this->session->flashdata('error');
if($error)
{
echo $error;
}
You can try
if($this->session->flashdata('msg') != "")
This works for me.

Resources