CodeIgniter - 两个表单,一页 [英] CodeIgniter - Two Forms, One Page

查看:183
本文介绍了CodeIgniter - 两个表单,一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个根本的问题,在理解MVC的概念和一次显示多个窗体。我尝试了各种方法,但我仍然坚持 - 这是因为我不认为我理解CI和MVC正确。



我试过使用2个不同的视图为两种不同的形式。没有工作。我试着在我的控制器中使用每个窗体一个函数。这也没有工作。我不知道该怎么办。



我应该这样做吗


    <
  1. 为此索引中的每个表单构建我的表单元素

  2. 创建一个控制器,创建1个显示这两种表单并在index()中调用的视图

  3. 使用form_open将提交操作定向到另一个函数 - 调用validate()

  4. 验证进入的所有内容,发回错误

  5. 不知何故,这是我没有得到的主要位,如果表单填写正确,请完成一个动作。 / li>

6是我最大的问题。不知道怎么做。例如,在成功完成表单后,我希望我的用户在选择的位置创建一个目录 - 所以我使用mkdir() - 所以我需要一个if语句在validate()函数或什么??



UPDATE



目前为止已创建;



控制器:

 <?php if (!defined('BASEPATH'))exit('不允许直接脚本访问); 

//表单CodeIgniter控制器
类Admin扩展CI_Controller {

  //控制器构造函数
public function __construct()
{
parent :: __ construct
//加载表单帮助器来验证表单
$ this-> load-> helper(array('form','url'));
$ this-> load-> library('form_validation');
}

// *********************************** ************** //

//为视图准备数据以输出表单
public function index()
{

// ***************************************** ************ //
//返回单选按钮的下拉列表,每个目录一个
$ map_one = $ this-> recursive_model-> iterate_add_folder_names ();
$ data ['folder_list_add'] = $ map_one;
// ******************************************** ******** //
// ********************************** ******************* //
//也返回一个单选按钮的下拉列表(略有不同),每个目录一个
$ map_two = $ this-> recursive_model-> iterate_folder_names();
$ data ['folder_list_select'] = $ map_two;
// ******************************************** ******** //

//加载视图和窗体
$ this-> load-> view('templates / header.php');
$ this-> load-> view('admin / add_new_folder.php',$ data);
$ this-> load-> view('admin / add_new_file.php',$ data);
$ this-> load-> view('templates / small_footer.php');
}

// *********************************** ************** //

//如果为当前结构添加一个新目录,函数
public function add_folder()
{
//需要选择一个目录
$ this-> form_validation-> set_rules('new_folder','New Folder','required');
//并命名新目录
$ this-> form_validation-> set_rules('new_folder_name','New Folder Name','required');

if($ this-> form_validation-> run()=== FALSE)
{
$ this-&
}
else
{
if($ this-> input-> post())
{
$ new_folder = $ this-> ; input-> post('new_folder');
$ new_folder_name = $ this-> input-> post('new_folder_name');
$ folder_path =/var/www/html/mike/content\".$new_folder.\"/\".$new_folder_name;
mkdir($ folder_path,0777);
$ this-> index();
}
}

}

// ******************* **************************** //

public function add_file()
{

//文件夹位置和文件名
$ folder_name = $ this-> input-> post('folder_name');
$ new_folder_name = $ this-> input-> post('file_name');

//验证规则
$ this-> form_validation-> set_rules('folder_name','文件夹名称','必填'
$ this-> form_validation-> set_rules('file_name','文件名','必填');

//如果验证有错误
if($ this-> form_validation-> run()=== FALSE)
{
/ /每当试图上传一个新文件夹时被卡在这里:
$ this-> index();
}
//如果没有验证错误
else
{
// $ folder_name将类似于http://www.example.com/publications/people/reports
$ config ['upload_path'] = $ folder_name ;
$ config ['allowed_types'] ='gif | jpg | png | html | pdf | xls';
$ this-> load-> library('upload',$ config);

//如果文件无法加载(由于$ config可能?)
if(!$ this-> upload-> do_upload())
{
$ error = array('error'=> $ this-> upload-> display_errors());
$ this-> index();
}
else
{
$ data = array('upload_data'=> $ this-> upload-> data());
$ this-> index();
}

}

}

// *************** ******************************** //

}



这里是一个视图(add_new_file.php);

 < div id =container> 

< h1>上传文件/发布< / h1>

< div id =body>

<?php // echo $ error;?>

<?php echo form_open_multipart('admin / add_file');?>

<?php echo $ folder_list_select; ?> & nbsp;& nbsp;
< input type =filename =file_namesize =20/> & nbsp;& nbsp;
< input type =submitvalue =upload/>

< / form>

< / div>



这是另一个(add_new_folder .php)

  div id =container> 

< h1>添加新文件夹< / h1>

< div id =body>

<?php echo validation_errors(); ?>

<?php echo form_open('admin / add_folder');?>

<?php echo $ folder_list_add; ?> & nbsp;& nbsp;
新文件夹名称:< input type =textname =new_folder_name> & nbsp;& nbsp;
< input type =submitvalue =upload/>

< / form>

< / div>



线程。



基本上,我可以得到第一部分工作 - 添加一个文件夹 - 但我不能得到添加一个文件工作。这是因为如果($ this-> form_validation-> run()=== FALSE)总是返回false。我认为它可能是在看其他形式的表单元素 - 它不应该做。

解决方案


我应该这样做吗?

1。创建一个控制器并在其中有一个index()函数。

[让我们为了谈话,调用此控制器 Users thx -ed]


这很酷。你也可以在控制器中有一个函数 edit banana 任何一种方式工作。只需使用 index 方法(函数),该网址可能就像 http://example.com/index.php/users ,而如果你添加另一个方法到控制器如 banana ,url可能看起来像 http://example.com/index。 php / users / banana


2。为此索引()中的每个表单构建我的表单元素


好吧,典型的表单元素不是在控制器中创建的。这是MVC中的V来的地方 - 你看到的东西进入视图



所以,可以做一些像

  
类用户扩展CI_Controller {
function index(){
//索引方法
}

函数banana(){
$ this - > load-> view('banana_view');
}
}

然后在 /banana_view.php ,您将创建表单。当您访问 http://example.com/users/banana 时,您将看到您在 banana_view.php


3。创建1个视图,显示这两种形式并从index()中调用它


当然,但请记住,每个< form>< / form> 需要自己的< input type =submitname =Lets GO> ; 里面,因此需要某处发送每个表单数据。这是 action =。您可以将其舍弃,但请注意,它会将表单发送到您当前所在的任何页面(在本例中, http://example.com/index.php/users/banana ),所以你必须在 banana()方法中处理表单数据。但是,通常,它将通过 form_open()设置。像 form_open('index.php / users / eat_banana'); 会产生< form action =index.php / users / eat_banana ...


4。使用form_open将提交操作定向到另一个函数 - 调用validate()


只是不要调用 late_for_dinner 。但是,验证有点宽 - 验证什么?验证为什么?至于验证 http://ellislab.com/codeigniter/user-guide /libraries/form_validation.html 。但是你应该在编写CodeIgniter的基础知识之后穿过那座桥梁(不会花很长时间)。


5。验证进入的所有内容,发回错误


查看最后一个问题。



< >

6。


很多时候,如果表格填写正确,

  class Users extends CI_Controller {

function index(){
//索引方法
}

function banana(){
$ this-> load-> view('banana_view');
}

//假设form_open('index.php / users / eat_banana'); in banana_view
function eat_banana(){
//确保这是一个POST
if($ this-> input-> post()){
//做数据的事情
//通常它被保存到数据库
//通过一个模型(MVC中的M)
// http://ellislab.com/codeigniter/user -guide / general / models.html

if($ saved_to_db){
//设置要发送到视图的消息
$ data ['message'] =一切都进行好;
} else {
$ data ['message'] =但谁是数据库?数据没有保存:(;
}
//加载视图并发送数据
$ this-> load-> view('eat_banana',$ data);
}
}

application / views / eat_banana.php

 <!DOCTYPE html> 
< html>
< head>< / head>
< body>
< >
< b>表单已提交。< / b>< br />
消息是:<?php echo $ message;?>
< div>
< / html>

/ p>

  class用户扩展CI_Controller {

function index(){
//索引方法
}

function banana(){
$ this-> load-> view('banana_view');
}

// assume form_open('index.php / users / eat_banana'); in banana_view
function eat_banana(){
//确保这是一个POST
if($ this-> input-> post()){
//用
做事情if($ saved_to_db){
//只是将它们发送到主页
redirect('/');
} else {
//发送回
redirect('index.php / users / banana');
}
}
}



M 适用于型号。模型用于与数据库通信。



V 用于 Vend 查看。视图呈现文本,表单,图片,GIF,任何到屏幕。这是想法。没有什么阻止你从 echo 从你的控制器中产生一个巨大的未最小化的JavaScript应用程序。这完全不是MVC。



C 是控制器的。控制器调用并发送数据到视图,接收从视图发送的数据,获取数据并将其发送到要保存在数据库中的模型(虽然CodeIgniter也不以任何方式强制执行此操作;如果要保存将数据直接从控制器传输到数据库,但这显然也会破坏MVC主体),从数据库检索数据并将其发送到视图以供显示。这些都是基本的。


I'm having a fundamental problem in understanding the concept of MVC and displaying more than one form at a time. I've tried a variety of methods but I'm still stuck - and that's because I don't think I'm understanding CI and MVC correctly.

I tried using 2 different views for the two different forms. Didn't work. I tried using one function per form in my controller. That didn't work either. I don't know what to do.

Should I be doing this;

  1. Create a controller and have an index() function in it.
  2. Build up my form elements for each form within this index()
  3. Create 1 view that displays both forms and call it from within index()
  4. Use form_open to direct the submit action to another function - call it validate()
  5. Validate everything that comes in, send back errors
  6. Somehow, and this is the main bit I don't get, complete an action if the form has been filled in correctly.

6 Is my biggest problem. Don't know how to do that. For example, on successful completion of the form I want my user to have created a directory at a chosen location - so I'm using mkdir() - so do I need an if statement within the validate() function or what??

UPDATE

Here is the code I have created so far;

Controller:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// Forms CodeIgniter controller class Admin extends CI_Controller {

// Controller constructor
public function __construct()
{
    parent::__construct();
    // Load form helper required to validate forms
    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');        
}

//*************************************************//

// Prepare data for the view to output the forms
public function index()
{

    //*****************************************************//
    //returns a drop down list of radio buttons, one for each directory
    $map_one = $this->recursive_model->iterate_add_folder_names();
    $data['folder_list_add'] = $map_one;    
    //****************************************************//
    //*****************************************************//
    //also returns a drop down list of radio buttons (slightly different), one for each directory
    $map_two = $this->recursive_model->iterate_folder_names();
    $data['folder_list_select'] = $map_two; 
    //****************************************************//

    //load the views and the forms
    $this->load->view('templates/header.php');
    $this->load->view('admin/add_new_folder.php', $data);
    $this->load->view('admin/add_new_file.php', $data);
    $this->load->view('templates/small_footer.php');
}

//*************************************************//

//function if adding a new directory to the current structure
public function add_folder()
{
    //need to select a directory for it to go under
    $this->form_validation->set_rules('new_folder', 'New Folder', 'required');
    //and name the new directory
    $this->form_validation->set_rules('new_folder_name', 'New Folder Name', 'required');

    if ($this->form_validation->run() === FALSE)
    {
        $this->index();
    }
    else
    {   
        if($this->input->post())
        {
            $new_folder = $this->input->post('new_folder');
            $new_folder_name = $this->input->post('new_folder_name');
            $folder_path = "/var/www/html/mike/content".$new_folder."/".$new_folder_name;
            mkdir($folder_path, 0777);
            $this->index();
        }
    }

}

//*************************************************//

public function add_file()
{

    //folder location and name of file
    $folder_name = $this->input->post('folder_name');
    $new_folder_name = $this->input->post('file_name');

    //validation rules
    $this->form_validation->set_rules('folder_name', 'Folder Name', 'required');
    $this->form_validation->set_rules('file_name', 'File Name', 'required');

    //if there is an error with validation
    if ($this->form_validation->run() === FALSE)
    {
        //gets stuck here every time when trying to upload a new folder :(
        $this->index();
    }
    //if there is not an error with validation
    else
    {   
        //$folder_name will be something like "http://www.example.com/publications/people/reports"
        $config['upload_path'] = $folder_name;
        $config['allowed_types'] = 'gif|jpg|png|html|pdf|xls';
        $this->load->library('upload', $config);

        //if file cannot be loaded (due to $config perhaps?)
        if ( ! $this->upload->do_upload())
        {
            $error = array('error' => $this->upload->display_errors());
            $this->index();
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());
            $this->index();
        }

    }   

}

//*************************************************//

}

Here is one view (add_new_file.php);

<div id="container">

<h1>Upload A File/Publication</h1>

<div id="body">

<?php //echo $error;?>

<?php echo form_open_multipart('admin/add_file');?>

<?php echo $folder_list_select; ?>   &nbsp;&nbsp; 
<input type="file" name="file_name" size="20" />   &nbsp;&nbsp; 
<input type="submit" value="upload" />

</form>

</div>

Here is the other (add_new_folder.php)

div id="container">

<h1>Add A New Folder</h1>

<div id="body">

<?php echo validation_errors(); ?>

<?php echo form_open('admin/add_folder');?>

<?php echo $folder_list_add; ?>   &nbsp;&nbsp; 
New Folder Name: <input type="text" name="new_folder_name">   &nbsp;&nbsp; 
<input type="submit" value="upload" />

</form>

</div>

I hope this helps answer this thread.

Basically, I can get the first section to work - adding a folder - but I cannot get the adding a file to work. This is because if ($this->form_validation->run() === FALSE) is always returning false. I think it might be looking at the form elements in the other form - which it shouldn't do. What am I missing?

解决方案

Should I be doing this;
1 . Create a controller and have an index() function in it.
[let's, for the sake of conversation, call this controller Users thx -ed]

Sure. That's cool. You could also have a function in that Controller called edit, or banana or whatever; either way works. With using just the index method (function), the url might look like http://example.com/index.php/users whereas if you add another method to the controller like banana, the url might look like http://example.com/index.php/users/banana.

2 . Build up my form elements for each form within this index()

Well, typically form elements are not created in the controllers. This is where the V in MVC comes in -- stuff you view goes into a view.

So, one might do something like

// Users Controller
class Users extends CI_Controller{
    function index(){
        //index method
    }

    function banana(){
        $this->load->view('banana_view');
    }
}

then in application/views/banana_view.php, you create your form. When you visit http://example.com/users/banana, you will see the form you created in banana_view.php.

3 . Create 1 view that displays both forms and call it from within index()

Sure, that'd work just fine. But remember that each <form></form> needs its own <input type="submit" name="Lets GO"> inside and thusly needs somewhere to send each forms data. This is the action="". You can leave it out, but beware that it will then send the form to whatever page you are currently on (in our case here, http://example.com/index.php/users/banana), so you have to have something in the banana() method to handle the form data. But, typically, it will be set via form_open(). Something like form_open('index.php/users/eat_banana'); will generate <form action="index.php/users/eat_banana"...

4 . Use form_open to direct the submit action to another function - call it validate()

Just don't call it late_for_dinner. But seriously, validate is a bit broad -- validate what? Validate why? As to validation, http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html. But you should cross that bridge after you grok the fundamentals of CodeIgniter (won't take long).

5 . Validate everything that comes in, send back errors

See last question.

6 . Somehow, and this is the main bit I don't get, complete an action if the form has been filled in correctly.

Many times people will display a success message

class Users extends CI_Controller{

    function index(){
        //index method
    }

    function banana(){
        $this->load->view('banana_view');
    }

    // assuming form_open('index.php/users/eat_banana'); in banana_view
    function eat_banana(){
        //make sure that this is a POST
        if($this->input->post()){
            // do things with the data
            // typically it gets saved to a database
            // via a model (the M in MVC)
            // http://ellislab.com/codeigniter/user-guide/general/models.html

            if($saved_to_db){
                // set message to send to the view
                $data['message'] = "Everything went OK";
            }else{
                $data['message'] = "but who was database? data didn't save :(";
            }
            // load the view and send the data
            $this->load->view('eat_banana', $data);
        }
     }

application/views/eat_banana.php:

 <!DOCTYPE html>
 <html>
 <head></head>
 <body>
 <div>
     <b>Form submitted.</b><br />
     The message is: <?php echo $message; ?>
 </div>
 </html>

other times, one might instead prefer to redirect

class Users extends CI_Controller{

    function index(){
        //index method
    }

    function banana(){
        $this->load->view('banana_view');
    }

    // assuming form_open('index.php/users/eat_banana'); in banana_view
    function eat_banana(){
        //make sure that this is a POST
        if($this->input->post()){
            // do things with the data             
            if($saved_to_db){
                // just send them to the homepage
                redirect('/');
            }else{
                // send them back to the form
                redirect('index.php/users/banana');
            }
        }
     }

So,

M is for model. Models are used to talk to the database.

V is for Vend view. Views render the text, forms, pictures, gifs, whatever to the screen. That's the idea anyway. There's nothing stopping you from echo'ing out an enormous unminimized javascript application from your controller. That would totally not be MVC tho.

C is for controller. Controllers call and send data to the views, receive data sent from views, take that data and send it to a model to be saved in the database (although CodeIgniter doesn't enforce this in any way either; you could if you wanted to save the data to a database directly from the controller, but this obviously defeats the MVC principal as well), retrieves data from the database and sends it to a view for display. Those are the basics anyway.

这篇关于CodeIgniter - 两个表单,一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆