Laravel library to handle messages - laravel-4

I have just created a library class in laravel.
class Message {
public static $data = array();
public function __construct() {
// If session has flash data then set it to the data property
if (Session::has('_messages')) {
self::$data = Session::flash('_messages');
}
}
public static function set($type, $message, $flash = false) {
$data = array();
// Set the message properties to array
$data['type'] = $type;
$data['message'] = $message;
// If the message is a flash message
if ($flash == true) {
Session::flash('_messages', $data);
} else {
self::$data = $data;
}
}
public static function get() {
// If the data property is set
if (count(self::$data)) {
$data = self::$data;
// Get the correct view for the message type
if ($data['type'] == 'success') {
$view = 'success';
} elseif ($data['type'] == 'info') {
$view = 'info';
} elseif ($data['type'] == 'warning') {
$view = 'warning';
} elseif ($data['type'] == 'danger') {
$view = 'danger';
} else {
// Default view
$view = 'info';
}
// Return the view
$content['body'] = $data['message'];
return View::make("alerts.{$view}", $content);
}
}
}
I can use this class in my views calling Message::get(). In the controllers, I can set the message as Message::set('info', 'success message here.'); and it works perfectly fine.
However, I can not use this class for flash messages redirects using Message::set('info', 'success message here.', true). Any idea, whats wrong in this code?

First problem is the constructor function is not called when using the above get and set methods, with minor modification the code is now working. :)
class Message {
public static $data = array();
public static function set($type, $message, $flash = false) {
$data = array();
// Set the message properties to array
$data['type'] = $type;
$data['message'] = $message;
// If the message is a flash message
if ($flash == true) {
Session::flash('_messages', $data);
} else {
self::$data = $data;
}
}
public static function get() {
// Check the session if message is available in session
if (Session::has('_messages')) {
self::$data = Session::get('_messages');
}
// If the data property is set
if (count(self::$data)) {
$data = self::$data;
// Get the correct view for the message type
if ($data['type'] == 'success') {
$view = 'success';
} elseif ($data['type'] == 'info') {
$view = 'info';
} elseif ($data['type'] == 'warning') {
$view = 'warning';
} elseif ($data['type'] == 'danger') {
$view = 'danger';
} else {
// Default view
$view = 'info';
}
// Return the view
$content['body'] = $data['message'];
return View::make("alerts.{$view}", $content);
}
}
}

Related

Laravel Eloquent Filtering Results

In my controller I retrieve a list of messages from the message model. I am trying to add a filter, but the filters are cancelling each other out.
// Controller
public function __construct(Message $messages)
{
$this->messages = $messages;
}
public function index($filter = null)
{
$messages = $this->messages
->actioned($filter == 'actioned' ? false : true)
->ignored($filter == 'ignored' ? true : false)
->get();
return view('...
}
// Model
public function scopeActioned($query, $actioned = true)
{
$constraint = ($actioned ? 'whereNotNull' : 'whereNull');
return $query->$constraint('ts_actioned');
}
public function scopeIgnored($query, $ignored = true)
{
return $query->where('is_ignored', ($ignored ? 'Yes' : 'No'));
}
How can I setup Eloquent so that scopeActioned is only called if $filter is set to 'actioned', and the same for ignored?
Simple Approach:
public function index($filter = null)
{
$query = $this->messages->query();
//applying filter
if($filter == 'actioned') {
$query->actioned();
}
if($filter == 'ignored') {
$query->ignored();
}
$messages = $query->get();
return view('...
}
Another Approach is work in Scope Function.
// Model
public function scopeActioned($query, $actioned = true)
{
if($actioned) {
$query->whereNotNull('ts_actioned');
}
return $query;
}
public function scopeIgnored($query, $ignored = true)
{
if($ignored) {
$query->where('is_ignored', 'Yes');
}
return $query;
}

Fatal error: Call to a member function num_rows() on boolean in Code igniter

I have face this Fatal error: problem in local.
$rr = $this->CI->db->query("select * from $table $condition ");
$mm = $rr->num_rows();
if ($mm>0) {
return 1;
} else {
return 0;
}
<?php
$this->db->select("your stuff");
$query = $this->db->get("your table");
if($query->num_rows() > 0 ) {
return 1;
}
else {
return 0;
}
?>
$this->CI->db->query("select * from $table $condition ");
remove CI and
$this->db->query("select * from $table $condition ");
First have you autoload the database
$autoload['libraries'] = array('database');
If a your trying to load a library then use the $CI instance http://www.codeigniter.com/user_guide/general/ancillary_classes.html#get-instance
application > libraries > Example.php
<?php
class Example {
protected $CI;
public function __construct() {
$this->CI =& get_instance();
}
public function somename() {
$query = $this->CI->db->query("select * from $table $condition ");
if ($query->num_rows() > 0) {
return 1; // return true;
} else {
return 0; // return false;
}
}
}
If on models
application > models > Example_model.php
<?php
class Example_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function somename() {
$query = $this->db->query("select * from $table $condition ");
if ($query->num_rows() > 0) {
return 1; // return true;
} else {
return 0; // return false;
}
}
}
Update one CI core file and resolve your error:
Go to : System/database/ and edit DB_active_rec.php file
Go to line no 990 and see blow code
if ($query->num_rows() == 0)
{
return 0;
}
Update to
if (!$query || $query->num_rows() == 0)
{
return 0;
}
Hope resolved your num_rows() issue.
class Site_m extends MY_Model {
protected $_table_name = 'setting';
protected $_primary_key = 'option';
protected $_primary_filter = 'intval';
protected $_order_by = "option asc";
function __construct() {
parent::__construct();
}
function get_site($id) {
$compress = array();
$query = $this->db->get('setting');
foreach ($query->result() as $row) {
$compress[$row->fieldoption] = $row->value;//here I am getting error
}
return (object) $compress;
}
}
/* End of file site_m.php */
This is fix in core CI-2
File
\system\database\DB_driver.php
Line in code
https://github.com/bcit-ci/CodeIgniter/blob/develop/system/database/DB_driver.php#L659
replace FALSE before end code
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
if ($this->save_queries == TRUE)
{
$this->query_times[] = 0;
}
// This will trigger a rollback if transactions are being used
$this->_trans_status = FALSE;
if ($this->db_debug)
{
// grab the error number and message now, as we might run some
// additional queries before displaying the error
$error_no = $this->_error_number();
$error_msg = $this->_error_message();
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
$this->trans_complete();
// Log and display errors
log_message('error', 'Query error: '.$error_msg);
return $this->display_error(
array(
'Error Number: '.$error_no,
$error_msg,
$sql
)
);
}
return FALSE;
}
To
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
if ($this->save_queries == TRUE)
{
$this->query_times[] = 0;
}
// This will trigger a rollback if transactions are being used
$this->_trans_status = FALSE;
if ($this->db_debug)
{
// grab the error number and message now, as we might run some
// additional queries before displaying the error
$error_no = $this->_error_number();
$error_msg = $this->_error_message();
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
$this->trans_complete();
// Log and display errors
log_message('error', 'Query error: '.$error_msg);
return $this->display_error(
array(
'Error Number: '.$error_no,
$error_msg,
$sql
)
);
}
$CR = new CI_DB_result();
return $CR;
}
Default should be return object empty
$CR = new CI_DB_result();
return $CR;

Return false limits multiple error message to one?

On my multiple upload library, I have a set error function.
On my upload function I use a in_array to check file extensions. If the in_array detects error it displays multiple error messages correct.
The problem I am having is for some reason when I use return FALSE; under the $this->set_error('file_extension_not_allowed') then will on display one message. Not sure why return FALSE limits error messages.
Question: How is it possible to use my return false but be able to display multiple message correct.
<?php
class Multiple_upload {
public $set_errors = array();
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1)) {
$this->set_error('file_extension_not_allowed', 'extension_check');
return FALSE;
}
}
return $this;
}
}
public function set_error($message, $type) {
$this->CI->lang->load('upload', 'english');
$this->error_message[] = $this->CI->lang->line($message);
return $this;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
foreach($this->error_message as $msg) {
var_dump($msg);
}
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
Maybe this can help...
public function upload($field = 'userfile')
{
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path))
{
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path))
{
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0]))
{
$check_error = 0;//added this
foreach ($this->files[$field]['name'] as $key => $value)
{
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1))
{
$this->set_error('file_extension_not_allowed', 'extension_check');
$check_error++;
}
}
if($check_error > 0 )
{
return FALSE;
}
return $this;
}
}

How to pass a message from model to controller codeigniter?

I want to pass a message variable in some conditions to controller from model in codeigniter. But when i am doing this it is printing only "No" everytime.
Model is
public function add_city() {
/* Storing form data into an array */
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
And Controller is
public function addingCity() {
$this->add_model->add_city();
var_dump($msg);
//redirect("/city");
}
Try This also
public function add_city() {
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
On controller redirect message with get method -
public function addingCity() {
$msg = $this->add_model->add_city();
redirect("/city?msg=".$msg);
}
And finally print this message on view page
echo $this->input->get('msg');
You need to assign value to $msg in your controller
public function addingCity() {
$msg=$this->add_model->add_city();// assign
var_dump($msg);
//redirect("/city");
}
Try this
public function add_city() {
$city_name = $this->input->post('city');
$city_overview = $this->input->post('overview');
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='$city_name' ORDER BY id ASC");
$result = $query->result_array()
$count = count($result);
if(empty($count))
{
$msg = "No";
return $msg;
}
else{
$data = array(
'city_name'=>$this->input->post('city'),
'city_overview'=>$this->input->post('overview') );
$this->db->insert('city_tbl', $data);
$msg = "Yes";
return $msg;
}
}
In Controller
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;
}
To pass data to view
public function addingCity() {
$data['msg'] = $this->add_model->add_city();
$this->load->view("filename", $data); # ex $this->load->view("index", $data);
}
Error is in your controller function
Try with this code
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;die;
//redirect("/city");
}

Show message on form submit using JForm loadform object in Joomla

I want to show success message after submitting the form. The currently message is working it is saying item successfully saved. But i also want to change this message. Is there a way or am i doing something wrong. This is my code example in model of my custom component.
class IAdonaModelPost extends JModelAdmin
{
protected function allowEdit($data = array(), $key = 'id')
{
//echo "<pre>"; print_R($data); print_r($key);die;
//return JFactory::getUser()->authorise('core.edit', 'com_events.message.'.((int) isset($data[$key]) ? $data[$key] : 0)) or parent::allowEdit($data, $key);
}
public function getTable($type = 'Eventpost', $prefix = 'iAdonaTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
public function getForm($data = array(), $loadData = true)
{
$form = $this->loadForm('com_iadona.post', 'post', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
//$displaymsg = "My message text..";
// JFactory::getApplication()->enqueueMessage($displaymsg);
}
protected function loadFormData()
{
$data = JFactory::getApplication()->getUserState('com_iadona.edit.post.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
}

Resources