I am making a CRUD application with Codeignater 3.
I have an "Add Customers" form with First name, Last name, Email address, City and a submit button.
The model looks like this:
class Customer extends CI_Model {
public function saveCustomer($data) {
$tbl = $this->db->dbprefix('customers');
$this->db->insert($tbl, $data);
}
}
The controller:
if ($this->form_validation->run()) {
$data = $this->input->post();
$this->load->model('Customer');
if ($this->Customer->saveCustomer($data)) {
$this->session->set_flashdata('response','Customer successfully added');
} else {
$this->session->set_flashdata('response','Failed to save customer');
}
return redirect('home');
}
The View file:
<?php echo form_open('home/save'); ?>
<div class="form-group <?php if(form_error('first_name')) echo 'has-error';?>">
<?php echo form_input('first_name', '', [
'type' => 'text',
'id' => 'first_name',
'class' => 'form-control',
'value' => '',
'placeholder' => 'First name',
]);
?>
<?php echo form_error('first_name'); ?>
</div>
<div class="form-group <?php if(form_error('last_name')) echo 'has-error';?>">
<?php echo form_input('last_name', '', [
'type' => 'text',
'id' => 'last_name',
'class' => 'form-control',
'value' => '',
'placeholder' => 'Last name',
]);
?>
<?php echo form_error('last_name'); ?>
</div>
<div class="form-group <?php if(form_error('email')) echo 'has-error';?>">
<?php echo form_input('email', '', [
'type' => 'text',
'id' => 'email',
'class' => 'form-control',
'value' => '',
'placeholder' => 'Email address',
]);
?>
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<?php echo form_input('phone', '', [
'type' => 'text',
'id' => 'phone',
'class' => 'form-control',
'value' => '',
'placeholder' => 'Phone number',
]);
?>
</div>
<div class="form-group">
<?php echo form_input('city', '', [
'type' => 'text',
'id' => 'city',
'class' => 'form-control',
'value' => '',
'placeholder' => 'City',
]);
?>
</div>
<div class="form-group">
<?php echo form_input('address', '', [
'type' => 'text',
'id' => 'address',
'class' => 'form-control',
'value' => '',
'placeholder' => 'Address',
]);
?>
</div>
<div class="form-group">
<?php echo form_submit('submit', 'Save', 'class = "btn btn-primary btn-block"'); ?>
</div>
<?php echo form_close(); ?>
The problem:
When I submit the form I get this error: Unknown column 'submit' in 'field list'
Why is that?
Change your $data as follows:
$data = array('column_name1' => $this->input->post('first_name'),
'column_name2' => $this->input->post('last_name'),
'column_name3' => $this->input->post('email'),
'column_name4' => $this->input->post('phone'),
'column_name5' => $this->input->post('city'),
'column_name6' => $this->input->post('address'));
NOTE: There is no need of return in controller, only redirect('home') is needed.
Small change in controller
if ($this->form_validation->run()) {
$data = $this->input->post();
//unset your submit value which are come from submit btn
if(isset($data['submit'])){unset($data['submit'])}
if(isset($data->submit)){unset($data->submit)}
$this->load->model('Customer');
if ($this->Customer->saveCustomer($data)) {
$this->session->set_flashdata('response','Customer successfully added');
} else {
$this->session->set_flashdata('response','Failed to save customer');
}
return redirect('home');
}
Related
I have a form like follow
<?php widgets\Pjax::begin(['id' => 'authors', 'enablePushState' => false]) ?>
<?php $form = ActiveForm::begin(['id' => $model->formName(),'enableAjaxValidation'=>true,'validationUrl'=>\yii\helpers\Url::toRoute(['paper-author/validation']), 'options' => ['data-pjax' => '']]); ?>
<?php echo $form->field($model, 'FirstName')->textInput()->input('string', ['placeholder' => Yii::t('app', ' FirstName...')])->label(false) ?>
<?php echo $form->field($model, 'LastName')->textInput()->input('string', ['placeholder' => Yii::t('app', ' LastName...')])->label(false) ?>
<?= Html::submitButton('Save', ['class' => 'btn btn-success', 'id' => 'btn1']) ?>
$widget = Yii::createObject([
'class' => 'yii\grid\GridView',
'dataProvider' => $dataprovider,
'columns' => [
'FirstName',
'LastName',
[
'class' => 'yii\grid\ActionColumn',
]
],
]
);
echo $widget->run();
<?php $form = ActiveForm::end(); ?>
<?php widgets\Pjax::end() ?>
and in my model I have some rules:
[['FirstName', 'LastName'],'required']
my controller:
public function actionValidation()
{
$model = new PaperAuthor();
$requestPost = Yii::$app->request->post();
if (Yii::$app->request->isAjax && $model->load($requestPost)) {
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
}
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
echo Json::encode([
'success' => true,
'messages' => [
Yii::t('app', 'Successfully Deleted.')
],
]);
}
actionCreate works well. but I can't delete any recored from gridview, it throws an validation error(required validation).
what can I do?
thanks in advance.
I am working on a CakePHP 3 project which is having a Apply Coupon form.
I want to apply the coupon using Ajax.
The view of coupon form is
<?= $this->Form->create(null, [
'url' => ['controller' => 'Coupons', 'action' => 'checkCoupon'],
'name' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
'type' => 'text',
'placeholder' => 'Apply Coupon Code',
'label' => false
]) ?>
<?= $this->Form->submit('Apply Coupon') ?>
and the checkCoupon action in CouponsController is
public function checkCoupon()
{
$this->request->onlyAllow('ajax'); // No direct access via browser URL
if ($this->request->is('post')) {
$couponCode = $this->request->data['coupon_code'];
$couponCheck = $this->Coupons->find('all', [
'conditions' => [
'coupon_code' => $couponCode
]
]);
if ($couponCheck->count() === 1) {
$coupon = $couponCheck->first();
$valid_till = $coupon->valid_till;
$dt = new Time($valid_till);
$date = $dt->format('Y-m-d');
if ($date >= date('Y-m-d')) {
echo 'Coupon is Valid. Discount of '.$coupon->value.'has been applied';
} else {
echo 'Coupon is Expired';
}
} else {
echo 'This is not a valid coupon code';
}
}
}
I want the $coupon->value and $coupon->id to be retrieved and added to the checkout link as
<?= $this->Html->link(__('Confirm Checkout'), ['controller' => 'ServiceRequests', 'action' => 'confirmCheckout', $service->id, $primaryAddressId, $serviceArea->id, $coupon->id], ['class' => 'btn btn-block btn-success']) ?>
The Apply Coupon form is in checkout action of RequestsController
Also the form is working well. I have checked it by removing the onlyAllow('ajax') line and printing values in check_coupon.ctp view.
How could I do it using Ajax ?
Edit 2 : checkout.ctp
<div class="form-info coupon">
<?= $this->Form->create(null, [
'url' => ['controller' => 'Coupons', 'action' => 'ajax_checkCoupon'],
'name' => 'checkCoupon',
'id' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
'type' => 'text',
'placeholder' => 'Apply Coupon Code',
'label' => false
]) ?>
<label class="hvr-sweep-to-right">
<?= $this->Form->submit('Apply Coupon', ['id' => 'applyCoupon']) ?>
</label>
<label id="couponUpdate"></label>
<label id="loading" style="display:none;">Loading...</label>
<?php
$data = $this->Html->script('#checkCoupon')->serializeForm(['isForm' => true, 'inline' => true]);
$this->Html->script('#checkCoupon')->event(
'submit',
$this->Html->script(
[
'controller' => 'Coupons',
'action' => 'ajax_checkCoupon'
],
[
'update' => '#couponUpdate',
'data' => $data,
'async' => true,
'dataExpression' => true,
'before' => "$('#loading').fadeIn();$('#applyCoupon').attr('disabled','disabled');",
'complete' => "$('#loading').fadeOut();$('#applyCoupon').removeAttr('disabled');"
]
)
);
?>
</div>
Error : Call to a member function serializeForm() on string on line 18 in checkout.ctp
I tried to submit a form using ajax. Below is my code:
controller code:
public function actionIndex($complaint, $work)
{
...
$this->render('index',array(
'model' => $model,
'work_order' => $work_order,
'work' => $work,
'complaint' => $complaint,
'work_complaint'=> $work_complaint
));
}
ajax action
public function actionCreate($complaint,$work)
{
...
$this->renderPartial('create',array(
'model' => $model,
'complaint' => $complaint,
'work' => $work,
'work_complaint' => $work_complaint,
'work_order' => $work_order,
'man_hour' => $man_hour,
'jobs' => $jobs,
));
}
my views
Create.php
<h1>Add Job</h1>
<?php $this->renderPartial('_form', array('model' => $model,
'work_complaint' => $work_complaint,
'work_order' => $work_order,
'man_hour' => $man_hour,
'jobs' => $jobs,
'complaint' => $complaint,
'work' => $work
)); ?>
my _form.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'post-form',
'enableAjaxValidation'=>false,
)); ?>
...
<div class="row buttons">
<div class="col-md-6 col-lg-6" >
<?php echo CHtml::ajaxSubmitButton ("Post",
array('complaintJob/create','complaint'=>$complaint,'work'=>$work),
array('update' => '#post')); ?>
</div>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
my index.php
<div id="post">
<?php
$man_hour = ManHourMaster::model()->findByPk(1);
$jobs = Job::model()->with('job_category1')->findAll( "job_category1.is_separate = 0" );
$this->renderPartial('create',array(
'model' => $model,
'complaint' => $complaint,
'work' => $work,
'work_complaint' => $work_complaint,
'work_order' => $work_order,
'man_hour' => $man_hour,
'jobs' => $jobs,
));
?>
</div>
...
so when i run this code i get the form, and when i submit it, i basically get 2 copies of the same view.
i tried this one and it worked
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'complaint-job-form',
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'afterValidate'=>'js:function(form,data,hasError){
if(!hasError){
$.ajax({
"type":"POST",
"url":"'.CHtml::normalizeUrl(array('complaintJob/create','complaint'=>$complaint,'work'=>$work)).'",
"data":form.serialize(),
"success":function(data){
toastr.success("Saved successfully.", "Success");
$("#results").html(data);
$("#ComplaintJob_job_id").select2("val", "");
},
});
}
}'
),
)); ?>
So basically I have a view action in my users controller where the user can modify his information(username,first name, last name, email..) this form sends to another update action which does the saving stuff, problem is that when I submit the form and one or more fields don't meet the validation rules it doesn't show underneath each fields but the data doesn't save and
$this->User->validationErrors
outputs the errors.
my update action (accessed after submiting the form on view.ctp)
view.ctp:
<?php
echo $this->Form->create('User', array(
'inputDefaults' => array(
'div' => 'form-group',
'wrapInput' => false,
'class' => 'form-control'
),
'class' => 'well',
'url'=>array('controller'=>'users','action'=>'update'),
'id'=>'info-form'
));
?>
<fieldset>
<legend>Personal Information</legend>
<?php
echo $this->Form->input('id', array('value' => $userinfo['User']['id']));
echo $this->Form->input('User.username', array(
'label' => 'Username',
'value'=>$userinfo['User']['username']
));
?>
<td><?php echo $this->Form->error('username'); ?></td>
<?php
echo $this->Form->input('User.email', array(
'label' => 'E-mail',
'value'=>$userinfo['User']['email']
));
?>
<?php
echo $this->Form->input('User.fname', array(
'label' => 'First name',
'value'=>$userinfo['User']['fname']
));
?>
<?php
echo $this->Form->input('User.lname', array(
'label' => 'Last name',
'value'=>$userinfo['User']['lname']
));
?>
<?php
echo $this->Form->submit('Update', array(
'div' => 'form-group',
'class' => 'btn btn-success'
));
?>
</fieldset>
<?php echo $this->Form->end(); ?>
update function:
function update() {
$this->autoRender = false;
$this->User->set($this->request->data);
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Information updated Successfuly.'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-success'), 'success');
return $this->redirect('/users/view/' . $this->request->data['User']['id']);
} else {
// $errors = $this->User->validationErrors; var_dump($errors);die;
$this->Session->setFlash(__('An error occured'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-danger'), 'danger');
return $this->redirect('/users/view/' . $this->request->data['User']['id']);
}
} else {
$this->Session->setFlash(__('Request was not of POST type.'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-danger'), 'danger');
return $this->redirect('/users/index/');
}
It's because you're redirecting after - that will make it lose the validation warnings.
i'm truly getting crazy!
I made a gallery with Meiouploader and PHPThumb. All is working very nice.
My uploaded images saved in folder img/uploads/images and in my database too.
But in the field for showing the images I only see the alt-text. Not the images.
But when In check the HTML-Code, I see the correct path to my images. But I don't see it.
What wrong???
Please help!
OK, here is all my code:
I think the paths are correct, because in source code in my browser i can see the image - Tag. Here is my code for Image-Model:
class Image extends AppModel {
var $name = 'Image';
var $validate = array(
'gallery_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
//'img_file' => array(
//'notempty' => array(
//'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
//),
//),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'Gallery' => array(
'className' => 'Gallery',
'foreignKey' => 'gallery_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
var $actsAs = array(
'MeioUpload' => array(
'img_file' => array(
'dir' => 'img{DS}uploads{DS}images',
'create_directory' => false,
'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/png'),
'allowed_ext' => array('.jpg', '.jpeg', '.png'),
'zoomCrop' => true,
'thumbnails' => true ,
'thumbnailQuality' => 75,
'thumbnailDir' => 'thumb',
'removeOriginal' => true,
'thumbsizes' => array(
'normal' => array('width' => 400, 'height' => 300),
),
'default' => 'default.jpg'
)
)
);
}
Here is my code for the Images-Controller:
class ImagesController extends AppController {
var $name = 'Images';
function index() {
$this->Image->recursive = 0;
$this->set('images', $this->paginate());
}
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid image', true));
$this->redirect(array('action' => 'index'));
}
$this->set('image', $this->Image->read(null, $id));
}
function add() {
if (!empty($this->data)) {
$this->Image->create();
if ($this->Image->save($this->data)) {
$this->Session->setFlash(__('The image has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The image could not be saved. Please, try again.', true));
}
}
$galleries = $this->Image->Gallery->find('list');
$this->set(compact('galleries'));
}
function edit($id = null) {
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid image', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->Image->save($this->data)) {
$this->Session->setFlash(__('The image has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The image could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->Image->read(null, $id);
}
$galleries = $this->Image->Gallery->find('list');
$this->set(compact('galleries'));
}
function delete($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid id for image', true));
$this->redirect(array('action'=>'index'));
}
if ($this->Image->delete($id)) {
$this->Session->setFlash(__('Image deleted', true));
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Image was not deleted', true));
$this->redirect(array('action' => 'index'));
}
}
Here is my code for index.ctp - View:
<div class="images index">
<h2><?php __('Images');?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id');?></th>
<th><?php echo $this->Paginator->sort('gallery_id');?></th>
<th><?php echo $this->Paginator->sort('name');?></th>
<th><?php echo $this->Paginator->sort('img_file');?></th>
<th class="actions"><?php __('Actions');?></th>
</tr>
<?php
$i = 0;
foreach ($images as $image):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
<tr<?php echo $class;?>>
<td><?php echo $image['Image']['id']; ?> </td>
<td>
<?php echo $this->Html->link($image['Gallery']['name'], array('controller' => 'galleries', 'action' => 'view', $image['Gallery']['id'])); ?>
</td>
<td><?php echo $image['Image']['name']; ?> </td>
<!--<td><?php echo $image['Image']['img_file']; ?> </td>-->
<td><?php echo $html->image('uploads' . DS . 'images' . DS . $image['Image']['img_file'], array('alt' => 'Gallery Image', 'width' => '400')); ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View', true), array('action' => 'view', $image['Image']['id'])); ?>
<?php echo $this->Html->link(__('Edit', true), array('action' => 'edit', $image['Image']['id'])); ?>
<?php echo $this->Html->link(__('Delete', true), array('action' => 'delete', $image['Image']['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $image['Image']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%', true)
));
?>
</p>
<div class="paging">
<?php echo $this->Paginator->prev('<< ' . __('previous', true), array(), null, array('class'=>'disabled'));?>
<?php echo $this->Paginator->numbers();?>
<?php echo $this->Paginator->next(__('next', true) . ' >>', array(), null, array('class' => 'disabled'));?>
</div>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('New Image', true), array('action' => 'add')); ?></li>
<li><?php echo $this->Html->link(__('List Galleries', true), array('controller' => 'galleries', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Gallery', true), array('controller' => 'galleries', 'action' => 'add')); ?> </li>
</ul>
</div>
And here is my code for the add.ctp - View:
<div class="images form">
<?php // echo $this->Form->create('Image');?>
<?php echo $form->create('Image',array('type' => 'file')); ?>
<fieldset>
<legend><?php __('Add Image'); ?></legend>
<?php
echo $this->Form->input('gallery_id');
echo $this->Form->input('name');
//echo $this->Form->input('img_file');
echo $form->input('img_file', array('type' => 'file'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Images', true), array('action' => 'index'));?></li>
<li><?php echo $this->Html->link(__('List Galleries', true), array('controller' => 'galleries', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Gallery', true), array('controller' => 'galleries', 'action' => 'add')); ?> </li>
</ul>
</div>
I did all like in the tutorial of Jason Whydro, but it doesn't work well. It don't show me the pictures in this field, only the alt-text within and the width.
When I click on link to one of these images in my source code in my browser, then he says me: There is no object. The URL coudn't found on server!!
I hope it's enough for you to see whats going wrong. I don't see it. What did you mean with User Permission? How can I fix it, if this is the problem. I work with windows 8.
Greetings...
If your path is correctly it means that when you put this on your url bar at your browser , it shoud appears.
When it doesn't , could be a permission issue. Try to check your files permission to your http user.