I am facing a wired problem for more than 2 hours. I couldn't figured it out. I am trying to pass the variable "errors" from model to view but when I try to load the page it shows error saying "undefined variable: errors". I am trying to build a "register" page for registering new users.
Here is my controller for register
function register(){
if($_POST){
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|min_length[3]|is_unique[users.username]'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[5]'
),
array(
'field' => 'password2',
'label' => 'Password Confirm',
'rules' => 'trim|required|min_length[5]|matches[password]'
),
array(
'field' => 'user_type',
'label' => 'User Type',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|is_unique[users.email]|valid_email'
)
);
$this->load->library('form_validation');
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE){
$data['errors'] = validation_errors();
}else{
$data_array = array(
'username' => $_POST['username'],
'password' => sha1($_POST['password']),
'email' => $_POST['email'],
'user_type' => $_POST['user_type']
);
$this->load->model('user');
$userid = $this->user->create_user($data_array);
$this->session->set_userdata('userID', $userid);
$this->session->set_userdata('user_type',$_POST['user_type']);
redirect(base_url().'index.php/posts');
}
}
$this->load->helper('form');
$this->load->view('header');
$this->load->view('register_user');
$this->load->view('footer');
}
In above when there is a error in validation I set the error in $data['errors'] array.
The view is given below
<h2>Register User</h2>
<?php if($errors): ?>
<div style="background:red;color:white;">
<?php echo $errors; ?>
</div>
<?php endif; ?>
But when I open the register page on browser, it shows the error saying "Undefined variable: errors". Can anyone tell me where I have done wrong?
You are not passing any data to your views. You can use the 2nd parameter to pass data to your views so rather than doing
$this->load->view('header');
$this->load->view('register_user');
$this->load->view('footer');
You want to do
$aData['errors']
$this->load->view('header', $aData);
$this->load->view('register_user', $aData);
$this->load->view('footer', $aData);
Then when you are in your view you can do
<h2>Register User</h2>
<?php if($errors): ?>
<div style="background:red;color:white;">
<?php echo $errors; ?>
</div>
<?php endif; ?>
Related
I have this error message when I submit form.
Notice: Undefined index: title in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 38
Notice: Undefined index: description in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 39
Notice: Undefined index: featured in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 58
Message:
An exception occurred while executing 'INSERT INTO auto (title,
description, featured, date_created) VALUES (?, ?, ?, ?)' with params
[null, null, null, "2017-06-15 05:04:44"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title'
cannot be null
this is my form and fieldset
use Zend\Form\Fieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use BusinessGhana\Entity\Autos;
class AddFieldset extends Fieldset
{
protected $objectManager;
public function init()
{
$this->add([
'type' => 'text',
'name' => 'title',
'attributes' => [
'id' => 'autoTitle'
],
'options' => [
'label' => 'Title',
'display_empty_item' => true,
'empty_item_label' => 'Maximum of 60 characters',
],
]);
$this->add([
'type' => 'textarea',
'name' => 'description',
'attributes' => [
'id' => 'autoDescription'
],
'options' => [
'label' => 'Description',
'display_empty_item' => true,
'empty_item_label' => 'description',
],
]);
$this->add([
'type' => 'radio',
'name' => 'featured',
'attributes' => [
'id' => 'autoFeatured'
],
'options' => array(
'label' => 'Featured',
'value_options' => array(
array('value' => '0',
'label' => 'No',
'selected' => true,
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-default',
),
),
array(
'value' => '1',
'label' => 'Yes',
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-danger',
),
),
),
'column-size' => 'sm-12',
'label_attributes' => array(
'class' => 'col-sm-2',
),
),
]);
}
}
use Zend\Form\Form;
//use Zend\InputFilter\InputFilter;
class AddForm extends Form
{
public function init()
{
$this->add([
'name' => 'dependentForm',
'type' => AddFieldset::class,
]);
$this->add([
'type' => 'submit',
'name' => 'submit',
'attributes' => [
'value' => 'Submit',
],
]);
}
}
This is my controller action
public function addAction()
{
// Create the form.
$form = new PostForm();
if ($this->getRequest()->isPost()) {
// Get POST data.
$data = $this->params()->fromPost();
// Fill form with data.
$form->setData($data);
if ($form->isValid()) {
// Get validated form data.
$data = $form->getData();
$this->AutosManager->addNewAutos($data);
return $this->redirect()->toRoute('retrieve');
}
}
return new ViewModel([
'form' => $form
]);
}
I know hydration can solve this problem but I don't know how to use it yet.
thanks for any help.
this is my autosManager
class AutosManager
{
/**
* Entity manager.
* #var Doctrine\ORM\EntityManager;
*/
private $entityManager;
/**
* Constructor.
*/
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function addNewAutos($data)
{
$autos = new Autos();
$autos->setTitle($data['title']);
$autos->setDescription($data['description']);
$autos->setFeatured($data['featured']);
$currentDate = date('Y-m-d H:i:s');
$autos->setDateCreated($currentDate);
$this->entityManager->persist($autos);
$this->entityManager->flush();
}
}
i can retrieve data from database.
This is where i render my forms:
$form = $this->form;
$fieldset = $form->get('dependentForm');
$title = $fieldset->get('title');
$title->setAttribute('class', 'form-control');
$title->setAttribute('placeholder', 'Maximum of 60 characters');
$title->setAttribute('id', 'autoTitle');
$description = $fieldset->get('description');
$description->setAttribute('class', 'form-control');
$description->setAttribute('placeholder', 'Description here...');
$description->setAttribute('id', 'autoDescription');
$featured = $fieldset->get('featured');
$featured->setAttribute('id', 'autoRadio');
$form->get('submit')->setAttributes(['class'=>'btn btn-primary']);
$form->prepare();
echo $this->form()->openTag($form);
?>
<fieldset>
<div class="form-group">
<?= $this->formLabel($title) ?>
<?= $this->formElement($title) ?>
<?= $this->formElementErrors()->render($title,['class'=>'help-block'])?>
</div>
<div class="form-group">
<?= $this->formLabel($description) ?>
<?= $this->formElement($description) ?>
<?=$this->formElementErrors()->render($description,
['class'=>'help-block'])?>
</div>
<div class="form-group">
<?= $this->formLabel($featured) ?>
<?= $this->formElement($featured) ?>
<?= $this->formElementErrors()->render($featured,
['class' =>'help-block']) ?>
</div>
</div></div><div class="row">
<div class="col-md-4">
</fieldset>
<?= $this->formElement($form->get('submit')); ?>
In your function addNewAutos($data) : your $data variable don't have title, description and featured fields. So php consider these as null, and your $this->entityManager->flush() will try to write null values in database, but you have a constraint that at least title must not be null.
So check your $data array contains the title, description and featured fields before to initiate your Auto object...
My config file
config/login_rules
i have defined my login form validation rules here
<?php
/**
* SETTING VALIDATION RULES FOR THE LOGIN FORM
*/
$config['login_settings'] = array(
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|trim|min_length[6]|max_length[20]|xss_clean',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|trim|valid_email|xss_clean'
)
);
/**
* SETTING ATTRIBUTES FOR THE LOGIN FORM
*/
$config['login_attribute'] = array(
'form' => array(
'id' => 'loginform',
'class' => 'form-horizontal',
'role' => 'form'
),
'email'=> array(
'id'=>'login-username',
'class' => 'form-control',
'name'=>'email',
'placeholder' => 'Enter Email',
'value'=>set_value('email')
),
'password' =>array(
'id'=>'login-password',
'class' => 'form-control',
'name'=>'password',
'placeholder'=>'Enter Password'
),
'checkbox' =>array(
'id' => 'login-remember',
'class' => 'form-control',
'name' => 'remember_me',
'value' => '1',
'checked' => TRUE
),
'submit' =>array(
'id' => 'btn-login',
'class' => 'btn btn-success',
'name' => 'submit',
'value' => 'Login'
)
);
?>
My Controller (Login.php)
in my controller i am loading the config file trying to apply validation rules for it
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class login extends CI_Controller {
public function __construct()
{
parent::__construct();
//$this->output->enable_profiler(TRUE);
}
public function index()
{
echo 'login controller index fun';
}
public function login()
{
$this->config->load('login_rules');
$this->form_validation->set_rules($this->config->item('login_settings'));
$data["login_attrib"] = $this->config->item("login_attribute");
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login_form',$data["login_attrib"]);
}
else
{
echo 'Success';
}
}
}
?>
i am not getting any error , nor the validation rules are working
View file (login_form.php)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<?php echo validation_errors();
echo form_open('login/login',$form);
echo form_input($email);
echo form_input($password);
echo form_submit($submit);
echo form_close();
?>
</body>
</html>
Try this .
$this->config->load('login_rules');
$this->form_validation->set_rules($this->config->item('login_settings'));
It will be useful for you.
So basically I have a view action in my users controller where the user can modify his information(username,first name, last name, email..) this form sends to another update action which does the saving stuff, problem is that when I submit the form and one or more fields don't meet the validation rules it doesn't show underneath each fields but the data doesn't save and
$this->User->validationErrors
outputs the errors.
my update action (accessed after submiting the form on view.ctp)
view.ctp:
<?php
echo $this->Form->create('User', array(
'inputDefaults' => array(
'div' => 'form-group',
'wrapInput' => false,
'class' => 'form-control'
),
'class' => 'well',
'url'=>array('controller'=>'users','action'=>'update'),
'id'=>'info-form'
));
?>
<fieldset>
<legend>Personal Information</legend>
<?php
echo $this->Form->input('id', array('value' => $userinfo['User']['id']));
echo $this->Form->input('User.username', array(
'label' => 'Username',
'value'=>$userinfo['User']['username']
));
?>
<td><?php echo $this->Form->error('username'); ?></td>
<?php
echo $this->Form->input('User.email', array(
'label' => 'E-mail',
'value'=>$userinfo['User']['email']
));
?>
<?php
echo $this->Form->input('User.fname', array(
'label' => 'First name',
'value'=>$userinfo['User']['fname']
));
?>
<?php
echo $this->Form->input('User.lname', array(
'label' => 'Last name',
'value'=>$userinfo['User']['lname']
));
?>
<?php
echo $this->Form->submit('Update', array(
'div' => 'form-group',
'class' => 'btn btn-success'
));
?>
</fieldset>
<?php echo $this->Form->end(); ?>
update function:
function update() {
$this->autoRender = false;
$this->User->set($this->request->data);
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Information updated Successfuly.'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-success'), 'success');
return $this->redirect('/users/view/' . $this->request->data['User']['id']);
} else {
// $errors = $this->User->validationErrors; var_dump($errors);die;
$this->Session->setFlash(__('An error occured'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-danger'), 'danger');
return $this->redirect('/users/view/' . $this->request->data['User']['id']);
}
} else {
$this->Session->setFlash(__('Request was not of POST type.'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-danger'), 'danger');
return $this->redirect('/users/index/');
}
It's because you're redirecting after - that will make it lose the validation warnings.
In YII views folder i have test module and admin.php file to manage contents are below and i render form here where i put the code of form and dropdown in it , i want that grid refresh value of status change in dropdown
Suppose i select "Approved" than Grid show the data where status is approved
<?php
Yii::app()->clientScript->registerScript('dropdown', "
$('.dropdown-form form').submit(function(){
$('#testimonial-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
<h1>Manage Testimonials</h1>
<div class="dropdown-form">
<?php $this->renderPartial('_dropdownform',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'testimonial-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'created_by',
'test_name',
'test_email',
'comments',
'created_at',
/*
'status',
'approved_on',
'approved_by',
*/
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Form below is _dropdownform , it contain a form and dropdown from this dropdown i am choosing the value of status
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
));
?>
<div class="row">
<?php
echo CHtml::dropDownList('status', '', array(0 => 'New', 1 => 'Approved', 2 => 'Declined'), array(
'prompt' => 'Select Status',
'ajax' => array(
'type' => 'POST',
'url' => Yii::app()->createUrl('testimonial/loadthedata'),
//or $this->createUrl('loadcities') if '$this' extends CController
'update' => '#testimonial-grid', //or 'success' => 'function(data){...handle the data in the way you want...}',
'data' => array('status' => 'js:this.value'),
)));
?>
</div>
<div class="row buttons">
<?php //echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form -->
AND THE CODE IN MY CONTROLLER OR URL GIVEN IN DROPDOWN TO FETCH DATA IS FOLLOWING ACTION BUT I DONT KNOW HOW TO FETCH DATA FROM THIS FUNCTION AND PASS TO GRID VIEW
public function actionloadthedata() {
if (isset($_POST['status'])) {
$status = $_POST['status'];
if($status==0){
$status='New';
}
if($status==1){
$status='Approved';
}
if($status==2){
$status='Declined';
}
Testimonial::model()->findByAttributes(array('status'=>$status));
}
}
You can use CGridView property filterCssClass to link the grid filter, for example
$this->widget('CGridView', array(
'id' => 'my-list',
'filterCssClass' => '#filterFormId .filter',
And there is filter form
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'filter-fomr-id',
)); ?>
<div class="filter clearfix">
<?php echo $form->dropDownList($model, 'name', [0=>'all', '1'=>'some else']); ?>
</div>
Replace #filterFormId .filter on jquery selector specific to you form. In other words, set id attribute for filter form, then use "#THISID .row".
In your gridview file, make sure you have this code:
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$('#ad-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
then in the CGridView definition:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'testimonial-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
...
array(
'name'=>'Status',
'filter'=>CHtml::dropDownList('YourModel[status]', $model->status, array(0 => 'New', 1 => 'Approved', 2 => 'Declined'), array('empty' => '--all--') ),
'value'=>'( $data->status == 0) ? "New": ( $data->status == 1) ? "Approved" : "Declined"',
'htmlOptions' => array(
'style' => 'width: 40px; text-align: center;',
),
),
...
array(
'class'=>'CButtonColumn',
),
),
));
// CGridView
In order to save if/else in the 'value' section, you can implement a method in your model that returns the string associated to the integer.
It works great, just with the default Yii admin.php view, which you can edit as much as you need.
Update
Added support for empty status, does not filter query results
Thanks #Alex for your help but i am successful to make filterdropdown for grid , code is following but will you please tell me that i want that grid show only values where status=New , how i can do when page load grid show values where status is New
but first i paste the working code of dropdown filter for grid
Here is my admin.php file
<?php
$this->breadcrumbs = array(
'Testimonials' => array('index'),
'Manage',
);
$this->menu = array(
array('label' => 'List Testimonial', 'url' => array('index')),
array('label' => 'Create Testimonial', 'url' => array('create')),
);
?>
<h1>Manage Testimonials</h1>
<!-----------drop down form------------->
<?php
Yii::app()->clientScript->registerScript('dropdownfilter', "
$('.dropdown-form form #staticid').change(function(){
$.fn.yiiGridView.update('testimonial-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<div class="dropdown-form">
<?php
$this->renderPartial('_dropdownfilter', array(
'model' => $model,
));
?>
</div><!-- search-form -->
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'testimonial-grid',
'dataProvider' => $model->search(),
// 'filter' => $model,
'columns' => array(
'id',
'created_by',
'test_name',
'test_email',
'comments',
'created_at',
'status',
array(
'class' => 'CButtonColumn',
),
),
));
?>
Here is my render partial form where i place the static drop dow
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
));
?>
<div class="row">
<?php
echo CHtml::dropDownList('staticid', '', array('0' => 'New', '1' => 'Approved', '2' => 'Declined'), array(
// 'onChange' => 'this.form.submit()',
'ajax' => array(
'type' => 'POST', //request type
)));
?>
</div>
<?php $this->endWidget(); ?>
And Here is code of my adminaction in controller
public function actionAdmin() {
$model = new Testimonial('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['staticid'])) {
$getStatus = $_GET['staticid'];
if ($getStatus == 0)
$status = 'New';
if ($getStatus == 1)
$status = 'Approved';
if ($getStatus == 2)
$status = 'Declined';
$model->status = $status;
}
if (isset($_GET['Testimonial']))
$model->attributes = $_GET['Testimonial'];
$this->render('admin', array(
'model' => $model,
));
}
Now i want that when i actionadmin triggered first time it show status=New values
I’ve a problem with implementing recaptcha in a CodeIgniter application.
The problem is that the recapctha_challenge_field and recaptcha_response_field do not get posted, however, the recapctcha (and those fields) is visible on the page (within the form).
The the recapctha_challenge_field and recaptcha_response_field are appearing in the HTML of the page, but not in the header when I post the form.
I’ve downloaded de recaptcha library and added it as an helper in CI.
Within the form in my view I echo the recaptcha_get_html($publickey) (with the public key set).
In my controller, I load the recaptchalib_helper and add set a form validation rule for the recapctha_challenge_field.
This is my view:
<h1>Register</h1>
<fieldset>
<legend>Personal information</legend>
<?php
echo form_open('login/create_user');
echo form_label('First name:', 'first_name');
echo form_input(
array(
'name' => 'first_name',
'id' => 'first_name',
'value' => set_value('first_name')
)
);
echo form_label('Last name:', 'last_name');
echo form_input(
array(
'name' => 'last_name',
'id' => 'last_name',
'value' => set_value('last_name')
)
);
echo form_label('Birth date:', 'birth_date');
echo form_input(
array(
'name' => 'birth_date',
'id' => 'birth_date',
'value' => set_value('birth_date')
)
);
echo form_label('E-mail:', 'email');
echo form_input(
array(
'name' => 'email',
'id' => 'email',
'value' => set_value('email')
)
);
?>
</fieldset>
<fieldset>
<legend>Login information</legend>
<?php
echo form_label('Username:', 'username');
echo form_input(
array(
'name' => 'username',
'id' => 'username',
'value' => set_value('username')
)
);
echo form_label('Password:', 'password1');
echo form_password(
array(
'name' => 'password1',
'id' => 'password1',
'value' => set_value('password1')
)
);
echo form_label('Confirm password:', 'password2');
echo form_password(
array(
'name' => 'password2',
'id' => 'password2',
'value' => set_value('password2')
)
);
$publickey = "mypublickey"; // here I entered my public key
echo recaptcha_get_html($publickey);
echo form_label(nbs(1), 'submit');
echo form_submit(
array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Registreren'
)
);
echo form_close();
?>
<?php echo validation_errors('<p class="error">'); ?>
</fieldset>
</div>
and this is a part of my controller:
function create_user() {
print_r($_POST);//for debugging
$this->load->library('form_validation');
$this->load->model('user');
$this->form_validation->set_rules('recaptcha_challenge_field', 'Captcha', 'callback_validate_captcha');
$this->form_validation->set_rules('first_name', 'First name', 'trim|xss_clean|required');
$this->form_validation->set_rules('last_name', 'Last name', 'trim|xss_clean|required');
$this->form_validation->set_rules('email', 'E-mail', 'trim|xss_clean|valid_email|callback_is_email_available|required');
$this->form_validation->set_rules('username', 'Username', 'trim|xss_clean|min_length[5]|callback_is_username_available|required');
$this->form_validation->set_rules('password1', 'Password', 'trim|xss_clean|min_length[8]|max_length[32]|required');
$this->form_validation->set_rules('password2', 'Confirm password', 'trim|xss_clean|matches[password1]|required');
if ($this->form_validation->run() == FALSE) {
$this->signup();
} else {
if ($this->user->create_user($this->input->post('username'),$this->input->post('password1'),$this->input->post('email'),$this->input->post('first_name'),$this->input->post('last_name'),$this->input->post('birth_date'))) {
$data['main_content'] = 'login/signup_successful';
$this->load->view('includes/template', $data);
} else {
$this->load->view('login/signup_form');
}
}
}
public function validate_captcha($recaptcha_challenge_field) {
$this->load->helper('recaptchalib');
$privatekey = "myprivatekey";//this is et to my private key
$resp = recaptcha_check_answer ($privatekey,
$this->input->ip_address(),
$this->input->post("recaptcha_challenge_field"),
$this->input->post("recaptcha_response_field"));
if (!$resp->is_valid) {
$this->form_validation->set_message('validate_captcha', 'Invalid Capctha code entered.');
return FALSE;
} else {
return TRUE;
}
}
The capctha fields are not set in the HTTP headers:
Form data:
csrf_test_name:8cc3f2391784867df2d46f193a65a317
first_name:Myfirstname
last_name:Mylastname
birth_date:10-12-2012
email:myemail#adres.com
username:username
password1:password
password2:password
submit:Register
What am I doing wrong?
Your sincerely,
Alwin
Does the form tag not begin within a table, tbody or tr?