How to retrieve an array in Simple MVC Framework? - php

How can I retrieve an array in Simple MVC Framework to show error messages if some input fields are not valid?
Controller:
public function index($error)
{
$data ['title'] = $this->language->get('welcome_text');
View::renderTemplate('header', $data);
View::render('insert/form', $data);
View::renderTemplate('footer', $data);
}
public function save()
{
if (isset($_POST)) {
$data ['is_valid'] = \Helpers\Gump::is_valid($_POST, array(
'firstname' => 'required|min_len,2'
));
if ($data ['is_valid'] === true) {
// continue
} else {
$this->index($data ['is_valid']); // show error messages
die();
}
}
}
View:
<div class="alert alert-danger"><?php var_dump($error); ?></div>
... <button type="submit">Save (calls save())</button>
var_dump($error) always shows bool(false).

Basically you wasn't sent error to render, as i see.
public function index($error)
{
$data ['title'] = $this->language->get('welcome_text');
$data ['error'] = $error;
View::renderTemplate('header', $data);
View::render('insert/form', $data);
View::renderTemplate('footer', $data);
}
View
<div class="alert alert-danger"><?php var_dump($data['error']); ?></div>

Related

database value how to pass dropdown list in codeigniter

How to pass value to drop down list in CodeIgniter?
This is my view file HTML code:
<div class="form-group">
<select name="department" id ="department">
<?php
foreach($dept as $country)
{
echo '<option value="'.$country['dept_id'].'">'.$country['managers_name'].'</option>';
}
?>
</select>
</div>
This is my controller code:
public function department()
{
$this->load->model('insert_model');
$data['dept'] = $this->insert_model->category_name_get();
}
This is my model file code:
function category_name_get()
{
$query = $this->db->get('dept');
if ($query->num_rows >= 1)
{
foreach($query->result_array() as $row)
{
$data[$row['dept_id']]=$row['managers_name'];
}
return $data;
}
}
I think you are searching for Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading method. Here is an example using an array:
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
In your case $data contains the department list in it as an array.
In Your COntroller file you will get all date on $data['dept'] that returned from model.
public function department()
{
$this->load->model('insert_model');
$data['dept'] = $this->insert_model->category_name_get();
$this->load->view('view_file_name',$data);
}
In your view file you will get this data
Just do print_r($dept); and check array..
you will find more info from this link
Probably your model is not returning "proper" data for your view. Perhaps something like this:
function category_name_get()
{
$data = array();
$query = $this->db->get('dept');
if ($query->num_rows >= 1)
{
foreach($query->result_array() as $row)
{
$data[] = array(
'dept_id' => $row['dept_id'],
'managers_name' => $row['managers_name']
);
}
}
return $data;
}
function category_name_get()
{
$query = $this->db->get('dept');
if ($query->num_rows() >= 1)
{
foreach($query->result_array() as $row)
{
$data[$row['dept_id']]=$row['managers_name'];
}
return $data;
}
}
Use num_rows() instead of num_rows. I hope it works now.

Codeigniter Bootstrap Alert not Working

I'm trying to make alert with cross sign. Unfortunately cross sign not working. I have included jquery before bootstrap.js. Here is my model. Thanks in Advance
public function create(){
$data = array('name'=> $this->input->post('name'));
$this->db->insert('dbname', $data);
echo'
<div class="alert alert-success">
×You have successfully posted
</div>
';
exit;
}
Change this to
×You have successfully posted
this
×You have successfully posted
And as well as use Model to write data into database. Use follows
In controller
public function create(){
$this->load->model('Model_name');
$result = $this->Model_name->insert_data();
if($result == 1)
{
?>
<div class="alert alert-success">
×You have successfully posted
</div>
<?php
}
else
{
?>
<div class="alert alert-error">
×Failed to poste
</div>
<?php
}
}
In Model
public function insert_data()
{
$data = array(
'name'=> $this->input->post('name')
);
if(!$this->db->insert('dbname', $data))
{
return $log = 0;
}
else
{
return $log = 1;
}
}

Yii: REST api problems

i'm beginner in yii and in the Yii Application Development CookBook(2nd edition) on pages 105 to 113 when i'm running this codes, add button does not work, While everything is in accordance with the text of the book, where is problem? please help me.
Some code easily run but others like this are not.
controller is:
<?php
class TodoController extends Controller
{
public function actionIndex()
{
$task = new Task();
$this->render('index', array(
'task' => $task,
));
}
public function actionTask()
{
$req = Yii::app()->request;
if($req->isPostRequest) {
$this->handlePost($req->getPost('id'),
$req->getPost('Task'));
}
elseif($req->isPutRequest) {
$this->handlePut($req->getPut('Task'));
}
elseif($req->isDeleteRequest) {
$this->handleDelete($req->getDelete('id'));
}
else {
$this->handleGet($req->getParam('id'));
}
}
private function handleGet($id)
{
if($id) {
$task = $this->loadModel($id);
$this->sendResponse($task->attributes);
}
else {
$data = array();
$tasks = Task::model()->findAll(array('order' => 'id'));
foreach($tasks as $task) {
$data[] = $task->attributes;
}
$this->sendResponse($data);
}
}
private function handlePut($data)
{
$task = new Task();
$this->saveTask($task, $data);
}
private function handlePost($id, $data)
{
$task = $this->loadModel($id);
$this->saveTask($task, $data);
}
private function saveTask($task, $data)
{
if(!is_array($data)){
$this->sendResponse(array(), 400, array('No data
provided.'));
}
// $task->setAttributes($data);
$task->attributes = $data;
if($task->save()) {
$this->sendResponse($task->attributes);
} else {
$errors = array();
foreach($task->errors as $fieldErrors) {
foreach($fieldErrors as $error) {
$errors[] = $error;
}
}
$this->sendResponse(array(), 400, $errors);
}
}
private function handleDelete($id)
{
$task = $this->loadModel($id);
if($task->delete()) {
$this->sendResponse('OK');
}
else {
$this->sendResponse(array(), 500, array('Unable to
delete task.'));
}
}
private function loadModel($id)
{
$task = Task::model()->findByPk($id);
if(!$task) {
$this->sendResponse(array(), 404, array('Task not
found.'));
}
return $task;
}
private function sendResponse($data, $responseCode = 200,
$errors = array())
{
$messages = array(
200 => 'OK',
400 => 'Bad Request',
404 => 'Not Found',
500 => 'Internal Server Error',
);
if(in_array($responseCode, array_keys($messages))) {
header("HTTP/1.0 $responseCode ".$messages[$responseCode],
true, $responseCode);
}
echo json_encode(array(
'errors' => $errors,
'data' => $data,
));
Yii::app()->end();
}
}
?>
and view is:
<?php
Yii::app()->clientScript->registerPackage('todo');
$options = json_encode(array(
'taskEndpoint' => $this->createUrl('todo/task'),
));
Yii::app()->clientScript->registerScript('todo', "todo.
init($options);", CClientScript::POS_READY);
?>
<div class="todo-index">
<div class="status"></div>
<div class="tasks"></div>
<div class="new-task">
<?php echo CHtml::beginForm()?>
<?php echo CHtml::activeTextField($task, 'title')?>
<?php echo CHtml::submitButton('Add')?>
<?php echo CHtml::endForm()?>
</div>
</div>
<script id="template-task" type="text/x-dot-template">
<div class="task{{? it.done==1}} done{{?}}" data-id="{{!it.
id}}">
<input type="checkbox"{{? it.done==1}}checked {{?}}/>
<input type="text" value="{{!it.title}}" />
Remove
</div>
</script>
I want when click on the add button, task added.

undefined variable error in codeigniter model

I am working on a registration form
When i submit the form after the entering details the registration data get stored in the database but the the page shows the following error
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: dbRet
Filename: models/registration_model.php
Line Number: 47
I am not getting the prolem the same code is working good at the localhost but what is the problem at server??
This is the model Code
class Registration_model extends CI_Model {
function __construct()
{
parent::__construct();
}
function index()
{
$data['page_title'] = 'Registration';
$this->load->view('client/general/head',$data);
$this->load->view('client/general/header');
$this->load->view('registration');
$this->load->view('client/general/footer');
}
function busregister()
{
$data['page_title'] = 'Registration';
$this->load->view('business/registration1');
}
public function save_registration($un,$email,$pwd,$utype)
{
try
{
$data = array(
'username' => $un,
'password' => $pwd,
'email' => $email
);
//print_r($data);
//die();
$this->load->database();
$this->db->reconnect();
if($utype=='buss')
{
$dbRet=$this->db->insert('business', $data);
}
else
{
$dbRet-$this->db->insert('user', $data);
}
if (!$dbRet) {
$ret['ErrorMessage'] = $this->db->_error_message();
$ret['ErrorNumber'] = $this->db->_error_number();
log_message('error', "DB Error: (".$ret['ErrorNumber'].") ".$ret['ErrorMessage']);
$this->db->close();
return $ret['ErrorNumber'];
}
else{
$rid=$this->db->insert_id();
$this->db->close();
return $rid;
}
}
catch (Exception $e){
return -1;
}
}
}?>
This is the controller code
class Registration extends CI_Controller {
public function index()
{
$this->load->helper(array('registration','date','country'));
$this->load->helper('client');
$this->load->model('Registration_model');
if ($this->input->post("submit_registration",TRUE))
{
if($this->form_validation->run("stud_registration_rules"))
{
$this->load->library(array('encrypt'));
$stud_first_name = $this->input->post('stud_user_name');
$stud_email = $this->input->post('stud_email');
$stud_pass = $this->input->post('stud_password');
$retval=$this->Registration_model->save_registration($stud_first_name,$stud_email,$this->encrypt->encode($stud_pass),"user");
var_dump($this->encrypt->encode($stud_pass));
if($retval!==-1){ //SAVE SUCCESS
$this->session->set_flashdata('flashSuccess', 'Record saved successfully.');
redirect('/');
}
else{
$this->session->set_flashdata('flashError', 'Error Saving Record');
redirect('/registration');
}
}
else{
// FORM IS NOT VALIDATED
$this->session->set_flashdata('flashError', 'Validation fields error');
redirect('/registration');
}
}
$this->Registration_model->index();
}
}
This is the view code
<div class="content">
<div class="container_12">
<div class="grid_12">
<?php if($this->session->flashdata('flashSuccess')) : ?>
<div class="alert alert-success">
×
<p><?php print_r($this->session->flashdata('flashSuccess'));
?></p>
</div>
<?php endif; ?>
<?php if($this->session->flashdata('flashError')) : ?>
<div class="alert alert-danger">
×
<p><?php print_r($this->session->flashdata('flashError'));
?></p>
</div>
<?php endif; ?>
<?php echo registration_form();?>
</div>
</div>
In your Model code Registration_model , Else part assignment operator is wrong
change the following line
$dbRet-$this->db->insert('user', $data);
to
$dbRet = $this->db->insert('user', $data);

execute another function within function with data variables

need help on this one:
here's a my sample code,
i would like to add a validation message if a preg_match occurs:
pls. see inline comments for more details..
public function supplier_entry()
{
if (preg_match("/[\'^£#&*...etc.../", $this->input->post('supplier')))
{
//add or pass validation message, ex. $msg = 'Invalid Supplier Name';
// i tried $this->supplier_entry_form($msg); but its not working.
$this->supplier_entry_form();
}else{
$post_data = array(
'supplier_name' =>$this->input->post('supplier'),
'user' => $this->input->post('user'),
'trx_id' =>$this->input->post('trx_id'),
);
$this->load->model('user_model');
$this->load->model('product_model');
$this->product_model->add_new_supplier($post_data);
$user_data['trx'] = 'Supplier Entry';
$user_data['username'] = $this->user_model->user_info();
$trx_data['supplier'] = $this->product_model->get_supplier_list();
$trx_data['msg'] = 'Supplier Posted.';
$this->load->view('header',$user_data);
$this->load->view('item_supplier', $trx_data);
}
}
thanks in advance..
public function supplier_entry_form()
{
$this->load->model('user_model');
$this->load->model('product_model');
$user_data['username'] = $this->user_model->user_info();
$user_data['trx'] = 'Supplier Entry';
$trx_data['supplier'] = $this->product_model->get_supplier_list();
$this->load->view('header', $user_data);
$this->load->view('item_supplier', $trx_data);
}
Use the built in form validation.
$this->load->library('form_validation');
$this->form_validation->set_rules($this->input->post('supplier'), 'Supplier', 'trim|callback_pregMatchSupplier');
if($this->form_validation->run()==FALSE)
{
$this->supplier_entry_from();
}
// continue code here if validation passes.
function pregMatchSupplier()
{
if (preg_match("/[\'^£#&*...etc.../", $this->input->post('supplier')))
{
return FALSE;
} else {
return TRUE;
}
Then in the view you echo out the validation errors:
<?php echo validation_errors(); ?>
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

Categories