Duplicating forms and having troubles with MYSQL and Codeigniter - php

The form is duplicating in a page. I cant upload the picture though:(
I dont remember having any loop for that. I badly need help. This is my
view_register.php
<body>
<h1>IMAGE HERE</h1>
<div id="body">
<br/>
<p class="body">
<!--trial-->
<?php
echo form_open('start');
$firstname = array(
'name' => 'firstname',
'value' => set_value('firstname')
);
$lastname = array(
'name' => 'lastname',
'value' => set_value('lastname')
);
$email = array(
'name' => 'email',
'value' => set_value('email')
);
$dateofbirth = array(
'name' => 'dateofbirth',
'value' => set_value('dateofbirth')
);
$gender = array(
'name' => 'gender',
'value' => set_value('gender'),
'style' => 'margin:10px'
);
$username = array(
'name' => 'username',
'value' => set_value('username')
);
$password = array(
'name' => 'password',
'value' => ''
);
$confpass = array(
'name' => 'confpass',
'value' => ''
);
?>
<!--trial ends here-->
<strong>User Information: </strong>
<div align="right"><font color="red">*</font>Denotes Required Field</div>
<div align="left">
First Name<font color="red">*</font>:
<?php echo form_input($firstname)?>
<br/>
Last Name<font color="red">*</font>:
<?php echo form_input($lastname)?>
<br/>
Email Address<font color="red">*</font>:
<?php echo form_input($email)?>
<br/>
Date Of Birth:
<?php echo form_input($dateofbirth)?>
<br/>
Gender:
<?php
echo form_radio($gender, 'Male');
echo "Male";
echo form_radio($gender, 'Female');
echo "Female";
?>
<br/>
<strong>Account Information:</strong><br/>
Username<font color="red">*</font>:
<?php echo form_input($username)?><br/>
Password<font color="red">*</font>:
<?php echo form_password($password)?><br/>
Password Confirmation<font color="red">*</font>:
<?php echo form_password($confpass)?><br/>
<?php
echo validation_errors();?>
<?php echo form_submit(array('name'=>'register'), 'Register');?>
<?php echo form_reset(array('name'=>'reset'), 'Reset')?>
</div>
</body>
This is my user.php. I'm not really sure with the codes. these are mostly form tutorials i've seen..
class User extends CI_Controller {
private $view_data = array();
function _construct()
{
parent::_construct();
$this->view_data['base_url']=base_url();
}
function index()
{
$this->register();
}
function register()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|max_length[100]|min_length[1]|xss_clean');
$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|max_length[100]|min_length[1]|xss_clean');
$this->form_validation->set_rules('email', 'Email Address', 'trim|required|max_length[100]|xss_clean|valid_email');
$this->form_validation->set_rules('dateofbirth', 'Date of Birth', 'trim|max_length[100]|min_length[1]|xss_clean');
$this->form_validation->set_rules('gender', 'Gender', 'trim|max_length[6]|min_length[6]|xss_clean');
$this->form_validation->set_rules('username', 'User Name', 'trim|required|alpha_numeric|callback_username_not_exists|max_length[100]|min_length[6]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
//not run
$this->load->view('view_register', $this->view_data);
}
else
{
//good
$firstname=$this->input->post('firstname');
$lastname=$this->input->post('lastname');
$email=$this->input->post('email');
$dateofbirth=$this->input->post('dateofbirth');
$gender=$this->input->post('gender');
$username=$this->input->post('username');
$password=$this->input->post('password');
$this->User_model->register_user($firstname, $lastname, $email, $dateofbirth, $gender, $username, $password);
}
$this->load->view('view_register', $this->view_data);
}
Then after that I am stuck. After clicking Register, It says Page404 Not Found, there's not even a validation.

First. Find new tutorials, there is a lot of code in there that makes zero sense. I strongly suggest this series: http://net.tutsplus.com/sessions/codeigniter-from-scratch/
Next. You're getting a page not found because your form action leads no where. In the line:
echo form_open('start');
You're trying to call a function in your controller called 'start' yet there is no function in your controller called start. The function is called register.
Next. You're running the form validation before even seeing if there is any post data and you're actually running it before there CAN be any post data.
You're getting the form twice probably because you're loading the same view into the page twice, once when the form validation fails, which it obviously will the first time you load then again when you're calling your user model.
Quite honestly the only answer here is to nuke what you've done, reinstall CI and follow the tutorial series I gave you above. The tutorials you're following are giving you very bad practices and you need to just forget what they've taught you. Follow the Nettuts tutorial one step at a time and make sure you're understanding what it's telling you before moving on. Don't just copy and paste and cross your fingers.

Related

How do I use CodeIgniter's `set_value()` function when using `form_validation.php`?

Problem:
I've got a form I'm trying to re-populate via the CodeIgniter docs, and I'm trying to use the set_value() function in my view file, but I receive an error: Message: Call to undefined function set_value().
I saw elsewhere on StackOverflow solutions to a similar problem when using the set_rules() function to define validations on a field-by-field basis.
However, I've got all of my validations together in config/form_validation.php, as sets of rules. Because all of my validations are defined within the rule set, it seems a little different than when defining field-by-field.
My rule set, controller, model and view methods are below.
Any idea why my re-population is not working?
Thanks for any insight anyone can offer, I'm new to CodeIgniter and I might be misunderstanding how things are working.
Validation Rules via config/form-validation.php:
$config = array(
'create' => array (
array(
'field' => 'name',
'label' => 'product name',
'rules' => 'trim|required|min_length[5]',
),
array(
'field' => 'description',
'label' => 'product description',
'rules' => 'trim|required|min_length[5]',
),
array(
'field' => 'price',
'label' => 'product price',
'rules' => 'trim|required|min_length[1]|less_than[100000]|decimal',
),
),
);
In my Controller:
public function create()
{
// XSS FILTER $POST OBJECT
$new_product = $this->input->post(null, true);
// SEND TO MODEL
$this->load->model("Product_model");
$product = $this->Product_model->add_product($new_product);
// IF VALIDATIONS RETURN FALSE, STORE ERRORS IN FLASH SESSION
if ($product[0] === FALSE)
{
$this->session->set_flashdata('errors', $product[1]);
redirect("/products/new");
}
// IF VALIDATION PASSES, SEND HOME
redirect("/");
}
In my Model:
public function add_product($product)
{
$this->load->library("form_validation");
if ($this->form_validation->run("create") === FALSE)
{
// STORE ERRORS & SHIP BACK TO CONTROLLER:
return array(FALSE, validation_errors());
}
else
{
// Success, Escape strings and insert to DB and return TRUE (or item)
}
}
In my form View:
(The page which displays returned errors above the form)
<form action="./create" method="POST">
<input type="text" name="name" id="name" value="<?php echo set_value('name'); ?>">
<textarea name="description" id="description" cols="30" rows="10" value="<?php echo set_value('description'); ?>"></textarea>
<input type="number" name="price" id="price" value="<?php echo set_value('price'); ?>">
<input type="submit" value="Create">
</form>
Hope this will help you :
add form_helper in your controller or in autoload.php
In controller :
public function __construct()
{
parent::__construct();
$this->load->helper('form');
}
Or in autoload.php :
$autoload['helper'] = array('form','url');
For more : https://www.codeigniter.com/userguide3/libraries/form_validation.html#re-populating-the-form

cakephp validation view issue?

First post here on stack overflow so I hope I do it right, I have searched but cannot find what I am looking for.
i am new to cakephp and fairly new to php. I was able to get up and running yesterday no problem and can send data to my database. to day I wanted to work on validation with ajax but I think I am going to leave the ajax out of it for a little while as I have a problem with the validation errors displaying.
The validation is set up for the first two form fields like this;
<?php
class people extends AppModel
{
public $name = 'people';
public $useTable = 'people';
public $validate = array(
'firstName'=>array(
'rule'=>'notEmpty',
'message'=>'Enter You First Name'
),
'secondName'=>array(
'rule'=>'notEmpty',
'message'=>'Enter Your Second/Family Name'
),
);
}?>
and it works fine if those fields are empty it wont write to the database so far so good. However, when I hit submit on the form the page refreshes, the error messages appear under the form fields but it also adds a completely new form under the previous one. here is the controller. Note: the validate_form function is from an cakephp with ajax tutorial i was following and is commented out
<?php
class peoplesController extends AppController
{
public $name = "peoples";
public $helpers = array('Html', 'form', 'Js');
public $components = array('RequestHandler');
public function index() {
if( $this->request->is('post'))
{
$data = $this->request->data;
$this->people->save($data);
}
}
/*public function validate_form() {
if ($this->RequestHandler->isAjax()) {
$this->data['people'][$this->params['form']['field']] = $this->params['form']['value'];
$this->people->set($this->data);
if ($this->people->validates()) {
$this->autoRender = FALSE;
}
else {
$error = $this->validateErrors($this->people);
$this->set('error', $error[$this->params['form']['field']]);
}
}
}*/
}
?>
and the view. note: the divs with id sending and success are also from the tutorial I was following but I dont think would have an effect on this particular issue.
<div id="success"></div>
<h2> Fill in your profile details </h2>
<?php
echo $this->Form->create('people');
echo $this->Form->input('firstName');
echo $this->Form->input('secondName');
echo $this->Form->input('addressOne');
echo $this->Form->input('addressTwo');
echo $this->Form->input('city');
echo $this->Form->input('county');
echo $this->Form->input('country');
echo $this->Form->input('postCode', array(
'label' => 'Zip Code',
));
echo $this->Form->input('dob', array(
'label' => 'Date of birth',
'dateFormat' => 'DMY',
'minYear' => date('Y') - 70,
'maxYear' => date('Y') - 18,
));
echo $this->Form->input('homePhone');
echo $this->Form->input('mobilePhone');
echo $this->Form->input('email', array(
'type' => 'email'
));
$goptions = array(1 => 'Male', 2 => 'Female');
$gattributes = array('legend' => false);
echo $this->Form->radio('gender',
$goptions, $gattributes
);
echo $this->Form->input('weight');
echo $this->Form->input('height');
$toptions = array(1 => 'Tandem', 2 => 'Solo');
$tattributes = array('legend' => false);
echo $this->Form->radio('trained',
$toptions, $tattributes
);
echo $this->Form->input('referedBy');
/*echo $this->Form->submit('submit');*/
echo $this->Js->submit('Send', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success'
));
echo $this->Form->end();
?>
<div id="sending" style="display: none; background-color: lightgreen">Sending.... </div>
<?php
echo $this->Html->script(
'validation', FALSE);
?>
so the creation of the second identical form on the same page is my primary problem, I think it has something to do with the controller taking the first form and sending it back to the same view but I dont know how to trouble shoot this.
a second problem is that for some reason if I use
echo $this->Form->submit('submit');
instead of
echo $this->Js->submit('send', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('sending')->effect('fadeOut'),
'update'=>'#success'));
Then I dont get my error messages anymore I instead just get a bubble that appears and says 'please fill in this field' I am sure this is a jquery issue but again I dont know how to trouble shoot it so that that bullbe does not appear and it instead shows the error messages I want
Thanks in advance
Couple things:
1) Use Caps for your classnames. So People, PeoplesController, etc
2) Don't mess with Ajax until you get the standard flow working. So go back to $this->Form->submit('submit');.
3) That "required" tooltip is HTML5. Since you set the validation to notEmpty, Cake adds HTML5 markup to make the field required. Modify your Form->create call to bypass that for now (if you need to, but it provides client-side validation which is more efficient):
$this->Form->create('People', array('novalidate' => true));
See the FormHelper docs for more info on HTML5 validations

connecting pages in codeigniter

i have a simple question i have a form where user enters his details and when the submit button is clicked whit his details submitted to database it will take the user to a different page i am using codeigniter and i am new to this is there an easy way to do this ? tnx for you help. here is my cmv:
controller
<?php
class Info extends CI_Controller{
function index(){
$this->load->view('info_view');
}
// insert data
function credentials()
{
$data = array(
'name' => $this->input->post('name'),
'second_name' => $this->input->post('second_name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
);
$this->info_model->add_record($data);
}
}
?>
model
<?php
class Info_model extends CI_Model {
function get_records()
{
$query = $this->db->get('credentials');
return $query->result();
}
function add_record($data)
{
$this->db->insert('credentials', $data);
return;
}
}
?>
view
<html>
<head>
</head>
<body>
<?php echo form_open('info/credentials'); ?>
<ul id="info">
<li>Name:<?php echo form_input('name')?></li>
<li>Second Name: <?php echo form_input('second_name');?></li>
<li>Phone: <?php echo form_input('phone');?></li>
<li>Email: <?php echo form_input('email');?></li>
<li><?php echo form_submit('submit', 'Start survay!!' );?></li>
</ul>
<?php echo form_close();?>
</body>
</html>
If all you need is a simple redirect upon submission of the form:
$this->info_model->add_record($data);
redirect('controller/method');
You could use the redirect() function from the URL Helper to actually redirect the user
(http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html)
Like this:
$this->load->helper('url');
redirect('/some/other/page');
Note that this has to be called before any data is outputted to the browser.
Another way of doing it is to simply have two different views that you load depending on the context. Normally you want some form validation as well so you can use that to direct the user. I usually end up with something like this in my function, which is used both for posting the data, inserting it to the database and "redirecting":
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required|trim|xss_clean');
/* More validation */
if ($this->form_validation->run() !== FALSE) {
$data = array(
'name' => $this->input->post('name'),
'second_name' => $this->input->post('second_name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
);
$this->info_model->add_record($data);
$this->load->view('some_other_view');
} else {
$this->load->view('info_view');
}
You can also use refresh as a second parameter:
$this->info_model->add_record($data);
redirect('controllerName/methodName','refresh');

Yii form and values of inputs

Im try working with Yii framework. I have 5 inputs like this
<div class="field">
<?php echo $form->label($model, 'name') ?>
<?php echo $form->textField($model, 'name'); ?>
<?php echo $form->error($model, 'name', array('class' => 'label label-important')); ?>
</div>
And this is my rules in model
public function rules() {
return array(
array('email, message', 'required', 'message' => 'Заполните поле'),
array('email', 'email', 'message' => 'Некорректный емаил')
);
}
If user does not pass validate, all values of inputs delete except email and message. Because i have 'method' required. How me save all values of form without required?
If you want to have input saved without any rules, you should define it as safe attribute, here is very good article about that: http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/

Symfony 1.4 form won't validate

I'm hoping someone can point me in the right direction here. This is my first Symfony project, and I'm stumped on why the form won't validate.
To test the application, I fill out all of the form inputs and click the submit button and it fails to validate every time. No idea why.
Any help will be appreciated!
The view -- modules/content/templates/commentSuccess.php :
<?php echo $form->renderFormTag('/index.php/content/comment') ?>
<table>
<?php echo $form['name']->renderRow(array('size' => 25, 'class' => 'content'), 'Your Name') ?>
<?php echo $form['email']->renderRow(array('onclick' => 'this.value = "";'), 'Your Email') ?>
<?php echo $form['subject']->renderRow() ?>
<?php echo $form['message']->renderRow() ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
The controller -- modules/content/actions/actions.class.php :
public function executeComment($request)
{
$this->form = new ContentForm();
// Deal with the request
if ($request->isMethod('post'))
{
$this->form->bind($request->getParameter("content"));
if ($this->form->isValid())
{
// Do stuff
//$this->redirect('foo/bar');
echo "valid";
}
else
{
echo "invalid";
}
}
}
The form -- /lib/form/ContentForm.class.php :
class ContentForm extends sfForm {
protected static $subjects = array('Subject A', 'Subject B', 'Subject C');
public function configure()
{
$this->widgetSchema->setNameFormat('content[%s]');
$this->widgetSchema->setIdFormat('my_form_%s');
$this->setWidgets(array(
'name' => new sfWidgetFormInputText(),
'email' => new sfWidgetFormInput(array('default' => 'me#example.com')),
'subject' => new sfWidgetFormChoice(array('choices' => array('Subject A', 'Subject B', 'Subject C'))),
'message' => new sfWidgetFormTextarea(),
));
$this->setValidators(array(
'name' => new sfValidatorString(),
'email' => new sfValidatorEmail(),
'subject' => new sfValidatorString(),
'message' => new sfValidatorString(array('min_length' => 4))
));
$this->setDefaults(array(
'email' => 'me#example.com'
));
}
}
Thanks in advance! I'll edit this post as needed during progress.
EDIT
I've changed my view code to this:
<?php echo $form->renderFormTag('/frontend_dev.php/content/comment') ?>
<table>
<?php if ($form->isCSRFProtected()) : ?>
<?php echo $form['_csrf_token']->render(); ?>
<?php endif; ?>
<?php echo $form['name']->renderRow(array('size' => 25, 'class' => 'content'), 'Your Name') ?>
<?php echo $form['email']->renderRow(array('onclick' => 'this.value = "";'), 'Your Email') ?>
<?php echo $form['subject']->renderRow() ?>
<?php echo $form['message']->renderRow() ?>
<?php if ($form['name']->hasError()): ?>
<?php echo $form['name']->renderError() ?>
<?php endif ?>
<?php echo $form->renderGlobalErrors() ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
This gives a required error on all fields, and gives " csrf token: Required.
" too.
My controller has been updated to include $this->form->getCSRFToken(); :
public function executeComment($request)
{
$this->form = new ContentForm();
//$form->addCSRFProtection('flkd445rvvrGV34G');
$this->form->getWidgetSchema()->setNameFormat('contact[%s]');
$this->form->getCSRFToken();
// Deal with the request
if ($request->isMethod('post'))
{
$this->form->bind($request->getParameter("content[%s]"));
if ($this->form->isValid())
{
// Do stuff
//$this->redirect('foo/bar');
echo "valid";
}
else
{
$this->_preWrap($_POST);
}
}
}
Still don't know why it's giving me an error on all fields and why I'm getting the csrf token: Required.
When you take full control of a Symfony form, as you are doing according to the code snippets in your OP, you will have to manually add the error and csrf elements to your form:
// Manually render an error
<?php if ($form['name']->hasError()): ?>
<?php echo $form['name']->renderError() ?>
<?php endif ?>
<?php echo $form['name']->renderRow(array('size' => 25, 'class' => 'content'), 'Your Name') ?>
// This will echo out the CSRF token (hidden)
<?php echo $form['_csrf_token']->render() ?>
Check out Symfony Docs on custom forms for more info. Also, be sure to add CSRF back to your form, there is no reason to leave it out, and will protect from outside sites posting to your forms.
It might be wise to render any global form errors:
$form->renderGlobalErrors()
Don't you have a typo in your executeComment function ?
$this->form->getWidgetSchema()->setNameFormat('contact[%s]');
and later:
$this->form->bind($request->getParameter("content[%s]"));
You should write:
$this->form->getWidgetSchema()->setNameFormat('content[%s]');
But this line is not necessary you can delete it (the NameFormat is already done in your form class).
And the $request->getParameter("content[%s]") will not word ("content[%s]" is the format of the data sent by the form), you should use:
$this->form->bind($request->getParameter("content"));
Or best, to avoid this kind of typo:
public function executeComment($request)
{
$this->form = new ContentForm();
// Deal with the request
if ($request->isMethod('post'))
{
$this->form->bind($request->getParameter($this->form->getName()));
if ($this->form->isValid())
{
// Do stuff
//$this->redirect('foo/bar');
echo "valid";
}
else
{
$this->_preWrap($_POST);
}
}
}
I ran into the same problem with an admin generated backend form. When I tried to apply css schema changes with this code, it broke the token. It didn't break right away. That signals to me this is a bug in Symfony 1.4
$this->setWidgetSchema(new sfWidgetFormSchema(array(
'id' => new sfWidgetFormInputHidden(),
'category' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('RidCategories'), 'add_empty' => false)),
'location_id' => new sfWidgetFormInputText(),
'title' => new sfWidgetFormInputText(array(), array('class' => 'content')),
'content' => new sfWidgetFormTextarea(array(), array('class' => 'content')),
'content_type' => new sfWidgetFormInputText(),
'schedule_date' => new sfWidgetFormInputText(),
'post_date' => new sfWidgetFormInputText(),
'display_status' => new sfWidgetFormInputText(),
'parent_id' => new sfWidgetFormInputText(),
'keyword' => new sfWidgetFormInputText(),
'meta_description' => new sfWidgetFormInputText(),
'update_frequency' => new sfWidgetFormInputText(),
'keywords' => new sfWidgetFormInputText(),
'allow_content_vote' => new sfWidgetFormInputText(),
'rating_score' => new sfWidgetFormInputText()
)));

Categories