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');
Related
I am trying to get users to fill in much information so I need more than one form and page. I made a main_view.php which has a side bar on the left with links to sub1.php, sub2.php, sub3.php. On the right half of main_view.php, it displays the sub pages with corresponding forms. Part of the main_view.php looks like this:
<?php $view_path = "../../application/views/"?>
<span id="theFormChanger" >
<?php
?>
</span>
var currentPage = 0;
var subviews = ['sub1.php', 'sub2.php','sub3.php'];
$('#sub1').click(function(){
currentPage = 1;
$('#theFormChanger').load(viewpath + subviews[currentPage]);
});
Part of the code of sub view pages:
<?php echo form_open('v_controller'); ?>
<?php echo form_input(array( 'type' => 'text', 'id' => 'demail', 'name' =>'demail')); ?>
<?php echo form_input(array( 'type' => 'text', 'id' => 'dname', 'name' => 'dname')); ?>
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?>
For ../application/controllers/,there is a v_controller.php:
function __construct() {
parent::__construct();
}
public function index()
{
$this->load->helper('form');
$this->load->view('sub1');
$data = array(
'User_Name' => $this->input->post('dname'),
'User_Email' => $this->input->post('demail'));
}?>
Every time when I go to localhost:8000/main/main_view, the left part is fine but the right part says "Fatal error: Call to undefined function form_open() in main_view.php"
I searched around but couldn't find answers. I made sure everything is loaded in autoload.php.
Is this a routing problem? I can't directly go to view files? Please help me. Thank you!
You can load views on to a view file like so
application > views > default.php
<?php $this->load->view('template/common/header');?>
<?php $this->load->view('template/common/navbar');?>
<?php $this->load->view('template/' . $page);?>
<?php $this->load->view('template/common/footer');?>
And then on controller
<?php
class Example extends CI_Controller {
public function index() {
$data['page'] = 'common/example';
$this->load->view('default', $data);
}
}
you need to create NameOfController/NameOfMethod in the form open method in your view page.
replace our code by this one , it will be work for you.
<?php echo form_open('v_controller/index'); ?>
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
I have a simple form setup. It shows up fine and when I hit submit looks like it is working, but when I go to check the datat in MSSQL Server it is not there. I am not sure why it is not working.
Controller is insert.php
<?php
class insert extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('insert_model');
}
function index()
{
// Including Validation Library
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
// Validating Name Field
$this->form_validation->set_rules('EmpName', 'Employee_Name', 'required|min_length[3]|max_length[15]');
// Validating Email Field
$this->form_validation->set_rules('Department', 'Department', 'required|min_length[3]|max_length[15]');
// Validating Email Field
$this->form_validation->set_rules('LanID', 'LanID', 'required|min_length[3]|max_length[15]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('insert_view');
}
else
{
// Setting Values For Tabel Columns
$data = array(
'Employee_Name' => $this->input->post('EmpName'),
'Department' => $this->input->post('Department'),
'LanID' => $this->input->post('LanID'),
);
// Transfering Data To Model
$this->insert_model->form_insert($data);
// Loading View
$this->load->view('insert_view');
}
}
}
?>
Model is insert_model.php
<?php
class insert_model extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert($data){
// Inserting in Table(requests) of Database(employee)
$this->db->insert('requests', $data);
}
}
?>
View is insert_view.php
<html>
<head>
<title>Insert Data Into Database Using CodeIgniter Form</title>
</head>
<body>
<div id="container">
<?php echo form_open('insert'); ?>
<h1>Insert Data Into Database Using CodeIgniter</h1>
<?php echo form_label('Employee Name :'); ?> <?php echo form_error('EmpName'); ?>
<?php echo form_input(array('id' => 'EmpName', 'name' => 'EmpName')); ?>
<?php echo form_label('Department :'); ?> <?php echo form_error('Department'); ?>
<?php echo form_input(array('id' => 'Department', 'name' => 'Department')); ?>
<?php echo form_label('LanID :'); ?> <?php echo form_error('LanID'); ?>
<?php echo form_input(array('id' => 'LanID', 'name' => 'LanID')); ?>
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit'));?>
<?php echo form_close(); ?>
</div>
</body>
</html>
have you tried debugging?
in your controller:
$data = array(
'Employee_Name' => $this->input->post('EmpName'),
'Department' => $this->input->post('Department'),
'LanID' => $this->input->post('LanID'),
);
does all array index matches exactly with your database table's column name?
in your model:
print_r($data);
before:
$this->db->insert('requests', $data);
if $data contains data, try set function.
$this->db->set('Employee_Name', $EmpName);
$this->db->set('Department', $Department);
$this->db->set('LanID', $LanID);
$this->db->insert('requests');
try debugging...
I'm really new to Yii and as a starter, I want to know how to get the value from the textbox when the button is pressed.
<?php CHtml::textField($name,$value,array('submit'=>'')); ?>
<?php echo CHtml::submitButton('Greet!',array(
'submit' => 'message/goodbye')); ?>
Keep your view some thing like
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'aForm',
'htmlOptions' => array('onsubmit'=>"return false;"),
));
?>
<?php echo CHtml::textField('name', 'value'); ?>
<?php echo CHtml::submitButton('Greet!', array('onclick' => 'getValue()'));?>
<?php $this->endWidget(); ?>
And the Action Script for the onclick event is
<script type="text/javascript">
function getValue()
{
$text=$("#aForm").find('input[name="name"]').val();
alert($text);
//$formData=$("#aForm").serialize();
}
</script>
UNDERSTANDING THE BASIC CONCEPT
You have to remember that Yii is an MVC framework ( Model, View Controller ) and the best practice is to keep the entire structure like so. The best way to learn it is from the awesome forum that they have.
Hence, to define a scenario where you would like to save a data/textbox from the form, you would be following the following workflow :
A BASIC WORKFLOW
Assuming that you don't want to save the data in the Database. :
I would be assuming that a basic knowledge of the how the framework works is known. You can check out the guide and the other tutorials if not.
This is a basic workflow in which the data would be taken from the form and validated in the model.
Create a model file in your protected/models folder
Example : Lets name this file as FormData.php
<?php
class FormData extends CFormModel{
public $name;
public $email;
public function rules()
{
return array(
array('name , email','required'), // This rule would make it compulsory for the data to be added.
array('email','email'), // This will check if the email matches the email criteria.
);
}
public function attributeLabels()
{
return array(
'name' => 'Enter your name',
'email' => 'Enter your email',
);
}
}
?>
2. After this , in your protected/FormController.php
Add this :
<?php
class Formdata extends CController{
public function actionCoolForm()
{
$model = new FormData();
if(isset($_POST['FormData'])){
$model->attributes = $_POST['FormData'];
if($model->validate()){
// Do whatever you want to do here.
}
}
$this->render('someview',array('model'=>$model));
}
}
?>
3. Now to add the form in your page is easy :
<?php echo CHtml::form('formdata/coolform','post'); ?>
<?php
echo CHtml::activeTextField($model,'name');
echo CHtml::activeTextField($model,'email');
?>
<?php echo CHtml::endForm(); ?>
Now to add it in the database
The best and the easiest method of adding it in the database is to use the Gii.
But the code is nearly identical, except that the model extends CModel.
I hope that I was able to help.
I have a view (_form.php) with fields (name,summary) submit button. If I click on submit button, it should update Name field of One model and Summary field of another model.Both this models are of different databases.
Can anyone help on this. I tried the following for this
In _form.php(Test)
<?php echo $form->labelEx($model, ‘name’); ?>
<?php echo $form->textField($model, ‘name’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error($model, ‘name’); ?>
<?php echo $form->labelEx(Test1::model(), ‘summary’); ?>
<?php echo $form->textField(Test1::model(), ‘summary’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error(Test1::model(), ‘summary’); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? ‘Create’ : ‘Save’); ?>
In TestController.php
public function actionCreate() {
$model = new Test;
if (isset($_POST['Test'])) {
$model->attributes = $_POST['Test'];
if ($model->save()) {
$modeltest1 = new Test1;
$modeltest1->attributes = $_POST['Test1'];
$modeltest1->Id = $model->Id;
if ($modeltest1->save())
$this->redirect(array('view', 'Id' => $model->Id));
}
}
$this->render('create', array(
'model' => $model,
));
}
This code is not working. How can I make it work for different databases. I followed the below link for this.
http://www.yiiframework.com/wiki/291/update-two-models-with-one-view/
This code actually should work, but its bad.
I assume that you dont understand at all what is model and what its doing in Yii, also how to render and create forms.
I'll try to explain how it should be.
1st of all dont use Test::model() in views, unless you want to call some function from it(but try to avoid it). It can be done by passing it from controller:
public function actionCreate() {
$model_name = new Name;
$model_summary=new Summary;
//something here
$this->render('create', array(
'name' => $model_name,
'summary'=>$model_summary,
));
}
When you make render you passing variables to your view (name_in_view=>$variable)
2nd. In your view you can use your variables.
<?php echo $form->labelEx($name, ‘name’);
echo $form->textField($name, ‘name’, array(‘size’ => 60, ‘maxlength’ => 250));
echo $form->error($name, ‘name’);
echo $form->labelEx($summary, ‘summary’);
echo $form->textField($summary, ‘summary’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
echo $form->error($summary, ‘summary’); ?>
echo CHtml::submitButton($model->isNewRecord ? ‘Create’ : ‘Save’); ?>
3rd. You need to understand what is model. It's class that extends CActiveRecord in this case. Your code in controller should loo like:
public function actionCreate() {
$model_name = new Name;
$model_summary=new Summary;
if (isset($_POST['Name']))
$model_name->attributes=$_POST['Name'];
if (isset($_POST['Summary']))
$model_name->attributes=$_POST['Summary'];
if ($model_name->save()&&$model_summary->save())
$this->redirect(array('view', 'Id' => $model->Id));
$this->render('create', array(
'name' => $model_name,
'summary'=>$model_summary,
));
}
$model->attributes=$_POST[] here is mass assignment of attributes, so they must be safe in rules. You always can assign attributes with your hands (1 by 1), or form an array and push it from array.