如何将PHP变量从视图(HTML)发送到控制器

3
这是我的HTML代码。我想将"$category_edit->c_name"的值传递给我的Update()控制器。我从另一个控制器获取"$category_edit"变量。
我正在使用CodeIgniter框架。
<form method="post" action="<?php echo base_url('admin/category/update');?>">
 <label>Parent Category: </label></br>
 <select name="parent_id">
 <?php
    echo '<option value="' .$category_edit->id .'">';
    echo $category_edit->p_name;
    echo '</option>';
 ?>
 </select>
 <label>Category</label>
 <input type="text" name="<?php echo $category_edit->c_name; ?>" id="category_name" value="<?php echo $category_edit->c_name; ?>">
 <button>Update</button>
</form>

这是我的update()控制器。我遇到了错误:
  1. Undefined variable: category_edit
  2. Trying to get property of non-object

    public function update(){
       $this->load->model('category_model');
       echo $category_edit->c_name;
    }
    

$category_edit 这不是全局变量。 - Ronak Patel
检查我的答案,兄弟。 - Ronak Patel
添加你的控制器代码。错误是Undefined variable: category_edit。这意味着category_edit数组是空的。 - Abdulla Nilam
3个回答

3
请查看以下参考代码:
public function update_view()
{
    $this->load->model('category_model');

    $data['category_edit'] = $this->category_model->get_category_values(); // return array
    $data['extra_variable'] = 'lorem ipsum';

    $this->load->view('category/update_view', $data);
}

在您的 category/update_view.php 文件中:
<form method="post" action="<?php echo base_url('admin/category/update');?>">
 <label>Parent Category: </label></br>
 <select name="parent_id">
 <?php
    echo '<option value="' .$category_edit['id'] .'">';
    echo $category_edit['p_name'];
    echo '</option>';
 ?>
 </select>
 <label>Category</label>
 <input type="text" name="<?php echo $category_edit['c_name']; ?>" id="category_name" value="<?php echo $category_edit['c_name']; ?>">
 <button>Update</button>
</form>

编辑:

请参考:http://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view


错误是“未定义变量:category_edit”。这意味着category_edit数组为空。你的答案是错误的。它不会将任何数据打印到视图中。 - Abdulla Nilam
兄弟,现在轮到你了,你的工作不能返回空数组,因为你正在进行数据库工作。或者对其进行验证。我可以向你展示路径,但不是完整的程序。我绝对正确,这是从我的项目中复制的相同内容。 - Ronak Patel
<?php print_r($category_edit); exit; ?> 在你的视图中执行,查看打印出来的内容。 - Ronak Patel

2

对HTML进行一些更改(请参见下面的代码)

<input type="text" name="category_name" id="category_name" value="<?php echo $category_edit->c_name; ?>">

public function update()
{
$this->load->model('category_model');
echo $this->input->post('category_name');
}

1
你需要添加静态字段的名称,而不是任何变量。因此,请尝试像这样添加。
<input type="text" name="category_name" id="category_name" value="<?php echo $category_edit->c_name; ?>">

在控制器上,您可以像这样获取它的值:

并且在控制器上,您可以获取它的值

$this->input->post('category_name');

错误是“未定义变量:category_edit”。这意味着category_edit数组为空。你的答案是错误的。它不会将任何数据打印到视图中。 - Abdulla Nilam
这个是控制器用的,视图你需要获取它。 - Jay
用户已经从视图请求到控制器。 - Jay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接