How to set validation rules in file upload in code igniter - codeigniter

I want to give validation for a file upload field in code giniter. I tried the below code, but this is not working. Any other way ?
$this->form_validation->set_rules('photo', 'Passport Photo', 'required');

except of client side verification with javascript, you can try the following in your controller:
if (empty($_FILES['photo']['name']))
{
$this->form_validation->set_rules('photo', 'Passport photo', 'required');
}

Related

Validation for Filepicker is not working in Moodle

Validation in Moodle filepicker is not working. My form is add_form.php
require_once("{$CFG->libdir}/formslib.php");
class add_form extends moodleform {
function definition() {
global $DB;
$mform =&$this->_form;
// add question title.
$mform->addElement('header','displayinfo', 'Add/Edit Question');
$mform->addElement('editor', 'question', 'Question');
$mform->addRule('question', null, 'required', null, 'client');
$mform->setType('question', PARAM_RAW);
$maxbytes = 0;
$mform->addElement('filepicker', 'answerfile', get_string('file'), null,
array('maxbytes' => $maxbytes, 'accepted_types' => array('document','.txt', '.pdf')));
$mform->addRule('answerfile', null, 'required', null, 'client');
$mform->setType('answerfile', PARAM_RAW);
$mform->addElement('hidden', 'blockid');
$mform->setType('blockid', PARAM_RAW);
$mform->addElement('hidden', 'courseid');
$mform->setType('courseid', PARAM_RAW);
$this->add_action_buttons(false, 'SAVE');
}
}
Here the required validation for first field(question) is working. But the validation (required) for answerfile is not working. I am using two fields one editor and one filepicker fields.
When I submit the button with empty value(no files choosen) in filepicker the form get submitted.
Why the validation for file picker is not working here.
Please help me...
Moodle ver: 2.9.1
Might be the client side validation isn't working. Try server side validation. If that works, then it might be something to do with javascript on the client side.
$mform->addRule('answerfile', null, 'required');
File validation rule works only if we pass first parameter in moodleform custructor.
Use $mform = new add_form($pageurl); insted of $mform = new add_form(); where you have instantiate add_form object.
$pageurl is url of page where form data submitted.
I checked your code and it works for both client and server side validation if parameter is used.

How to repopulate form after form validation and also keep the URI?

I have a problem repopulating my form after validation fails. Problem is my url contains an additional uri which I access by clicking a link. This is what it looks like:
http://www.example.com/admin/trivia/add/5
At first trouble was that the segment 4 of the uri completely disappeared, so even though the validation errors showed and the form was repopulated, I lost my added uri.
Then I found in another question that the solution was to set form open like this:
echo form_open(current_url());
Problem is now it isn't showing any validation errors and the form is not repopulated. Is there a way to achieve this?
This is what my controller looks like:
function add()
{
$data = array('id' => $this->uri->segment(4));
if($_POST)
{
$this->_processForm();
}
$this->load->view('admin/trivia_form', $data);
}
And inside _processForm() I got all the validation rules, error message and redirecting in case success.
[edit] Here is my _processForm() :
function _processForm()
{
$this->load->library('form_validation');
//validation rules go here
//validation error messages
$this->form_validation->set_rules($rules);
$this->form_validation->set_error_delimiters('<div style="color:red">', '</div>');
if ($this->form_validation->run())
{
//get input from form and assign it to array
//save data in DB with model
if($this->madmin->save_trivia($fields))
{
//if save is correct, then redirect
}
else
{
//if not show errors, no redirecting.
}
}//end if validation
}
To keep the same url, you can do all things in a same controller function.
In your controller
function add($id)
{
if($this->input->server('REQUEST_METHOD') === 'POST')// form submitted
{
// do form action code
// redirect if success
}
// do your actual stuff to load. you may get validation error in view file as usual if validation failed
}
to repopulate the form fields you are going to need to reset the field values when submitting it as exampled here and to meke it open the same page you can use redirect() function as bellow:
redirect('trivia/add/5','refresh');
i don't know what you are trying to do, but try this to repopulate the form with the values user entered
<?php
echo form_input('myfield',set_value('myfield'),'placeholder="xyz"');
?>

Codeigniter + Redactor (wysiwyg js editor). Image uploading

I trying to integrate wysiwyg editor Redactor in Codeigniter website.
RedactorOptions:
{
lang: lang(),
toolbarFixed: true,
buttons: ['html', '|', 'bold', 'italic', 'deleted', '|', 'image', 'video', '|', 'unorderedlist', 'orderedlist', '|', 'alignment', '|', 'horizontalrule', '|', 'table', '|', 'mtLink'],
imageUpload: '/upload_photo'
}
while I start to send photo through Upload Image Dialog, I see in Developer console:
Uncaught TypeError: Cannot read property '0' of null redactor.js:1
Redactor.(anonymous function).$.(anonymous function).(anonymous function).uploadLoaded redactor.js:1
p.isFunction.f jquery.js:2
p.event.dispatch jquery.js:2
g.handle.h
Script "upload_photo" is running, but $_FILES is empty.
What wrong and how I can to fix it?
Thank in advance.
I have been fumbling around all night trying to fix this same issue, and it turns out to be a simple over site (so give your self a slap like I gave my self one!)
You have CI Cross-site request forgery (CSRF) protection set to TRUE in your config. Redactor is getting that nasty error page you see when you submit a form with out refreshing an old page (I really want to find a fix for that)!
The CSRF token has to be passed in any form that is submitted by POST. This gets done automatically when using CI's form_open(), but Redactor is using it's own form to do the post. So you need to include the CSRF info like this.
uploadFields: {
<?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>'
}
I'm pretty sure that's your problem. It was mine (thumps self in head - again).
CI's file upload class will look for POST data from input field named 'userfile' by default. The file input field of redactor is named 'file'. So you need to stipulate this name in your upload script by changing $this->upload->do_upload() to $this->upload->do_upload('file').
If this isn't the problem you will need to include your upload code here so I can see what's going on.

error with upload images in Attachments using Croogo and cakephp

Hope someone can help me!
I'm trying to upload an image in Attachments and insert image in a page using croogo.
And when I upload i keep getting the same error message:
Security Error
The requested address was not found on this server.
Request blackholed due to "auth" violation.
The images are saved in the uploads folder but i cant get them to display on the page.
Just add some line of code in your controller
public function afterFilter() {
if (($this->request->isPost() || $this->request->isPut()) && empty($_POST) && empty($_FILES)) {
$this->Security->csrfCheck = false;
}
}
OR
May be you forgot to define multipart in your form.
echo $this->Form->create('Something', array( 'type' => 'file'));
Hope this help you.

Clear validation error message when the value is updated or selected

I have form in yii that validates the form field. When I submit the form it shows the errors.
But when the value of the field with the validation error is updated, the error still present.
I want the message to clear. How should i clear the validation error?
Below the form widget code
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation'=>true
)); ?>
In my form I echo the validation error like the code below:
<?php echo $form->error($model, 'firstname'); ?>
I tried the solution from this problem
Trigger Yii field validation onchange of another field
$('#user-form').change(function(){
var settings = $(this).data('settings');
$.each(settings.attributes, function () {
this.status = 2; // force ajax validation
});
$(this).data('settings', settings);
// trigger ajax validation
$.fn.yiiactiveform.validate($(this), function (data) {
$.each(settings.attributes, function () {
$.fn.yiiactiveform.updateInput(this, data, $(this));
});
});
});
But the error message is still not cleared. I have confirmed that the ajax request is sent and there are response as its showed on the firebug console.
[EDIT]
It seems those validation errors for "select" fields are the ones that are not updated/cleared only.
[EDIT]
All the validation errors that are printed/echo after the form is submmitted will not disappear even if the value is supplied or change to satisfy the validation rules.
Place this just above the // trigger ajax validation comment:
$('.errorSummary, .errorMessage').hide();
This should reset the errors before they get re-validated.
In my case I added the code below on the page to remove the red highlight on input field on the form.
$('#user-form select, #user-form input').change(function(){
field = $(this).attr('id');
if($('#'+field+'_em').text() == ''){
$(this).removeClass('error');
}
});
I also add the updateInput function on framework/web/js/source/jquery.yiiactiveform.js so it will remove the validation error for certain field.
if(hasError == false){
$error.toggle(hasError);
$el2 = form.find('#' + attribute.id);
$el2.removeClass(attribute.errorCssClass);
}
I am not sure if this the proper solution but it works for me.
With your form widget code, i don't think ajax validation won't work.
To enable Ajax validation on form you should configure your widget as below,
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
With this configuration, your form will be validated when form field lost the focus(blur).
Try it, It will give the solution for your problem.

Resources