CodeIgniter控制器传参至视图及按需显示表单问题排查
Hey there, let's walk through why your form switching logic isn't working and fix it up step by step. I looked over your code and noticed a few key mistakes that are causing the problem:
1. Incorrect Variable Check in Your View
Your current check <?php if(isset(['epacat'])):?> is invalid syntax—isset() expects a variable, not an array literal. When you pass $data['epa_cat'] from the controller to the view, CodeIgniter makes it available as the variable $epa_cat directly. You also want to ensure the variable isn't empty (in case the query returns no results), so the correct check is:
if(isset($epa_cat) && !empty($epa_cat))
2. Undefined $pc Variable
You're using $pc->pa_cat_name in the update form, but you never defined $pc in your view. The data you passed from the controller is stored in $epa_cat, so you need to reference that instead.
3. Missing echo on form_close()
Your form_close() calls don't have echo, which means the closing </form> tag won't be rendered in the HTML. This can break form submission behavior.
Corrected View Code
Here's the fixed version of your view with all the issues addressed:
<div class="row"> <?php // Check if we have valid category data to show the update form if(isset($epa_cat) && !empty($epa_cat)):?> <div class="col-md-12"> <?php echo form_open('admin/apacat');?> <label><h4>Update Parent Category</h4></label> <?php echo form_input([ 'name'=>'pa_cat_name', 'class'=>'form-control', 'placeholder'=>'Enter your parent category', 'value'=>set_value('pa_cat_name', $epa_cat->pa_cat_name) ]);?> <button type="reset" class="btn btn-warning">Reset</button> <button type="submit" class="btn btn-primary">Submit</button> <?php echo form_close();?> <!-- Added echo to render closing tag --> </div> <?php else:?> <div class="col-md-12"> <?php echo form_open('admin/apacat');?> <label><h4>Add Parent Category</h4></label> <?php echo form_input([ 'name'=>'pa_cat_name', 'class'=>'form-control', 'placeholder'=>'Enter your parent category', 'value'=>set_value('pa_cat_name') ]);?> <button type="reset" class="btn btn-warning">Reset</button> <button type="submit" class="btn btn-primary">Submit</button> <?php echo form_close();?> <!-- Added echo to render closing tag --> </div> <?php endif;?> </div>
Quick Notes on Your Controller
Your controller code looks fine, but just double-check that your epacatQ($pa_cat_id) method returns a single object (like a row from your database) when a valid $pa_cat_id is passed. If it returns an empty array or null, the !empty($epa_cat) check will correctly fall back to the add form.
内容的提问来源于stack exchange,提问作者Sachin Singh

