Codeigniter validate form is not working - forms

I have the same implementation for my login for and is working, but on my contact form it is not, and I have no error message just re routed to the home page.
the weird thing is if in my controller i implement the index function like this:
public function index() {
$this->myprocess();
}
and my view using
<?php
$attributes = array('class' => 'form-contact', 'id' => 'myform2');
echo form_open('contact',$attributes);
?>
instead of calling my function myprocess all the validations work but no use for a form with out my header footers etc.
bellow that is how i want my code to work i hope yall can help me.
my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class contact extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('contact_m');
}
public function index()
{
$data = array('title' => 'Contact', 'main_content' => 'contact_v');
$this->load->view('template', $data);
}
public function myprocess(){
$this->form_validation->set_rules('dfname', 'Name', 'required|trim|xss_clean|max_length[40]');
$this->form_validation->set_rules('dfemail', 'Email', 'required|trim|xss_clean|valid_email|max_length[50]|callback__verifyemail');
$this->form_validation->set_rules('dfmsg', 'dfmsg', 'trim|xss_clean');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('contact_v');
}
else
{
$form_data = array(
'dfname' => set_value('dfname'),
'dfemail' => set_value('dfemail'),
'dfmsg' => set_value('dfmsg')
);
if ($this->contact_m->SaveForm($form_data) == TRUE)
{
redirect('contact/success');
}
else
{
echo 'An error occurred saving your information. Please try again later';
}
}
}
function success()
{
echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';
}
public function verifyemail(){
$name = $this->input->post('dfName');
$pass = $this->input->post('dfemail');
if($this->contact_m->email_exist($name,$pass)){
if ($this->session->userdata('site_lang') == 'portuguese')
{
$this->form_validation->set_message('_verifyuser','Usuario Inexistente!');
}else{
$this->form_validation->set_message('_verifyuser','User Not Found!');
}
$this->index();
return false;
}else{
return true;
}
}
}
?>
my view:
<div class="container">
<div class="row">
<div class=" col-md-4 col-md-offset-4">
<?php echo br(2)?>
<div class="account-wall drop-shadow">
<?php
$title = $this->my_library->my_title($this->session->userdata('site_lang'),FORM_CONTACT);
echo '<h1 class="text-center login-title">'. $title. '</h1>';
echo br(1)
?>
<?php
$attributes = array('class' => 'form-contact', 'id' => 'myform2');
echo form_open('contact/myprocess',$attributes);
?>
<p>
<label for="dfname">Name</span></label>
<?php echo form_error('dfname'); ?>
<input id="dfname" type="text" class="form-control" placeholder="Name" name="dfname" maxlength="40" value="<?php echo set_value('dfname'); ?>" autofocus />
<?php echo br(1)?>
</p>
<p>
<label for="dfemail">Email</span></label>
<?php echo form_error('dfemail'); ?>
<input id="dfemail" type="text" class="form-control" placeholder="Email" name="dfemail" maxlength="50" value="<?php echo set_value('dfemail'); ?>" />
<?php echo br(1)?>
</p>
<p>
<label for="dfmsg">Message</label>
<?php echo form_error('dfmsg'); ?>
<?php echo form_textarea( array( 'name' => 'dfmsg', 'rows' => '4', 'cols' => '43', 'value' => set_value('dfmsg') ) )?>
<?php echo br(1)?>
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php form_close();?>
</div>
</div>
</div>
</div>
<?php echo br(5)?>

your callback function for validation need an underscore for prefix name :
public function _verifyemail()
and you need to call the process function :
public function index()
{
$data = array('title' => 'Contact', 'main_content' => 'contact_v');
if($this->input->post())
$this->myprocess();
$this->load->view('template', $data);
}

So after all this days and examining all my code and re-writing all of it i found the problem.
for some reason this line wasnt working : echo form_close(); so my first form was aways open messing up asll my validation after writing on all of then it starting working.

Related

How to post multiple inputs in database

I'm working with Codeigniter, on a sales targets' form for salesmen.
They have to input values for each product, locality, year, etc.
Product and locality are already get with existing database: no need to set rules (see controller).
When I checked the post (with enable_profiler of Codeigniter), I get this:
The problem is these datas don't insert into the database table.
I read and tested a lot, but always blocked.
Here is my model:
public function add($params)
{
$this->db->insert($this->table, $params);
return $this->db->insert_id();
}
My controller:
$this->load->library('form_validation');
$this->form_validation->set_rules('year', 'Year', 'required|integer');
$this->form_validation->set_rules('prevision', 'Prevision', 'required');
$this->form_validation->set_rules('value', 'Value', 'required|integer');
if ($this->form_validation->run()) {
$params = array(
'year' => $this->input->post('year'),
'prevision' => $this->input->post('prevision'),
'locality_id' => $this->input->post('locality'),
'product' => $this->input->post('product'),
'value' => $this->input->post('value'),
);
$this->Objectif_model->add($params);
redirect('admin/objectif');
} else {
$this->layout('admin/objectif/add');
}
And my view with inputs:
<?php foreach ($products as $product) : ?>
<tr class="form-group">
<td class="bg-warning">
<?= $product->grp_product; ?>
</td>
<td class="bg-warning product">
<?= $product->code; ?>
</td>
<?php foreach ($localities as $locality ) : ?>
<td>
<input type="text" class="form-control valeur" placeholder="Value k€" name="value[]" data-validation="number" data-validation-ignore="./" data-validation-optional="true" />
<input type="text" name="year[]" />
<input type="text" name="prevision[]" />
<input type="text" name="product[]" value="<?= $product->code ?>" />
<input type="text" name="localite_id[]" value="<?= $locality->id ?>" />
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
Hope you will help me.
I find my answer.
In my controller, I had to pass each post in a variable and made a loop.
//action post in a var for each data
$id = $this->input->post('id');
$prev = $this->input->post('prevision');
$year= $this->input->post('year');
$locality_id = $this->input->post('locality_id');
$product = $this->input->post('product');
$value= $this->input->post('value');
if ($this->form_validation->run()) {
$count_id = count($id);
if (isset($id)) {
for ($i = 0; $i < $count_id; $i++) {
$obj[$i] = array(
'id' => $id[$i],
'prevision' => $prev,
'year' => $year,
'locality_id' => $locality_id[$i],
'product' => $product[$i],
'value' => $value[$i]*1000
);
} // endfor
if (isset($obj)) {
$this->Objectif_model->add_obj($obj);
} // endif
}// endif isset
}// endif form validation

Yii2 use form tags

When I submit my form i got some errors,
This is my form script which contains posted fields.
<?php $form = ActiveForm::begin([
'action'=>'userpermission/create',
]); ?>
<form method="post" action="<?php echo Yii::$app->getUrlManager()->createUrl('admin/userpermission/create')?>">
<ul class="list-unstyled">
<li>
<?= $form->field($model, 'idPermission')->checkboxList(ArrayHelper::map(Permission::find()->all(),"idPermission", "libelle", [
'onclick' => "$(this).val( $('input:checkbox:checked').val());",
'item' => function($index, $label, $name, $checked, $value) {
return "<label class='ckbox ckbox-primary col-md-4'><input type='checkbox' {$checked} name='{$name}' value='{$value}' tabindex='3'>{$label}</label>";
}
])) ?>
</li><br>
</ul>
<div class="form-group">
<?php Html::submitButton($model->isNewRecord ? 'Valider' : 'Create' ,['class' => $model->isNewRecord ? 'btn btn-primary','value'=>'Create', 'name'=>'submit']) ?>
</div>
<?php ActiveForm::end(); ?>
and my create function looks like but i got the error undefined variable model!
public function actionCreate()
{
$model = new Userpermission();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
print_r(Yii::$app->request->post());
exit;
return $this->redirect(['index', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
1st off, you dont need that <form> tag.
<?php $form = ActiveForm::begin([
'action'=>'userpermission/create',
]); ?>
creates and initializes the form for you with corresponding client-validations.
the possible issue is due to unclosed </form> which anyways is unnecessary.
suggesting to remove the <form> tag entirely. and try again and if any issue please let me know the error.
also bring the print_r(Yii::$app->request->post()); before if condition.
enable error reporting in your function
error_reporting(E_ALL);
please give the filename to code block. it would be easier to understand that way.

Input Form Using Codeigniter and Bootstrap 3

I'm using Codeigniter, styled with Bootstrap 3 to build a website.
I can't stylize the text-fields built by the PHP/Form Helper, as I'm not sure where to use the tags, every solution I've tried has resulted in either an extra text field, or just the addon appearing, or nothing at all.
Controller
public function __construct ()
{
parent::__construct();
}
public function index ()
{
// Fetch all users
$this->data['users'] = $this->user_m->get();
// Load view
$this->data['subview'] = 'admin/user/index';
$this->load->view('admin/_layout_main', $this->data);
}
public function edit ($id = NULL)
{
// Fetch a user or set a new one
if ($id) {
$this->data['user'] = $this->user_m->get($id);
count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
}
else {
$this->data['user'] = $this->user_m->get_new();
}
// Set up the form
$rules = $this->user_m->rules_admin;
$id || $rules['password']['rules'] .= '|required';
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->user_m->array_from_post(array('name', 'email', 'password'));
$data['password'] = $this->user_m->hash($data['password']);
$this->user_m->save($data, $id);
redirect('admin/user');
}
// Load the view
$this->data['subview'] = 'admin/user/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function delete ($id)
{
$this->user_m->delete($id);
redirect('admin/user');
}
public function login ()
{
// Redirect a user if he's already logged in
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
// Set form
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
// Process form
if ($this->form_validation->run() == TRUE) {
// We can login and redirect
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}
else {
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('admin/user/login', 'refresh');
}
}
// Load view
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
}
public function logout ()
{
$this->user_m->logout();
redirect('admin/user/login');
}
public function _unique_email ($str)
{
// Do NOT validate if email already exists
// UNLESS it's the email for the current user
$id = $this->uri->segment(4);
$this->db->where('email', $this->input->post('email'));
!$id || $this->db->where('id !=', $id);
$user = $this->user_m->get();
if (count($user)) {
$this->form_validation->set_message('_unique_email', '%s should be unique');
return FALSE;
}
return TRUE;
}
}
View
<div class="modal-body">
<?php echo validation_errors(); ?>
<?php echo form_open();?>
<div class="container">
<div class="modal-header">
<h3>Log in</h3>
<p>Please log in using your credentials</p>
</div>
<table class="table">
<tr>
<td>Email</td>
<td><?php echo form_input('email'); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php echo form_password('password'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Log in', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<div class="modal-footer">
© <?php echo date('Y'); ?> <?php echo $meta_title; ?>
</div>
<?php echo form_close();?>
</div>
</div>
</div>
Bootstrap
<form class="form-signin" role="form">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="form-control" placeholder="email" required autofocus value="<?php echo set_value('email') ?>">
<input type="password" class="form-control" placeholder="password" required value"<?php echo set_value('password') ?>">
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
You just pass everything as an array to form_input
<?php echo form_input(['name' => 'email', 'id' => 'email', 'class' => 'form-control', 'value' => set_value('email')]); ?>
Here's your entire form as presented,
<?php echo form_open('controller/method', ['class' => 'form-signin', 'role' => 'form']); ?>
<h2 class="form-signin-heading">Please sign in</h2>
<?php echo form_input(['name' => 'email', 'id' => 'email', 'class' => 'form-control', 'value' => set_value('email'), 'placeholder' => 'Email']); ?>
<?php echo form_password(['name' => 'password', 'id' => 'password', 'class' => 'form-control', 'placeholder' => 'Password']); ?>
<label class="checkbox">
<?php echo form_checkbox(['name' => 'remember_me', 'value' => 1]); ?>
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<?php echo form_close(); ?>

Handle two different forms in a single page

So I want to handle two forms on one single page, and I've got some problems to do it; I've got a module named 'contact', here is the indexSucces.php
<div id="registerForm">
<form action="<?php echo url_for('contact'); ?>" method="post" id="loginForm">
<?php foreach ($loginForm as $widget): ?>
<?php if(!$widget->isHidden()) { ?>
<?php echo $widget->renderRow(); ?>
<?php } else { ?>
<?php echo $widget->render() ?>
<?php } ?>
<?php endforeach; ?>
<br/><input type="submit" id="loginSubmit" class="btn primary" value="<?php echo __('Envoyer'); ?>" />
</form>
</div>
<div id="registerForm">
<form action="<?php echo url_for('contact'); ?>" method="post" id="registerForm">
<?php foreach ($registerForm as $widget): ?>
<?php if(!$widget->isHidden()) { ?>
<?php echo $widget->renderRow(); ?>
<?php } else { ?>
<?php echo $widget->render() ?>
<?php } ?>
<?php endforeach; ?>
<br/><input type="submit" id="registerSubmit" class="btn primary" value="<?php echo __('Envoyer'); ?>" />
</form>
</div>
Is it possible to handle that in a single action page ? I need to know the way on how to it, I'm stuck since yesterday. For exemple, when I want to submit the first form, it wants to submit the second form with.
Someone can provide me an exemple ? I can post my sh** action page if you want to see how I tried to handle that.
Thanks in advance !
EDIT:
I made this code according to your advice :
public function executeIndex(sfWebRequest $request)
{
$this->loginForm = new loginForm();
$this->registerForm = new registerForm();
$this->processForm($request, $this->loginForm, $this->registerForm);
}
public function processForm(sfWebRequest $request, sfForm $loginForm, sfForm $registerForm)
{
if($request->hasParameter('login'))
{
if($request->isMethod('post'))
{
$loginForm->bind($request->getParameter($loginForm->getName()));
if($loginForm->isValid())
{
$this->redirect('payement');
}
}
} elseif ($request->hasParameter('register'))
{
if($request->isMethod('post'))
{
$registerForm->bind($request->getParameter($registerForm->getName()));
if($registerForm->isValid())
{
$this->redirect('payement');
}
}
}
}
The registerForm is submitting correctly, I can see the errors I've made in the form etc, and if it's correct, it is correctly redirected. But when I submit the loginForm, here is the error :
Argument 1 passed to sfForm::bind() must be an array, string given : on this line
$loginForm->bind($request->getParameter($loginForm->getName()));
Why ?
Yes, you can.
Add a name attribute to your buttons (i.e. login and register), and modify your action to:
if ($request->hasParameter("login")) {
// handle login
}
elseif ($request->hasParameter("register")) {
// handle register
}

Zend Framework Custom Forms with viewScript

I am having some problems working out how to use custom forms in Zend Framework.
I have followed various guides but none seem to work. Nothing at all gets rendered.
Here is the bits of code that I am trying to use (All code below is in the default module). I have simplified the code to a single input for the test.
applications/forms/One/Nametest.php
class Application_Form_One_Nametest extends Zend_Form {
public function init() {
$this->setMethod('post');
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Box Name')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Submit Message');
$submit->setAttrib('id', 'submitbutton');
$submit->setAttrib('class', 'bluebutton');
$this->addElements(array($name, $submit));
}
}
application/views/scripts/one/formlayout.phtml
<form action="<?= $this->escape($this->form->getAction()) ?>" method="<?= $this->escape($this->form->getMethod()) ?>">
<p>
Please provide us the following information so we can know more about
you.
</p>
<? echo $this->element->name ?>
<? echo $this->element->submit ?>
</form>
application/controllers/IndexController.php
public function formtestAction() {
$form = new Application_Form_One_Nametest();
$form->setDecorators(array(array('ViewScript', array('viewScript' => 'one/formlayout.phtml'))));
$this->view->form = $form;
}
application/views/scripts/index/formtest.phtml
<h1>Formtest</h1>
<?
echo $this->form;
?>
The above code does not throw any errors or render any part of formlayout.phtml including the form tags or text between the p tags.
Can anybody tell me what I might be doing wrong?
I think the problem is your form element's decorator. You should set the decorator to ViewHelper and Error only. It works for me at least.
Here is the code I used and it should work
applications/forms/Form.php
class Application_Form_Form extends Zend_Form {
public function loadDefaultDecorators() {
$this->setDecorators(
array(
array(
'ViewScript',
array(
'viewScript' => 'index/formlayout.phtml',
)
)
)
);
}
public function init() {
$this->setAction('/action');
$this->setMethod('post');
$this->addElement('text', 'name', array(
'decorators' => array('ViewHelper', 'Errors')
));
}
}
application/views/scripts/index/formlayout.phtml
<form action="<?php echo $this->element->getAction(); ?>" method="<?php echo $this->element->getMethod(); ?>">
<div>
<label for="name">Box Name</label>
<?php echo $this->element->name; ?>
</div>
<input type="submit" value="Submit Message" id="submitbutton" class="bluebutton">
</form>
application/views/scripts/index/index.phtml
<!-- application/views/scripts/index/index.phtml -->
<?php echo $this -> form; ?>
application/controllers/IndexController.php
public function indexAction() {
$form = new Application_Form_Form();
$this -> view -> form = $form;
}
Here is a very simple example to get you going adapted from this article.
The form:-
class Application_Form_Test extends Zend_Form
{
public function init()
{
$this->setMethod('POST');
$this->setAction('/');
$text = new Zend_Form_Element_Text('testText');
$submit = new Zend_Form_Element_Submit('submit');
$this->setDecorators(
array(
array('ViewScript', array('viewScript' => '_form_test.phtml'))
)
);
$this->addElements(array($text, $submit));
$this->setElementDecorators(array('ViewHelper'));
}
}
The order in which setDecorators(), addElements() and setElementDecorators() are called is very important here.
The view script _form_test.phtml can be called anything you like, but it needs to be in /views/scripts so that it can be found by the renderer.
/views/scripts/_form_test.phtml would look something like this:-
<form id="contact" action="<?php echo $this->element->getAction(); ?>"
method="<?php echo $this->element->getMethod(); ?>">
<p>
Text<br />
<?php echo $this->element->testText; ?>
</p>
<p>
<?php echo $this->element->submit ?>
</p>
</form>
You instantiate the form, pass it to the view and render it as usual. The output from this example looks like this:-
<form id='contact' action='/' method='post'>
<p>
Text<br />
<input type="text" name="testText" id="testText" value=""></p>
<p>
<input type="submit" name="submit" id="submit" value="submit"></p>
</form>
That should be enough to get you started creating your own forms.
Usually, if you don't see anything on the screen it means that some sort of error happened.
Maybe you have errors turned off or something, maybe not. I'm just trying to give you ideas.
The only things I could spot where the following.
In the below code, you have to still specify the form when trying to print out the elements.
<form>
action="<?php $this->escape($this->element->getAction()) ?>"
method="<?php $this->escape($this->element->getMethod()) ?>" >
<p>
Please provide us the following information so we can know more about
you.
</p>
<?php echo $this->element->getElement( 'name' ); ?>
<?php echo $this->element->getElement( 'submit' ) ?>
</form>
As vascowhite's code shows, once you are inside the viewscript, the variable with the form is called element. The viewscript decorator uses a partial to do the rendering and thus it creates its own scope within the viewscript with different variable names.
So, although in your original view it was called $form, in the viewscript you'll have to call it element.
Also, maybe it was copy/paste haste, but you used <? ?> tags instead of <?= ?> or <?php ?> tags. Maybe that caused some error that is beyond parsing and that's why you got no output.