KO3 - Kohana 3 - How can I pass $_POST data from a controller/action back to the view/form that called it? - validation

I am trying to validate a form submission in Kohana 3. I have the form::open point to my action_create in my controller which successfully validates the data posted to it from the form in my view. If the data passes validation, a new item is created as intended, and the user is redirected to the item that was just created. This works correctly. If the data fails validation, however, I would like the user to be directed back to the originating view/page while retaining a variable containing the data that was posted so that I can repopulate the form and display errors.
In short, how can I pass data from a view -> controller -> original view?
Thank you, everyone!

The user also posed this question on the Kohana forums.
Those seeking an answer to this should have look over there.

I assume you're using Controller_Template.
File views/form.php:
// Set default variables if variables not passed to this view
$username = isset($username) ? $username : '';
echo Form::open('login');
// Input: username
echo Form::label('username', 'Username');
echo Form::input('username', $username);
echo isset($errors['username']) ? $errors['username'] : '';
// Input: username
echo Form::label('password', 'Password');
echo Form::input('password', $password);
echo isset($errors['password']) ? $errors['password'] : '';
echo Form::close();
File views/template.php
<html>
<head><title>My Website</title></head>
<body>
<?php echo isset($content) ? $content : ''; ?>
</body>
</html>
File classes/controller/user.php
Class Controller_User extends Controller_Template {
public $template = 'template';
public function index()
{
$this->template->content = $this->display_form('form');
}
public function login()
{
// Setup validation & rules here
// Check validation, assume $validation is Validation object
if ($validation->check()
{
// Validation succeeded. Do anything you want here
}
else
{
// Validation failed. Display form with entered values
$form_vars = $_POST;
$form_vars['errors'] = $validation->errors();
// Display form
$this->template->content = $this->display_form('form', $form_vars);
}
}
// Displaying form
private function display_form($form_file, $form_vars=NULL)
{
$form = View::factory($form_file);
if ($form_vars != NULL)
{
foreach($form_vars as $key => $value)
{
$form->$key = $value;
}
}
return $form;
}
}
Hope that helps!

Related

codeigniter pagination - how to keep on same page after deleting row

I am using codeigniter pagination library and doing update and delete through form. The problem is when I delete or update any record after delete or update I redirected back to 1st page even if I am at 4th page. How I can redirected to the same page at which I have done update or delete.
Here is my controller code for update and delete functions:
public function update_att(){
if(isset($_POST['update'])){
$u_id = $_POST['at_id'];
if($_POST['status']=="Present"){
$data = array(
'status'=>"Absent"
);
$this->db->where('at_id', $u_id);
$this->db->update('attendence', $data);
}elseif ($_POST['status']=="Absent") {
$data = array(
'status'=>"Present"
);
$this->db->where('at_id', $u_id);
$this->db->update('attendence', $data);
}
redirect("usr/att_list", "refresh");
}
}
public function delete_att(){
if (isset($_POST['delete'])) {
$at_id = $_POST['at_id'];
$this->db->where('at_id', $at_id);
$this->db->delete('attendence');
}
redirect("usr/att_list" );
}
Currently I am redirecting to the first page , any suggestion how I redirect to that page where I have done delete or update.
Add <input type='hidden' name='current_page' value='<?php echo $current_page?>' /> to your form.
Keep in mind you need to populate $current_page with something like
$current_page = ''; // empty means first page
if( isset($_REQUEST['current_page'] ){
$current_page = $_REQUEST['current_page'];
}
Then based on your sample you just modifiy the redirect path as follows (for both your functions):
public function delete_att(){
if (isset($_POST['delete'])) {
$at_id = $_POST['at_id'];
$this->db->where('at_id', $at_id);
$this->db->delete('attendence');
}
redirect("usr/att_list".(strlen($current) ? "?".$current : "" );
}
Note:
Your path to your page should look something like this domain.com/controller/your_page_with_pagination/?current_page=A_NUMBER then in your controller/your_page_with_pagination you adjust the data you wish to output based on $_GET['current_page']
Edit based on your link:
public function att_list($id = ""){
/**
* Keep your data in array
*/
$this->data = array();
/**
* Add the page number ($id) to the array
* Check for url /:id first , or else check for a $_GET/$_POST current_page (this will be triggered when you submit your form)
*/
$this->data['current_page'] = is_numeric($id) ? $id : (isset($_REQUEST['current_page'] ? $_REQUEST['current_page']: 0);
/**
* This is your 'keep on the same page' line
* $this->data['current_page'] will act as an offset in your query
* You can read about 'offset' here https://www.w3schools.com/php/php_mysql_select_limit.asp
* $this->data['my_desired_records'] must be generated into your <form> ... </form> , and the same form must contain the input with name='current_page'
*/
$this->data['my_desired_records'] = $this->your_model->get_data($this->data['current_page']);
/**
* Pass the whole array into your view
*/
$this->load->view('path/to/view', $this->data);
}
Then in your view add in your form <input type='hidden' name='current_page' value='<?php echo $this->data['current_page']?>' />

not able get flashdata in CodeIgniter

Here is my controller code
function index() {
echo $this->session->flashdata('message');
$this->load->view('categoryView');
}
function delete() {
$products = $this->item_model->get_category_id($category_id);
if (count($products)) {
$message = 'Category Name is used by the product. Please change them to another category!';
}
else {
$category_id = $this->product_category_model->delete($category_id);
$message = ($category_id) ? 'Category Deleted Successfully' : 'Failed to Delete Category';
}
$this->session->set_flashdata('message', $message);
redirect('category', 'refresh');
}
After calling the delete function the flashdata has to be set and retrieve that value in index() function of the same controller but I can't.
Am also tried the $this->session->keep_flashdata('message'); before redirect to index function. But still am not get any value in index function.
Also changed $config['sess_expire_on_close'] = FALSE; to $config['sess_expire_on_close'] = TRUE; Still am not get the result.
I am wasted more time(nearly half day). Please anybody help to retrieve the flas data in codeigniter.
There are several probabilities:
1- Check your browser cookie. See if it allows cookies or if any other extension is intervening.
2- Refresh might not send the browser a new request (which thus mean a new URL). Try it for another controller see if it make any change
3- hard code the set_flashdata() with hard-coded value than a variable. set_flashdata("message", "Thank you");
In codeingitor you cannot echo anything in controller.
You have to set in $this->session->flashdata('message'); in view file not in index() function of controller
Try again by putting $this->session->flashdata('message'); in "categoryView" file where you want to display flash message.
You could try:
function set_flashdata_notification($notify_type, $msg, $error_code = null)
{
$ci =& get_instance();
$flashdata_data = set_notification_array($notify_type, $msg, $error_code);
$ci->session->set_flashdata($flashdata_data);
}
function delete() {
$products = $this->item_model->get_category_id($category_id);
if (count($products)) {
set_flashdata_notification('Category Name is used by the product.','Please change them to another category!');
redirect('path_to_view/view','refresh');
}

codeigniter: using uri segment in model

I am using uri segment to delete info in my database:
anchor('site/delete_note/'.$row->id, 'Delete')
Model:
function delete_note()
{
$this->db->where('id', $this->uri->segment(3));
$this->db->delete('note');
}
It works fine, but I want to do the same for updating my info and can't get it work
So this is link in view:
anchor('site/edit_note/'.$row->id, 'Edit')
My controller:
function edit_note()
{
$note_id = $this->uri->segment(3);
$data['main_content'] = 'edit_note';
$this->load->view('includes/template', $data);
$this->load->library('form_validation');
$this->form_validation->set_rules('content', 'Message', 'trim|required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('Note_model');
$this->Note_model->edit_note($note_id);
redirect('site/members_area');
}
}
My model:
function edit_note($note_id)
{
$content = $this->input->post('content');
$data = array('content' => $content);
$this->db->where('id', $note_id);
$this->db->update('note', $data);
}
My view of edit_note:
<?php
echo form_open('site/edit_note');
echo form_textarea('content', set_value('content', 'Your message'));
echo form_submit('submit', 'Change');
echo anchor('site/members_area', 'Cancel');
echo validation_errors('<p class="error">'); ?>
Edit doesn't work as delete, when i am trying to get segment directly in edit model, as I used in delete model.
If I set $note_id to a number in my controller, instead of this '$this->uri->segment(3)', it updates my database. But if I use getting segment it doesn't work. I thought uri segments are available in controller as in model, but there is something I don't know.
Better yet, instead of manually reading the IDs via the segments, you could change your functions to be:
function delete_note($note_id)
and
function edit_note($note_id)
And remove the $note_id = $this->uri->segment(3); lines.
And as silly as it'll sound, the generated URL is definitely correct, right?
And last question, have you done anything with routes?
Edit
I've also noticed that in edit, you use this in your form:
echo form_open('site/edit_note');
So when the form submits, the URL it submits to is site/edit_note instead of site/edit_note/{SOME_ID}. So once you make your changes, and the form submits, there won't be a 3rd URL segment!
Well there are some logical errors in your code.
function edit_note()
{
$note_id = $this->uri->segment(3);
$data['main_content'] = 'edit_note';
$this->load->view('includes/template', $data);
//// What is the use of loadig a view when you are editing
$this->load->library('form_validation');
$this->form_validation->set_rules('content', 'Message', 'trim|required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('Note_model');
$this->Note_model->edit_note($note_id);
redirect('site/members_area');
}
}
Instead do it like this
function edit_note()
{
if($this->input->post()){
$this->load->library('form_validation');
$this->form_validation->set_rules('content', 'Message', 'trim|required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('Note_model');
$this->Note_model->edit_note($note_id);
redirect('site/members_area');
}
}else{
$note_id = $this->uri->segment(3);
$data['main_content'] = 'edit_note';
$this->load->view('includes/template', $data);
}
}
MOST IMPORTANT
And the other thing you should note that you are using anchor to access edit note but not actually submitting a form so it is not getting any post data to update.
In my view it's a 'bad' approach to use uri segments in your models... you should pass an id as a parameter from your controller functions ..
function delete_note()
{
$this->db->where('id', $this->uri->segment(3));
$this->db->delete('note');
}
What if you want to re-use this delete method? e.g. deleting notes from an admin panel, via a cron job etc then the above relies upon the uri segment and you will need to create additional delete methods to do the job. Also, if you were to continue with the same you don't even need a model then .. just call these lines in your controllers if you know what I mean ...
$this->db->where('id', $this->uri->segment(3));
$this->db->delete('note');
so best is to change it to similar to your edit_note() model function.

codeigniter validate

Hello I have a forum and when a user creates a comment, I want that if he didn't type anything I want to show him an error that he must type something in :) but I dont know how to put him the the thread he is in.
I have this
if($this->_submit_validate_comment() == false) {
$this->post(); return;
}
function _submit_validate_comment() {
$this->form_validation->set_rules('kommentar', 'kommentar', 'required|min_length[4]');
return $this->form_validation->run();
}
You could do this with jquery but if that is not an option you could get the forum or topic id from the url (assuming your are using the url this way).
For example:
http://yoursite.com/forum/topic/12
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
redirect('/forum/topic/'. $topic_id);
}
Or
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
$this->topic($topic_id);
}
Hope this helps.
Thanks for helping i can see what you mean but it just dont work :b,
i have this
$topic_id = $this->uri->segment(3);
$this->post($topic_id);
return;
and my url is
localhost:8888/ci/index.php/forum/create_comment
it looks like it cant find the ID
my URL to the forum is
localhost:8888/ci/index.php/forum/post/33
this is my functions
function create_comment() {
if($this->_submit_validate_comment()
== false) { $id = $this->uri->segment(3);
$this->post($id); return;
//echo "validate fejl, kontakt lige
en admin!"; } else { $data =
array( 'fk_forum_traad' =>
$this->input->post('id'),
'brugernavn' =>
$this->session->userdata('username'),
'indhold' =>
$this->input->post('kommentar'),
'dato' => 'fejl' );
$this->load->model('forum_model');
$this->forum_model->create_comment($data);
redirect('/forum/post/'.
$this->input->post('id').'',
'refresh'); }
}
function post($id) {
$this->load->model('forum_model');
$data['query'] =
$this->forum_model->posts($this->uri->segment(3));
$this->load->model('forum_model');
$data['comments'] =
$this->forum_model->comments($this->uri->segment(3));
$data['content'] = 'forum_post_view';
$this->load->view('includes/template',
$data); }
Why not pass in the return uri in the form submission using a hidden input field? No additional work will be needed by the controller other than validation of the return uri before performing a redirect.
Place the validation error string in session class's flashdata for echoing out in the form, along with any other data used to pre-populate your form)

Zend Framework :: Is this code good for user login (Its begining- because that I want to know if its can be improve)

I new in Zend.
Main Question:
Is this code good for user login (Its beginning- because that I want to know if its can be improve)?
Thanks
view index.phtml
<? echo $this->form
controller IndexAction.php
public function indexAction() {
$form=new Application_Form_Login();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
echo " test value username: ".$form->getValue('username');
}
}
}
form Login.php
public function init() {
$this->setMethod('post');
$this->setName('user login');
$username = new Zend_Form_Element_Text('username');
$username->setLabel("username")
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$password = new Zend_Form_Element_Password('password');
$password->setLabel('password')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$submit = new Zend_Form_Element_Submit('submit');
$this->addElements(array($username, $password, $submit));
}
So far, so good. IMO there's nothing to improve on this further. It renders the form and if the request is POST it validates the form against the data in the POST array.
what is really special in your code? standart pattern.

Resources