Using CodeIgniter, how do I access and display text entered into an input field on a view file (see code below) from my controller file?
// input_view.php
<?php
echo form_open('search/submit');
$input_data = array('name' => 'search_field', 'size' => '70');
echo form_input($input_data);
form_submit('submit','Submit');
form_close();
?>
When text is entered into an input field, it is impossible to access until the form has been posted back to the server. In other words, the form must be submit for your controller to see it.
Let's say you have a form in the file called input_view.php:
<?php echo form_open('my_controller/my_method'); ?>
<?php echo form_input('search'); ?>
<?php echo form_submit('submit', 'Search'); ?>
When this form is submit, it will be sent to the 'my_controller' controller.
Now, Here's what the my_method should look like if you want to simply print the contents of the search field:
public function my_method() {
if ($this->input->post()) {
$name = $this->input->post('search');
echo $name;
}
}
I hope this helps.
Related
I want to create a link on login form, that is by clinking "Signup" a user will be redirected to sign up form but when I create a link it does not work and come back after refreshing the page shortly.
My login page looks like this:-
v_login.php
<body>
<h1>Simple Login with CodeIgniter</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('c_verifylogin/index');
echo form_label("Username: ");
echo form_input("username");
echo "<br>";
echo form_label("Password: ");
echo form_password("password");
echo "<br>";
echo form_submit("","Login");
echo form_close();
?>
**<a href="<?php echo site_url('c_signup/mylink_to_signup')?> " >Signup</a>**
</body>
The controller for this login id:-
c_login.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_login extends CI_Controller {
function index() {
$this->load->helper(array('url','form','html'));
$this->load->view('v_login'); //load view for login
}
}
my signup controller is:-
c_signup.php
<?php
class c_signup extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->model('m_regt');
}
function mylink_to_signup(){
$this->load->view('v_signup');
}
function index()
{
// Including Validation Library
if ($this->form_validation->run() == TRUE)
{
$this->load->view('v_signup');
}
else
{
// Setting Values For Tabel Columns
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'email' => $this->input->post('email'),
'gender' => $this->input->post('gender'),
'profession' => $this->input->post('profession')
);
// Transfering Data To Model
$this->m_regt->form_insert($data);
// Loading View
//$this->load->view('v_login');
}
}
}
?>
and the Signup view is:-
v_signup.php
<div id="container">
//sign up form here
</div>
Check out URL helper in codeigniter which has an anchor function for creating anchor tags
The tag has three optional parameters:
anchor(uri segments, text, attributes)
The first parameter can contain any segments you wish appended to the URL. As with the site_url() function above, segments can be a string or an array.
Note: If you are building links that are internal to your application do not include the base URL This will be added automatically from the information specified in your config file. Include only the URI segments you wish appended to the URL.
The second segment is the text you would like the link to say. If you leave it blank, the URL will be used.
The third parameter can contain a list of attributes you would like added to the link. The attributes can be a simple string or an associative array.
Here are some examples:
echo anchor('news/local/123', 'My News', 'title="News title"');
Would produce: My News
echo anchor('news/local/123', 'My News', array('title' => 'The best news!'));
Would produce: My News
https://ellislab.com/codeigniter/user-guide/helpers/url_helper.html
you don't have any mylink_to_signup function in c_login controller so it will be
<a href="<?php echo site_url('c_signup/mylink_to_signup');?>" >Signup</a>
Please look there was a space on your url:
**<a href="<?php echo site_url('c_signup/mylink_to_signup')?> " >Signup</a>**
Try change it:
Signup
i found the problem. there was actually a helper link for query string enable/disable in cofig file .
$config['enable_query_strings'] = FALSE;
i changed this to TRUE that's why the links were not working.
Thanks all for your help.`
I want to post a checkbox to action and print alert if the checkbox is checked, here is my code:
view:
echo CHtml::checkBox('hi');
echo CHtml::button('Search', array('onclick' => 'js:document.location.href="index"'));
controller:
public function actionIndex()
{
$model = Jobs::model()->findAll();
$model2 = Tags::model()->findAll();
if(isset($_POST['hi']))
echo "<script>alert('hello');</script>";
$this->render('index', array('model'=>$model, 'model2'=>$model2));
}
when I check the checkbox and click the button nothing is happened, where is the error in my code?
You just redirect your page to actionIndex. You must SUBMIT your form instead of redirecting it. Take a look:
echo CHtml::beginForm(Yii::app()->createUrl('index'), 'POST');
echo CHtml::checkBox('hi');
echo CHtml::submitButton('Search');
echo CHtml::endForm();
If you try:
CVarDumper::dump($_POST,56789,true);
You can see the POST value after submitting the form.
Or you can do it via java-script in your button:
//if you have created a form
echo CHtml::button('Search', array('onclick' => 'this.submit();'));
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 website with few short News , to every News we can write a comment via Form. And there my problem occur.
When i fill my fields in one form, after pressing button, all forms are reloading without saving, and every field in every form must be filled out so they're treated like a one part how to avoid it ?
Additional info ( Info is my main modal with news, it's joined with Com modal)
index.ctp Form
<br><h5>Add comment:</h5><br>
<?php echo $this->Form->create('Com'); ?>
<?php echo $this->Form->input(__('mail',true),array('class'=>'form-control')); ?>
<?php echo $this->Form->input(__('body',true),array('class'=>'form-control')); ?>
<?php $this->request->data['ip'] = $this->request->clientIp(); ?>
<?php $this->request->data['info_id'] = $info['Info']['id']; ?>
<?php echo $this->Form->submit(__('Add comment',true),array('class'=>'btn btn-info')); ?>
<?php $this->Form->end(); ?>
controller ComsController.php
public function add()
{
if($this->request->is('post'))
{
$this->Infos_com->create();
$this->request->data['Infos_com']['ip'] = $this->request->clientIp();
$this->request->data['Infos_com']['id_infos'] = $number;
if($this->Infos_com->save($this->request->data))
{
$this->Session->setFlash(__('Comment is waiting for moderating',true),array('class'=>'alert alert-info'));
return $this->redirect(array('controller'=>'Infos','action'=>'index'));
}
$this->Session->setFlash(__('Niepowodzenie dodania komentarza',true),array('class'=>'alert alert-info'));
return TRUE;
}}
and Model Com.php, i comment lines to avoid neccesity of filling every field in forms
class Com extends AppModel
{
public $belongsTo = array('Info');
/*public $validate = array(
'mail'=>array(
'requierd'=>array(
'rule'=>array('notEmpty'),
'message'=>'Write your email'
)
),
'body'=>array(
'required'=>array(
'rule'=>array('notEmpty'),
'messages'=>'Write smth'
)
)
); */
}
I don't think you can access $this->request->data in a view (the data should be entered with a form, it was not submitted). You should use hidden fields to pass arguments like IP od id... Example:
echo $this->Form->input('Infos_com.client_id', array(
'type' => 'hidden',
'value' => $value
));
If you have multiple forms, it would be useful to separate their fields. For example:
echo $this->Form->input('Infos_com.' . $news_id . '.body', array('label' => __('body')));
This way you will get an array like:
$this->request->data['Infos_com'][$news_id]['body'].
And then you can make your logic in the model.
I have an edit page set up for editing blog posts. Here's the controller action...
public function edit($id = null) {
$post = $this->Post->findById($id);
if(!$post) {
throw new NotFoundException('Post not found');
}
if($this->request->is('post')) {
$this->Post->id = $id;
if($this->Post->save($this->request->data)) {
$this->Session->setFlash('Post updated!');
$this->redirect('/');
} else {
$this->Session->setFlash('Unable to update post!');
}
}
if (!$this->request->data) {
$this->request->data = $post;
}
$this->set('tags', $this->Post->Tag->find('list'));
$this->set('pageTitle', 'Edit blog post');
}
And the edit pages view...
<h1>Edit blog post</h1>
<?php echo $this->Form->create('Post'); ?>
<?php echo $this->Form->input('Post.title'); ?>
<?php echo $this->Form->input('Post.body'); ?>
<?php echo $this->Form->input('Tag.Tag', array('type' => 'text', 'label' => 'Tags (seperated by space)', 'value' => $tags)); ?>
<?php echo $this->Form->input('Post.slug'); ?>
<?php echo $this->Form->end('Save Changes'); ?>
For some reason when I make changes and click "save changes", the page just refreshes and although the changes are reflected in the form after the refresh, I have to click "save changes" again for them to get saved to the database and for Cake to redirect me to /.
What could be causing that?
Because there is no Post.id in your form, CakePHP sends a PUT request (instead of a POST request) to create (or "put") a new row into your database the first time. This doesn't pass your request check:
if($this->request->is('post'))
Now, at this point your logic gets the entire row for the corresponding post, with this code:
$this->request->data = $post;
This will include the ID of the given post, since it's in your find() result and hence the second time you submit it, it has an id and therefor sends a POST request instead of a PUT request.
Assuming you only want to edit existing posts, add an id field to your form (the FormHelper automagic should make a hidden field of it, but you can always explicitly tell it to, like in the example below):
echo $this->Form->input('Post.id', array('type' => 'hidden');
This should pass along the id and hence trigger a POST request rather than a PUT request and make your submission pass at once.