Kohana ORM and Validation, having problems

后端 未结 1 1715
一个人的身影
一个人的身影 2021-01-06 14:11

Trying to get Validation with ORM working for Kohana 3.2.

At the moment i have my Model:



        
相关标签:
1条回答
  • 2021-01-06 14:52

    This is how I do model validation, and I feel it's most straightforward and elegant.

    First, I set my rules in the rules() method:

    <?php defined('SYSPATH') or die('No direct access allowed.');
    
    class Model_Brand extends ORM {
    
        public function rules()
        {
            return array(
                'name' => array(
                    array('not_empty'),
                    array('min_length', array(':value', 3)),
                    array('max_length', array(':value', 20)),
                )
                'sku' => array(
                    array('not_empty'),
                    array('min_length', array(':value', 3)),
                    array('max_length', array(':value', 6)),
                )
            );
        );
    }
    

    And this is how I manage my edit action:

    public function action_edit()
    {
        $brand = ORM::factory('brand', $this->request->param('id'));
    
        if (!$brand->loaded())
        {
            throw new Kohana_Exception('Brand not found.');
        }
    
        $this->template->title = __('Edit Brand');
        $this->template->content = View::factory('brands/edit')
            ->set('brand', $brand)
            ->bind('errors', $errors);
    
        if ($this->request->method() === Request::POST)
        {
            try
            {
                $brand->values($this->request->post());
                $brand->save();
    
                // Success! You probably want to set a session message here.
    
                $this->request->redirect($this->request->uri());
            }
            catch(ORM_Validation_Exception $e)
            {
                // Fail!
    
                $errors = $e->errors('brand');
            }
        }
    }
    

    And in my view:

    <?php if ($errors) {?>
        <!-- display errors here -->
    <?php } ?>
    
    <?php echo Form::open()?>
        <fieldset>
    
            <div class="field">
                <?php echo 
                    Form::label('name', __('Name')),
                    Form::input('name',  $brand->name)
                ?>
            </div>
    
            <?php echo Form::submit('save', 'Save')); ?>
        </fieldset>
    <?php echo Form::close()?>
    

    As you can see in the view, I'm not doing any conditional checking to see what to display in the form field, as that is managed by the data in the model, which is managed by the controller.

    Hope this helps, ask away if you need further clarification.

    0 讨论(0)
提交回复
热议问题