I'm really new to CI and have been trying to create an update form class today, but I'm running into a dead end. I have my functions set up to create the form and publish the data to the database, I now need to be able to update this.
My edit form function is below:
public function edit_event()
{
$vars = array();
$data['form_url'] = $this->form_url;
if ($form_id = $this->EE->input->get('form_id'))
{
$data['form_id'] = $form_id;
}
return $this->EE->load->view('edit_event', $data, TRUE);
}
and the edit_event file loaded within the function is:
<?php
$this->EE=& get_instance();
$this->load->helper('form');
$attributes = array('class' => 'event_form', 'id' => 'my_event_form');
echo form_open($form_url.AMP.'method=update_form', $attributes);
$this->EE->load->library('table');
$this->EE->table->set_heading(
'Preference',
'Setting'
);
$query = $this->EE->db->query("SELECT * FROM exp_events WHERE id = '$form_id'");
foreach($query->result_array() as $row)
{
$this->EE->table->add_row(
form_label('Application Key', 'app_key'),
form_input('app_key',$row['app_key'])
);
$this->EE->table->add_row(
form_label('Access Token', 'access_token'),
form_input('access_token',$row['access_token'])
);
$this->EE->table->add_row(
form_label('User Key', 'user_key'),
form_input('user_key',$row['user_key'])
);
}
echo $this->EE->table->generate();
echo form_reset('reset', 'Clear Form');
echo form_submit('mysubmit', 'Submit Post!');
echo form_close();
?>
I then have my update form function:
public function update_form()
{
$form_id = $this->EE->input->get('form_id');
$data['form_id'] = $form_id;
$form_data = array(
'app_key' => $this->EE->input->post('app_key'),
'access_token' => $this->EE->input->post('access_token'),
'user_key' => $this->EE->input->post('user_key')
);
$this->EE->db->where('id', $form_id);
$this->EE->db->update('exp_events', $form_data);
$this->EE->functions->redirect($this->base_url);
}
When removing the $form_if option I can get the data to update, but it updates for every single item in the database. I obviously need this to only update the data with the form id of the form being edited.
As it stands, when I submit the update form, I get redirected to my $base_url which is correct, but no data gets updated, therefore I am clearly doing something wrong when defining the form id?
As I said I'm new to this, so if anyone notices any preferred methods feel free to let me know :).
Any pointers appreciated.
Thanks in advance.
Ben
You need to include a 'hidden' field in your form, with the form_id. At the moment your 'form_id' is not part of your input, so when you go and get the form_id it is failing.
change
echo $this->EE->table->generate();
echo form_reset('reset', 'Clear Form');
echo form_submit('mysubmit', 'Submit Post!');
to
echo $this->EE->table->generate();
echo form_hidden('form_id', $form_id);
echo form_reset('reset', 'Clear Form');
echo form_submit('mysubmit', 'Submit Post!');
Related
I have a url of a page as
http://localhost/projectname/admin/client/1
In the above url i have a form in which i need to fill details and save it in database. The form on this page is:
<?php
$data = array(
'type'=>'text',
'name'=>'job_title',
'value'=>'Job Title',
'class'=>'form-control');
?>
<?php echo form_input($data); ?>
<?php
$data = array(
'type'=>'submit',
'class'=>'btn',
'name'=>'submit',
'content'=>'Submit!'
);
echo form_button($data);
?>
<?php
echo form_close();
?>
On the submission of the page i wish to save it in a table but along with it i also wish to carry the id/value which is in url (in this case it is 1), and would like to carry it forward till model so that i can perform actions in database based on this id/value. Can anyone please tell how it can be done
Present code for controller
public function form()
{
$this->form_validation->set_rules('job_title','Full Name','trim|required|min_length[3]');
if($this->form_validation->run() == FALSE)
{
$regdata = array
(
'regerrors' => validation_errors()
);
$this->session->set_flashdata($regdata);
redirect('admin/clients');
}
else
{
if($this->user_model->job())
{
redirect ('admin/client');
}
}
}
Present code for model // In the users table i wish to add job title to that row where the id matches the value in url i.e 1
public function job()
{
$data = array(
'job_title' => $this->input->post('job_title')
);
$insert_data = $this->db->insert('users', $data);
return $insert_data;
}
Try some thing like this:
$clientId = $this->uri->segment('3'); // will return the third parameter of url
Now put this $clientId in form in a hidden input. Now you can get the $clientId on controller function when form submits. Pass it to model or use accordingly.
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 do not understand how a form submission work in yii.Help me please...
public function actionHome() {
$model = new LoginForm;
$form = new CForm('application.views.website.formV', $model);
//protected/views/website/formV.php.
if($form->submitted('login') && $form->validate()){
echo 'nig';
$this->redirect(array('website/send'));
}
else {
$this->render('login', array('form'=>$form));
}
echo '<h1>Hello</h1>';
echo '<div class="form">';
echo $form;
echo '</div>';
}
FormV.php
return array(
'title'=>'Label title',
'elements'=>array(
'username'=>array(
'type'=>'text',
'maxlength'=>32,
),
'<div class="djada"></div>'
,
/*
'password'=>array(
'type'=>'password',
'maxlength'=>10,
),
*
*/
'rememberMe'=>array(
'type'=>'checkbox',
)
),
'buttons'=>array(
'login'=>array(
'type'=>'submit',
'label'=>'Enter',
),
),
);
When I click validation good but not redirect to 'website/send' ...
Another question is why the model is transmitted to new CForm...Why such a method?
How to work with it?
If you check LoginForm class in models directory, you will find that it holds 2 public variables which are required. Required variables are username and password. Since you have commented out the password element in the form builder you will not pass the following if statement.
if($form->submitted('login') && $form->validate()){
Reason why you are redirected to new form is because it is coded that way. Once submitted() and validate() functions return true you will be redirected to website/send action instead of new login form.
Please read http://www.yiiframework.com/doc/guide/1.1/en/form.builder for more information about the CForm class.
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
value of FORM INPUT Help!!
//this is just a refrence of $nm and $fid from test_model//
$data['fid']['value'] = 0;
$data['nm'] = array('name'=>'fname',
'id'=>'id');
say i have one form_view with
<?=form_label('Insert Your Name :')?>
<?=form_input($nm)?>
and a function to get single row
function get($id){
$query = $this->db->getwhere('test',array('id'=>$id));
return $query->row_array();
}
then in controller.. index($id = 0)
and somewhere in index
if((int)$id > 0)
{
$q = $this->test_model->get($id);
$data['fid']['value'] = $q['id'];
$data['nm']['value'] = $q['name'];
}
and mysql table has something like 1. victor, 2. visible etc. as a name value
but here its not taking the value of name and id from form_input and not showing it again in form_view in same input box as victor etc so to update and post it back to database...
anyone please help!!
and please be easy as I am new to CI!!
Based on your comment to my first answer, here is a sample of a Controller, Model and View to update a user entry pulled from a table in a database.
Controller
class Users extends Controller
{
function Users()
{
parent::Controller();
}
function browse()
{
}
function edit($id)
{
// Fetch user by id
$user = $this->user_model->get_user($id);
// Form validation
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run())
{
// Update user
$user['name'] = $this->input->post('name', true);
$this->user_model->update_user($user);
// Redirect to some other page
redirect('users/browse');
}
else
{
// Load edit view
$this->load->view('users/edit', array('user' => $user));
}
}
}
Model
class User_model extends Model
{
function User_model()
{
parent::Model();
}
function get_user($user_id)
{
$sql = 'select * from users where user_id=?';
$query = $this->db->query($sql, array($user_id));
return $query->row();
}
function update_user($user)
{
$this->db->where(array('user_id' => $user['user_id']));
$this->db->update('users', $user);
}
}
View
<?php echo form_open('users/edit/' . $user['user_id']); ?>
<div>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo set_value('name', $user['name']); ?>" />
</div>
<div>
<input type="submit" value="Update" />
</div>
<?php echo form_close(); ?>
It's hard to see the problem from your snippets of code, please try and give a little more information as to the structure of your app and where these code samples are placed.
Presume in the last code listing ('somewhere in index') you are getting $id from the form, but you define the ID of the form input box as 'id' array('name'=>'fname','id'=>'id') rather than an integer value so maybe this is where the problem lies.
Where does the $data array get passed to in the third code listing?
From your question I think you want to display a form to edit a person record in the database.
Controller code
// Normally data object is retrieved from the database
// This is just to simplify the code
$person = array('id' => 1, 'name' => 'stephenc');
// Pass to the view
$this->load->view('my_view_name', array('person' => $person));
View code
<?php echo form_label('Your name: ', 'name'); ?>
<?php echo form_input(array('name' => 'name', 'value' => $person['name'])); ?>
Don't forget to echo what is returned from form_label and form_input. This could be where you are going wrong.