problem (my_form_validation) not working properly for upload input - codeigniter

hoping someone can help me solve this problem, thanks a lot for providing the solution
i recently had a problem with my library called my_form_validation on codeigniter version 3. i don't know why it can enter validation true even though it was wrong in function photo check
I have done several options but none of the results I want. my example already used the callback it's the same
example code controller
public function validation_photo()
{
// load custom library Validation
$this->my_form_validation->config_photo();
$this->my_form_validation->photo_checker($_FILES['photo']);
// Conditional validation form
if ($this->form_validation->run() == FALSE) {
// does not pass validation
$data['Title'] = 'Profile';
$data['Content'] = 'management/V_Profile';
$this->load->view('dinamis/Layout', $data);
} else {
// passed validation
var_dump('passed');
}
}
the code above is my loading from my_form_validation library which works for configuring and validating the upload format
example code my_form_validation (config_photo)
function config_photo()
{
$ci = get_instance();
$config = array(
array(
'field' => 'photo',
'label' => 'photo',
'rules' => 'photo_checker',
),
);
$ci->form_validation->set_rules($config);
}
the code above is to set the rules to be used, I use photo_checker
example code my_form_validation (photo_checker)
function photo_checker($photo)
{
$ci = get_instance();
$allowed_mime_type_arr = array('image/jpeg', 'image/png', 'image/x-png', 'image/jpg');
$mime = $photo['type'];
if (in_array($mime, $allowed_mime_type_arr)) {
return TRUE;
} else {
$ci->form_validation->set_message('photo_checker', 'Please select a supported format (jpeg,png,jpg).');
return FALSE;
}
}
The above code is for validating if it doesn't match the desired format then it returns false with the message set
very very thank you very much for helping me.
I hope this issue gets resolved well in this forum, I'm sure there are really great people here

Related

Drupal 7 - Trying to add form to list view

sorry if this has been asked before, I looked around but haven't found this specific question on StackOverFlow.com.
I have a view called 'view-post-wall' which I'm trying to add the form that submits posts to this view called 'post' via ajax submit, though I haven't begun adding ajax yet.
My module's name is 'friendicate'
I don't understand what I'm missing here, I'm following a tutorial and have been unable to get past this issue for 2 days now.
I don't get any errors either.
Here is the module code in full
function _form_post_ajax_add() {
$form = array();
$form['title'] = array(
'#type' => 'textfield',
'#title' => 'Title of post',
);
$form['body'] = array(
'#type' => 'textarea',
'#title' => 'description',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit post',
);
return $form;
}
function post_ajax_preprocess_page(&$variables) {
//krumo($variables);
$arg = arg();
if($arg[0] == 'view-post-wall') {
$variables['page']['content']['system_main']['main']['#markup'] = drupal_render(drupal_get_form('_form_post_ajax_add'));
}
}
There are multiple ways to accomplish this, and I'll outline those methods below. Also, if nothing works from my suggestions below, it's possible that you have an invalid form function name. Im not sure if that throws off Drupal or not. The correct format for the function name should end in _form and contain the arguments $form and $form_state, like so:
_form_post_ajax_add_form($form, &$form_state) { ... }
Also, if you want to use a hook, Steff mentioned in a comment to your question that you'll need to use your module name in the function name.
friendicate_preprocess_page(&$variables) { ... }
Ok, now for a few ideas how to get the form on the page.
Block
You can create a custom block within your module, and then assign it to a region in admin/structure/blocks
<?php
/**
* Implements hook_block_info().
*/
function friendicate_block_info() {
$blocks = array();
$blocks['post_ajax'] = array(
'info' => t('Translation Set Links'),
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function friendicate_block_view($delta = '') {
$block = array();
if ($delta == 'post_ajax') {
$form = drupal_get_form('_form_post_ajax_add_form');
$block['content'] = $form;
}
return $block;
}
Clear the cache and your block should appear in admin/structure/blocks
Views attachment before/after
You can add markup before and after a view using the Views hook hook_views_pre_render()
<?php
/**
* Implements hook_view_pre_render().
*/
function frendicate_views_pre_render(&$view) {
if($view->name == 'view_post_wall') { // the machine name of your view
$form = drupal_get_form('_form_post_ajax_add_form');
$view->attachment_before = render($form);
}
}
Or maybe use view post render
function friendicate_views_post_render(&$view, &$output, &$cache) {
//use the machine name of your view
if ($view->name == 'view_post_wall') {
$output .= drupal_render(drupal_get_form('_form_post_ajax_add'));
}
}

Image validation not working If using ajaxForm

I tried googling and saw other questions posted at this forum but could not find any solution for my issue. I am using Jquery ajaxForm method to submit form. My form contains one file field too in the form that can be used to upload a picture. I have defined the validation in my model. But the issue is even i am uploading a correct jpg file, still i am getting error message that
Argument 1 passed to Illuminate\\Validation\\Factory::make() must be of the type array, object given.
Javascript Code
$('#create_form').ajaxForm({
dataType:'JSON',
success: function(response){
alert(response);
}
}).submit();
Controllder Code
if ($file = Input::file('picture')) {
$validator = Validator::make($file, User::$file_rules);
if ($validator->fails()) {
$messages = $validator->messages();
foreach ($messages->all(':message') as $message) {
echo $message; exit;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
// do rest
}
}
Model Code
public static $file_rules = array(
'picture' => 'required|max:2048|mimes:jpeg,jpg,bmp,png,gif'
);
POST Request
I know that my validation defined in the model expects an array. But by passing $file in the validator, an object is passed. Then i changed the code like:
$validator = Validator::make(array('picture' => $file->getClientOriginalName()), User::$file_rules);
Now i am getting error:
The picture must be a file of type: jpg, JPEG, png,gif.
The problem is you pass file object directly to validate. Validator::make() method takes all four parameters as array. Moreover, you need to pass the whole file object as value so that Validator can validate mime type, size, etc. That's why your code should be like that.
$input = array('picture' => Input::file('picture'));
$validator = Validator::make($input, User::$file_rules);
if ($validator->fails()) {
$messages = $validator->messages();
foreach ($messages->all(':message') as $message) {
echo $message; exit;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
// do rest
}
Hope it will be useful for you.
Try rule like this.
$rules = array(
'picture' => 'image|mimes:jpeg,jpg,bmp,png,gif'
);
or try removing 'mimes'

One-shot laravel validator

I have a form where someone searches for something. Based on this form, I validate if the input is correct:
$validator = Validator::make(Input::all() , array(
'address' =>'required',
));
if($validator->fails()) {
return Redirect::to('/')->withErrors($validator);
}
After this, I want to validate something else (that a result object isn't empty), which is completely unrelated to the search. In other words, it's NOT input from a form.
1) Do I create another validator to validate this? Or
2) Is there a better way to simply check this value and spawn an object that can be returned with "withErrors"?
UPDATE
This isn't working for me:
$validator = Validator::make(
array(
'searches' => sizeof($search)
) ,
array(
'searches' => 'required|min:1'
)
);
if($validator->fails()) {
return Redirect::to('/')->withErrors($validator);
}
It's not working because for some reason it's picking up that the "searches" item should only be validated "sometimes"
you have two ways. one is custom validator
or there is a simpler way,
suppose,
private function foo()
{
$data = ''; //retrieved the data error here with whatever call you want to make
return !empty($data) ? true : false;
}
in the controller,
public function bar()
{
if(!$this->foo())
{
$messages = new \Illuminate\Support\MessageBag;
// you should use interface here. i directly made the object call for the sake of simplicity.
$messages->add('custom', 'custom error');
return Redirect::back()->withErrors($messages)->withInput();
}
}
in the view:
#if($errors->has('custom'))
<p>custom error output.</p>
#endif
it is just the outline to give you the idea.

codeigniter: using uri segment in model

I am using uri segment to delete info in my database:
anchor('site/delete_note/'.$row->id, 'Delete')
Model:
function delete_note()
{
$this->db->where('id', $this->uri->segment(3));
$this->db->delete('note');
}
It works fine, but I want to do the same for updating my info and can't get it work
So this is link in view:
anchor('site/edit_note/'.$row->id, 'Edit')
My controller:
function edit_note()
{
$note_id = $this->uri->segment(3);
$data['main_content'] = 'edit_note';
$this->load->view('includes/template', $data);
$this->load->library('form_validation');
$this->form_validation->set_rules('content', 'Message', 'trim|required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('Note_model');
$this->Note_model->edit_note($note_id);
redirect('site/members_area');
}
}
My model:
function edit_note($note_id)
{
$content = $this->input->post('content');
$data = array('content' => $content);
$this->db->where('id', $note_id);
$this->db->update('note', $data);
}
My view of edit_note:
<?php
echo form_open('site/edit_note');
echo form_textarea('content', set_value('content', 'Your message'));
echo form_submit('submit', 'Change');
echo anchor('site/members_area', 'Cancel');
echo validation_errors('<p class="error">'); ?>
Edit doesn't work as delete, when i am trying to get segment directly in edit model, as I used in delete model.
If I set $note_id to a number in my controller, instead of this '$this->uri->segment(3)', it updates my database. But if I use getting segment it doesn't work. I thought uri segments are available in controller as in model, but there is something I don't know.
Better yet, instead of manually reading the IDs via the segments, you could change your functions to be:
function delete_note($note_id)
and
function edit_note($note_id)
And remove the $note_id = $this->uri->segment(3); lines.
And as silly as it'll sound, the generated URL is definitely correct, right?
And last question, have you done anything with routes?
Edit
I've also noticed that in edit, you use this in your form:
echo form_open('site/edit_note');
So when the form submits, the URL it submits to is site/edit_note instead of site/edit_note/{SOME_ID}. So once you make your changes, and the form submits, there won't be a 3rd URL segment!
Well there are some logical errors in your code.
function edit_note()
{
$note_id = $this->uri->segment(3);
$data['main_content'] = 'edit_note';
$this->load->view('includes/template', $data);
//// What is the use of loadig a view when you are editing
$this->load->library('form_validation');
$this->form_validation->set_rules('content', 'Message', 'trim|required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('Note_model');
$this->Note_model->edit_note($note_id);
redirect('site/members_area');
}
}
Instead do it like this
function edit_note()
{
if($this->input->post()){
$this->load->library('form_validation');
$this->form_validation->set_rules('content', 'Message', 'trim|required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('Note_model');
$this->Note_model->edit_note($note_id);
redirect('site/members_area');
}
}else{
$note_id = $this->uri->segment(3);
$data['main_content'] = 'edit_note';
$this->load->view('includes/template', $data);
}
}
MOST IMPORTANT
And the other thing you should note that you are using anchor to access edit note but not actually submitting a form so it is not getting any post data to update.
In my view it's a 'bad' approach to use uri segments in your models... you should pass an id as a parameter from your controller functions ..
function delete_note()
{
$this->db->where('id', $this->uri->segment(3));
$this->db->delete('note');
}
What if you want to re-use this delete method? e.g. deleting notes from an admin panel, via a cron job etc then the above relies upon the uri segment and you will need to create additional delete methods to do the job. Also, if you were to continue with the same you don't even need a model then .. just call these lines in your controllers if you know what I mean ...
$this->db->where('id', $this->uri->segment(3));
$this->db->delete('note');
so best is to change it to similar to your edit_note() model function.

cannot set user data in session codeigniter

please look at this.
The code below is from my model class (using datamapper orm)
function login()
{
$u = new User();
$u->where('username', $this->username)->get();
$this->salt = $u->salt;
$this->validate()->get();
if (empty($this->id))
{
// Login failed, so set a custom error message
$this->error_message('login', 'Username or password invalid');
return FALSE;
}
else
{
// Login succeeded
$data = array
(
'username' => $u->username,
'usergroup' => $u->usergroup->get(),
'is_logged_in' => true
);
$this->session->set_userdata($data);
return TRUE;
}
}
when i do this i get
**Fatal error: Call to a member function set_userdata() on a non-object**
but when i do this instead
$data = array
(
'username' => $u->username,
'usergroup' => $u->usergroup->get(),
'is_logged_in' => true
);
$obj=& get_instance();
$obj->session->set_userdata($data);
It works.
Please what is the right way to get this working ?
Thanks in advance.
your model did not extends CI_Model
after that you have to add constructor to your model
add this code to yours
function __construct()
{
parent::__construct();
$this->load->library('session');
}
Well, you didn't provide enough information.
The first code looks fine, provided that:
You actually load the session class before calling it (you also need to create an encryption key in your configs).
$this->load->library('session');
$this->session->set_userdata($data);
The above code, or your code, is inside a controller, a model or a view.
$this relates to the CI's superclass, in particular to an instance of the Session class, so if you're calling that inside a helper (collection of functions), or inside a library (where you need to create a CI instance first), it won't work.

Resources