Yii form and values of inputs - php

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/

Related

How to write form tag in codeignter

I have use codeignter, I need to write form tag using codeignter how to do this
I don't need normal html form tag.
<Form>
I don't need like this
Here is an example of form helper in codeigniter.
<?php
echo form_open('create_user.php', ['id' => 'frmUsers']); #formTagOpen
echo form_label('User Id', 'user_id'); #formLabel
echo form_input(['name' => 'user_id']); #formInput
echo form_label('Password', 'password'); #formLabel
echo form_input(['type' => 'password', 'name' => 'password']); #formInputPassword
echo form_submit('btnSubmit', 'Create User'); #formSubmitButton
echo form_close(); #formClosingTag
?>
To learn more you can refer this

CakePHP 3 - How to automatically show validation errors in view for form without model

I'm reviewing a basic contact form which is not associated with any model. I would like some advice on the best way to leverage Cake's automatic view rendering of field errors for this situation.
Controller
Performs validation through a custom Validator.
public function index()
{
if ($this->request->is('post')) {
// Validate the form
$validator = new EnquiryValidator();
$data = $this->request->data();
$errors = $validator->errors($data);
if (empty($errors)) {
// Send email, etc.
// ...
// Refresh page on success
}
// Show error
$this->Flash->error('Unable to send email');
}
}
View
<?= $this->Form->create(); ?>
<?= $this->Form->input('name', [
'autofocus' => 'autofocus',
'placeholder' => 'Your name',
'required'
]);
?>
<?= $this->Form->input('email', [
'placeholder' => 'Your email address',
'required'
]);
?>
<?= $this->Form->input('subject', [
'placeholder' => 'What would you like to discuss?',
'required'
]);
?>
<?= $this->Form->input('message', [
'label' => 'Query',
'placeholder' => 'How can we help?',
'cols' => '30',
'rows' => '10',
'required'
]);
?>
<div class="text-right">
<?= $this->Form->button('Send'); ?>
</div>
<?= $this->Form->end(); ?>
Currently the form will not show any errors next to the input fields. I assume it's because there is no entity associated with the form or something like that, but I'm not sure.
What is the best solution? Can the validation be performed in a better way to automatically provide field errors in the view?
Modelless forms
Use a modelless form. It can be used to validate data and perform actions, similar to tables and entities, and the form helper supports it just like entities, ie, you simply pass the modelless form instance to the FormHelper::create() call.
Here's the example from the docs, modified a little to match your case:
src/Form/EnquiryForm.php
namespace App\Form;
use App\...\EnquiryValidator;
use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\Validation\Validator;
class EnquiryForm extends Form
{
protected function _buildSchema(Schema $schema)
{
return $schema
->addField('name', 'string')
->addField('email', ['type' => 'string'])
->addField('subject', ['type' => 'string'])
->addField('message', ['type' => 'text']);
}
protected function _buildValidator(Validator $validator)
{
return new EnquiryValidator();
}
protected function _execute(array $data)
{
// Send email, etc.
return true;
}
}
in your controller
use App\Form\EnquiryForm;
// ...
public function index()
{
$enquiry = new EnquiryForm();
if ($this->request->is('post')) {
if ($enquiry->execute($this->request->data)) {
$this->Flash->success('Everything is fine.');
// ...
} else {
$this->Flash->error('Unable to send email.');
}
}
$this->set('enquiry', $enquiry);
}
in your view template
<?= $this->Form->create($enquiry); ?>
See also
Cookbook > Modelless Forms

Passing temporary data back to hidden field in Yii

I'm trying to pass a temporary data from my form to my model. My form has a hidden data in it, but it does not get any values from my model.
My form is
<?php echo $form->hiddenField($model, 'fieldName'); ?>
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
<?php echo $form->error($model,'name'); ?>
I threw in the data for my hidden field using JQuery, and then I proceeed to validate my form.
public function rules()
{
return array(
array('name, email, subject, phone, body', 'required','message' => '{attribute} Required'),
array('resume', 'file', 'types'=>'txt,pdf,doc,docx', 'maxSize'=>2097152, 'tooLarge'=>'File has to be smaller than 2MB','allowEmpty'=>false),
array('email', 'email'),
);
}
Whenever the validation hits an exception, it returns all of the $_POST data I inputted except the data I sent from the hidden form.
How do I get the $_POST so it gets back to the hidden form?
First:
The attribute must be declared as public in the model.
public $fieldName;
Add in rules() of Model the field with a safe mode array('fieldName','safe') :
public function rules()
{
return array(
array('name, email, subject, phone, body', 'required','message' => '{attribute} Required'),
array('resume', 'file', 'types'=>'txt,pdf,doc,docx', 'maxSize'=>2097152, 'tooLarge'=>'File has to be smaller than 2MB','allowEmpty'=>false),
array('email', 'email'),
array('fieldName','safe'), // Add the custom field to 'safe' mode.
);
}
Is 'fieldName' part of the model/table? If not and it is just a custom property declared in the model, then try setting it as 'safe'

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');

Duplicating forms and having troubles with MYSQL and Codeigniter

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.

Categories