cakephp saving data into database - php

i am new in cake php.I want to insert form data into database.But could not inserted.please help
controller:
officetypesController.php
<?php
class OfficetypesController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->Officetype->create();
if ($this->Officetype->save($this->request->data)) {
$this->Session->setFlash(__('The data has been saved'));
}
$this->Session->setFlash(
__('The data could not be saved. Please, try again.')
);
}
}
}
?>
view
add.ctp
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php echo $this->Form->input('name');
//echo $this->Form->input('password');
echo $this->Form->input('under', array(
'options' => array('1' => 'HO', '2' => 'RO')
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
model
officetype.php
<?php
class Officetype extends AppModel {
}
database:
table name :officetypes ,
fields name :id,name,under
when i click submit button than showing the message "The data could not be saved. Please, try again."

public function add() {
if ($this->request->is('post')) {
$this->Officetype->create();
if ($this->Officetype->save($this->request->data)) {
$this->Session->setFlash(__('The data has been saved'));
} else {
$this->Session->setFlash(__('The data could not be saved. Please, try again.'));
}
}
}
Check the database to see if the records are added.
Why is the form related to users if you want to add office types?
<div class="office_type form">
<?php echo $this->Form->create('Officetype'); ?>
<fieldset>
<legend><?php echo __('Add Office type'); ?></legend>
<?php echo $this->Form->input('name');
echo $this->Form->input('under', array(
'options' => array('1' => 'HO', '2' => 'RO')
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>

Related

Display data from database using codeigniter

Hi im new to codeigniter and i stuck in displaying data from database. I have tried to find solution but yet can't understand them properly. So can anyone help me with this? really need your expert suggestions thankyou!!
View file Userinsert_view.php
<html>
<head>
<title>Insert Data Into Database Using CodeIgniter Form</title>
</head>
<body>
<div id="container">
<?php echo form_open('Userinsert_controller'); ?>
<h1>Insert Data Into Database Using CodeIgniter</h1><hr/>
<?php if (isset($message)) { ?>
<CENTER><h3 style="color:green;">Data inserted successfully</h3></CENTER><br>
<?php } ?>
<?php echo form_label('Student Name :'); ?> <?php echo form_error('dname'); ?><br />
<?php echo form_input(array('id' => 'dname', 'name' => 'dname')); ?><br />
<?php echo form_label('Student Email :'); ?> <?php echo form_error('demail'); ?><br />
<?php echo form_input(array('id' => 'demail', 'name' => 'demail')); ?><br />
<?php echo form_label('Student Mobile No. :'); ?> <?php echo form_error('dmobile'); ?><br />
<?php echo form_input(array('id' => 'dmobile', 'name' => 'dmobile', 'placeholder' => '10 Digit Mobile No.')); ?><br />
<?php echo form_label('Student Address :'); ?> <?php echo form_error('daddress'); ?><br />
<?php echo form_input(array('id' => 'daddress', 'name' => 'daddress')); ?><br />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?><br/>
<div id="fugo">
</div>
</div>
</body>
</html>
Controller file
Userinsert_controller.php
<?php
class Userinsert_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('Userinsert_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('dname', 'Username', 'required|min_length[5]|max_length[15]');
//Validating Email Field
$this->form_validation->set_rules('demail', 'Email', 'required|valid_email');
//Validating Mobile no. Field
$this->form_validation->set_rules('dmobile', 'Mobile No.', 'required|regex_match[/^[0-9]{10}$/]');
//Validating Address Field
$this->form_validation->set_rules('daddress', 'Address', 'required|min_length[10]|max_length[50]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('Userinsert_view');
} else {
//Setting values for tabel columns
$data = array(
'Student_Name' => $this->input->post('dname'),
'Student_Email' => $this->input->post('demail'),
'Student_Mobile' => $this->input->post('dmobile'),
'Student_Address' => $this->input->post('daddress')
);
//Transfering data to Model
$this->Userinsert_model->form_insert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('Userinsert_view', $data);
}
}
Model file
Userinsert_model.php
<?php
class Userinsert_model extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert($data){
// Inserting in Table(students) of Database(college)
$this->db->insert('students', $data);
}
}
?>
in controller function
public function GetAll(){
$data['all_data'] = $this->Userinsert_model->selectAllData();
$this->load->view('view_page', $data);
}
in model
public function selectAllData() {
$query = $this->db->get('students');
return $query->result();
}
in view
<?php
foreach ($all_data as $show):
?>
<tr>
<td><?php echo $show->your_table_column_name?></td>
</tr>
<?php
endforeach;
?>
i have read your question you didn't write write the code for fetching data. you only submitted it in you database.
here is simple example so you can easily finds out the solution
in your controller file:
public function view()
{
$this->load->model('uModel'); //edit it with you model name
$data['users']= $this->uModel->All();
$this->load->view('list' , $data);
}
in your model file:
//Func for getting all data of a table in a 'users' variable by using get method
public function All()
{
return $users = $this->db->get('users')->result_array();
}
and create a table view file in view folder where you can fetch your data
<tbody>
<?php if (!empty($users)) { foreach ($users as $user) { ?>
<tr>
<td> <?php echo $user['userid'] ?></td>
<td> <?php echo $user['name'] ?></td>
</tr>
<?php } }
?>
Hope it will help you

Adding a Child in Parent View CakePHP

I am trying to add a child in a parent view in CakePHP.
Meaning, I have a Lesson I want to add to a Course in the Course view.
I tried doing it via a simple form helper - adding a $course['Lesson']:
<div class="lessons form">
<?php echo $this->Form->create($course['Lesson']); ?>
<fieldset>
<legend><?php echo __('Add Lesson'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('description');
echo $this->Form->input('course_id', array(
'value'=>$course['Course']['id']
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
But that doesn't seem to do it.
Am I missing something in the Controller/Model?
let's think course controller
//course controller
public function add_lesson() {
if ($this->request->is('post')) {
$this->Lesson->create();
if ($this->Lesson->save($this->request->data)) {
$this->Session->setFlash(__('The Lesson has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The Lesson could not be saved. Please, try again.'));
}
}
$this->set('courses', $this->Course->find('list'));
}
//add_Lesson View
<?php echo $this->Form->create('Lesson', array('url' => array('controller'=>'courses', 'action'=>'add_lesson')) ); ?>
<fieldset>
<legend><?php echo __('Add Lesson'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('description');
echo $this->Form->input('course_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
If you want to use Course controller you can save your data like this:
$this->Course->Lesson->save($this->request->data);
in this case you will need to make sure after submitting your form your data is structure as below:
array(
'Course' => array(
'id' => 1
),
'Lesson' => array(
'name' => 'name'
'description' => 'balbalbala'
'course_id' => 1
),
);

DROPDOWN list input values not fetched

I get repeatedly the same error. dropdown data is not fetched from the form. I have my code here
this is my controller:ProductController
{<?php
class ProductController extends Controller
{
public function actionCreate()
{
$model=new CreateForm;
// collect user input data
if(isset($_POST['CreateForm']))
{
$model->attributes=$_POST['CreateForm'];
$model->setAttributes($_POST['CreateForm']);
// validate user input and redirect to the previous page if valid
if($model->validate())
{
$product=new Product;
$product->save();
}
else {
echo "Hi";
}
}
// display the login form
$this->render('create',array('model'=>$model));
}
}
?>}
My model:CreateForm
{<?php
class CreateForm extends CFormModel
{
public $product_name;
public $category_name;
public $description;
public function rules()
{
return array(
array('product_name, category_name, description', 'required'),
array('product_name', 'unique', 'className' => 'Product', 'attributeName' => 'product_name', 'message'=>'This product name is already in use'),
);
}
public function attributeLabels()
{
return array(
'product_name'=>'PRODUCT NAME',
'category_name'=>'CATEGORY',
'description'=>'DESCRIPTION'
);
}
}
?>
}
Category
{
<?php
class Category extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'category';
}
public function attributeLabels()
{
return array(
'category_id'=>'CATEGORY ID',
'category_name'=>'CATEGORY NAME',
);
}
}
?>}
MY view:create.php
{<?php
$this->pageTitle=Yii::app()->name . ' - Create';
$this->breadcrumbs=array(
'Create',
);
?>
<h1>CREATE</h1>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'create-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model,'product_name'); ?>
<?php echo $form->textField($model,'product_name'); ?>
<?php echo $form->error($model,'product_name'); ?>
</div>
<div class="row">
<?php
echo $form->labelEx($model,'category_name');
$records = Category::model()->findAll();
$list = CHtml::listData($records, 'category_id', 'category_name');
echo CHtml::DropDownList('category_name', null, $list, array('prompt'=>'select '));
echo $form->error($model,'category_name');
?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?></br>
<?php echo $form->textArea($model,'description',array('style' => 'height:100px;width:500px;','maxlength'=>500)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('CREATE'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
}
if I enter all the fields, again it gives an error stating "PLS enter the category"
What you have done is called massive assignment
$model->attributes=$_POST['CreateForm'];
this would not assign all the values and is not safe in handling datas also
the datas would be saved only if they are in safe in the model
you will redeclare the posted data as
$model->attributes=$_POST['CreateForm'];
$model->dropdownname=$_POST['CreateForm']['dropdownname'];
Hope this will help you
http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/#hh2
I think you change your code of dropdown.
<?php
echo $form->labelEx($model,'category_name');
$records = Category::model()->findAll();
$list = CHtml::listData($records, 'category_id', 'category_name');
echo CHtml::DropDownList('category_name', null, $list, array('prompt'=>'select '));
echo $form->error($model,'category_name');
?>
To
<?php
echo $form->labelEx($model,'category_name');
$records = Category::model()->findAll();
$result = array();
foreach($records as $p) {
$result[p->category_id] = p->category_name ;
}
echo CHtml::activeDropDownList($model, 'category_name', $result);
echo $form->error($model,'category_name');
?>
Now you need to check, either your category id or name is coming or not.
Then you debug your controller file, as in given below.
public function actionCreate()
{
$model=new CreateForm;
// collect user input data
if(isset($_POST['CreateForm']))
{
$model->attributes=$_POST['CreateForm'];
echo $model->category_id ;
exit ; // Finish program here, and drop down will be printed.
$model->setAttributes($_POST['CreateForm']);
// validate user input and redirect to the previous page if valid
if($model->validate())
{
$product=new Product;
$product->save();
}
else {
echo "Hi";
}
} // display the login form
$this->render('create',array('model'=>$model));
}
Hope it help you.
Thanks

CakePHP Find Condition Breaking Submit

When using the conditions paramater of find, the user id doesn't submit along with the other fields.
public function add() {
if ($this->request->is('post')) {
$this->Thing->create();
if ($this->Thing->save($this->request->data)) {
$this->Session->setFlash(__('The Thing has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The Thing could not be saved. Please, try again.'));
}
}
$users = $this->Thing->User->find('list', array(
'fields' => array('User.username'),
'conditions' => array('User.ownedby' => '3')
));
$this->set(compact('users'));}
Here is my view:
<div class="things form">
<?php echo $this->Form->create('Thing'); ?>
<fieldset>
<legend><?php echo __('Add Thing'); ?></legend>
<?php
echo $this->Form->input('user_id');
?>
<div id="user-info">
</div>
</fieldset>
<?php echo $this->Form->end(__('Submit'
)); ?>
</div>
However, when I omit the condition parameter, it submits just fine. Any ideas? In case you were wondering, I'm using the conditions parameter to sort the list of users that results in the select dropdown this creates.
Thanks.

Cakephp multiple drop down list with view

I'm trying to get drop down list in Cake for below two finds by list:
function add() {
if (!empty($this->data)) {
$this->User->create();
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('The User has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
}
$group = $this->User->Group->find('list');
$commune = $this->User->Commune->find('list');
$this->compact('group','commune');
}
}
The model already has belongsTo defined in User model for Group and Commune models with their ids but I cannot seem to get group and commune to show up as drop down list in the add view page.
Below is what I have for add view page.
<div class="Users form">
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php __('Add User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('group_id', array('type' => 'select'));
echo $this->Form->input('commune_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Users', true), array('action' => 'index'));?></li>
</ul>
</div>
Is there a reason why it's not working?
you need to use plurals in order to automatically load those options into the form fields.
$groups, $communes
Try this in the view:
$this->Form->input('Group');
Alternatively:
$this->Form->input('group_id', array('type' => 'select', 'options' => $group));
You're setting $group and $commune but the view is looking for $group_id and $commune_id.

Categories