开发者

Codeigniter - anonymous validation rule, independent of any field

I'd like to create a validation rule independent of any form field. Is it possible in Codeigniter? As far as I could see in the documentation, the set_rules method wants a form field name as first parameter.

Even so, I tried

$this->form_validation->set_rules('products_count', 'products_count', 'callback_products_count_check');

and this is the callback check

function products_count_check()
    {
    $user = $this->user_model->get(array(
        'id' => $this->session->userdata('user_id')
    ));

    if ( ! empty($user))
    {
      $kit = $this->kit_model->get(array('id' => $user->kit_id));
      if ( ! empty($kit)) {
        $products_count = $this->product_model->get(ar开发者_运维问答ray('user_id' => $user->id, 'count' => TRUE));

        if ($products_count >= $kit->max_products) {
          $this->form_validation->set_message('products_count_check', lang('products.max_products_reached'));
          return FALSE;
        }
      }
        }

    return TRUE;
    }

The function returns false, but the error message isn't shown.

Any ideas?

Thank you.


I don't think you're wanting to use form validation at all actually...

This sounds like a job for FLASHDATA!

check out the session class, I would use flash data in this situation for a few reasons

  • You're not validating a form field, which is what the form_validation class was intended for.
  • Flashdata messages are intended for this purpose

so to do this, in your controller...

$this->session->set_flashdata('error','Put your error message here');

then in the view, create a generic error handler

<?php if ($this->session->flashdata('error')): ?>
    <p class="error"><?php echo $this->session->flashdata('error') ?></p>
<?php endif; ?>


This looks like something you could check before a form is processed, unless I'm missing something. In that case, I would handle this logic in your view. Just get all of the product and kit records you need in the controller and pass them to the view and use a conditional to display the appropriate notification messages to the user if there is an error. That's easier than trying to use the validation class since it's not really intended to be used this way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜