codeIgniter update data based on search - php

Based on search a form wiill be displayed with data based on search . I want to update this data with a button on the search result page. the update doesn't work and when I use var dump null values are returned
please help me out
view:
<h3> Allowances: </h3>
<div class='panel panel-info'>
<div class='panel panel-heading'></div>
<?php foreach ($allowance as $data): ?>
<div class="form-group">
<?php echo form_label( $data->name); ?>
<?php echo form_input(['class' => 'form-control', 'name' => 'amount','value' => $data->amount]); ?>
<?php echo form_hidden(['class' => 'form-control', 'name' => 'emp','value' => $data->emp_id]); ?>
<?php echo form_hidden(['class' => 'form-control', 'name' => 'comp','value' => $data->comp_id]); ?>
</div>
<?php endforeach; ?>
</div>
<a href='<?php echo base_url('payroll/update') ?>' class="btn btn-primary" type='submit'> Update</a>
COntroller
public function update(){
$emp_id = $this->input->get('emp');
$comp_id =$this->input->get('comp');
$d = [
'amount' =>$this->input->post('amount')
];
$this->payroll_model->update($d,$emp_id,$comp_id);
var_dump($d);
$this->session->set_flashdata('success','Successfully updated');
}
model
public function update($d,$emp_id,$comp_id){
// $array = array('emp_id'=>$emp_id,'comp_id' =>$comp_id);
// $this->db->where($array);
$this->db->where('emp_id',$emp_id);
$this->db->where('comp_id',$comp_id);
$this->db->update('emp_sal',$d);
return true;
enter code here
enter code here
enter code here

The reason why you are getting null values returned is that the line below redirects to the link in href instead of posting user's inputs
<a href='<?php echo base_url('payroll/update') ?>' class="btn btn-primary" type='submit'> Update</a>
To overcome this issue, use a form tag with action attribute that has the value of
base_url('payroll/update')
Such as the following
<?php echo form_open(base_url('payroll/update'), array('method'=>'post')) ; ?>
Replace the a tags you are using with the following input that submits user values instead of just redirecting with null values
<input class="btn btn-primary" type='submit'> Update</input>

Related

Layout of a simple PHP form needs altering

I'm trying to create a simple inline form that displays an entry field followed by a submit button - how can I alter this existing code so that these elements display horizontally in one row? ...I've tried altering the form class but no success. Thank you in advance.
PHP
<div class="d3-mailchimp" data-block-id="<?php echo $bID; ?>">
<?php
if (isset($errors)) {
$errors->output();
}
if (isset($message)) {
echo '<p class="message">'.$message.'</p>';
} else {
?>
<form method="post" action="<?php echo $this->action('submit') ?>" onsubmit="d3_mailchimp_submit(this); return false;">
<?php $token->output('d3_mailchimp.subscribe'); ?>
<div class="form-group field">
<?php
echo $form->email('email_address', '', [
'required' => 'required',
'placeholder' => t(''),
]);
?>
</div>
<?php
if ($showTermsCheckbox) {
?>
<div class="accept-terms">
<label for="accept_terms">
<?php
echo $form->checkbox('accept_terms', 1, 0, [
'required' => 'required',
]);
?>
<?php echo $acceptTermsText; ?>
</label>
</div>
<?php
}
?>
<div class="submit-button">
<?php
echo $form->submit('submit', t('Subscribe'), [
'class' => 'button',
]);
?>
</div>
</form>
<?php
}
?>

Change method for form generator in Codeigniter

I'm using form generator for form create form in Codeigniter.
This form now using POST method, I want to change to Get method.
<div class="col-md-10">
<?php echo $form->open(); ?>
<?php echo $form->messages(); ?>
<?php echo $form->bs3_text('Insert Name', 'name'); ?>
<div class="col-md-10" >
<p><?php echo $form->bs3_submit('submit', 'btn btn-primary '); ?></p>
</div>
<?php echo $form->close(); ?>
</div>
Where to change method in this generator?
use below associative array and pass it to form_open()
$attributes = array('class' => 'client', 'id' => 'myform', 'method' => 'get');
echo form_open('client/feedback', $attributes);
output
<form accept-charset="utf-8" action="http:/example.com/index.php/client/feedback" class="client" id="myform" method="get" />
use
<?php echo $form->open('your_url','method="get"'); ?>

Yii2 like button via AJAX and mysql table 400 error bad request

I reached this state: i made a table ->
| likes |
| like_id(primary key) | user_id(foreign key) | comment_id(foreign key) |
On clicking the like link my code is supposed to add a row in the likes table
and refresh the <div id="like_"<?php $comment['comment_id'] ?>> which is holding
the likes count. And this should happen via ajax. I am not familiar with AJAX so please give me advice. Am i on the right way?
my actionFeedback:
public function actionFeedback($comment_id)
{
if(\Yii::$app->request->isAjax)
{
$user_id = \Yii::$app->user->identity->id;
\Yii::$app->db->createCommand("INSERT INTO likes(user_id, comment_id)
VALUES ($user_id, $comment_id)")->execute();
$likes = \Yii::$app->db->createCommand("SELECT COUNT(*)
FROM likes
WHERE comment_id=$comment_id")->queryScalar();
return $likes;
}
}
and my view comments.php:
<?php
use yii\helpers\Html;
use app\models\BlogUser;
use app\controllers\PostController;
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<?php foreach ($comments as $comment): ?>
<div class='col-md-3 post-prof-img'>
<?php
$currUser = BlogUser::find()->where(['id' => $comment['author_id']])->one();
$commentID = $comment['comment_id'];
$likes = \Yii::$app->db->createCommand("SELECT COUNT(*)
FROM likes
WHERE comment_id=$commentID")->queryScalar();
?>
<?= Html::img('../images/' . $currUser->image, ['class' => 'tall img-circle']) ?>
<p class="text-center title-par">
<em><strong><?= $currUser->username ?></strong></em>
</p>
</div>
<div class='col-md-9 col-md-offset-1'>
<div class='post-comment'>
<p><em><?= $comment['comment_content'] ?></em></p>
</div>
<div class='comment-options'>
<div class='col-md-8'>
<?php
if(\Yii::$app->user->identity->id == $comment['author_id'] || PostController::isAdmin())
{
echo Html::a('Edit',['update-comment', 'id' => $comment['comment_id']]);
echo Html::a('Delete',
['delete-comment', 'id' => $comment['comment_id']],
['data' => [
'confirm' => 'Are you sure?',
'method' => 'POST'
]
]);
}
echo Html::a('Like',[''],['class' => 'like_up', 'data_id' => $comment['comment_id']]);
echo Html::a('Dislike');
?>
</div>
<div class='col-md-4 text-right'>
<div class="ajax-helper">
<span class='glyphicon glyphicon-hand-up' style="color:green"></span>
<span id="likes-"<?php $comment['comment_id'] ?>><?= $likes ?></span>
<span class='glyphicon glyphicon-hand-down' style="color:red"></span>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
<?php
$this->registerJs("
$('.like_up').on('click', function(event){
event.preventDefault();
var id = $(this).attr('data_id');
$.ajax({
url : '".\yii\helpers\Url::to(['feedback'])."?id='+id,
cache : false,
success : function( data ){
$('#likes-'+id).html( data );
}
});
});
");
?>
<div>
<?= Html::a('Add Comment', ['create-comment', 'id' => $_GET['id']],['class' => 'btn btn-primary add-comment', 'style'=>'margin-top: 2%']) ?>
</div>
</div>
</div>
</div>
With this lines of code i am getting an error :
GET http://letsblog/post/feedback?id=25&_=1491990823748 400 (Bad Request)
From what i found on google the problem is in my ajax part but do not know how to solve it :/
Thank you in advance!
url : '".\yii\helpers\Url::to(['feedback'])."?comment_id='+id, replace url for ajax request section like this.

how to get value from previous view in Yii

I'm not sure how to describe my question. First I added a button at my CCGridview:
array(
'class'=>'CButtonColumn',
'template' => '{view}{update}{delete}{upload_image}',
'buttons' => array(
'upload_image' => array(
'label' => 'upload foto',
'url' => 'Yii::app()->createUrl("/image/create",
array("product_id" => $data->product_id))',
),
),
),
when I clicked it will bring me to the /image/create view which has a product_id value. For example on that gridview I clicked record number 7, so the url would be:
(webApp)/index.php/image/create?product_id=7
Since it rendering a partial _form so the form has the attribute according to the image table which has this attributes: id, title, filename, product_id.
So the view will be something like:
<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'filename'); ?>
<?php echo $form->fileField($model,'filename',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'filename'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'product_id'); ?>
<?php echo $form->textField($model,'product_id'); ?>
<?php echo $form->error($model,'product_id'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
My question is, how do we use the value from the url which I mentioned before is 7 (../create?product_id=7) into the product_id attribute without have to type it at provided textField?
In other word I will remove this from the view:
<div class="row">
<?php echo $form->labelEx($model,'product_id'); ?>
<?php echo $form->textField($model,'product_id'); ?>
<?php echo $form->error($model,'product_id'); ?>
</div>
But when i submitted, the form the value (7) should have been passed/saved at product_id field.
Added:
My controller actionCreate is
//...
public function actionCreate()
{
$dir = Yii::app()->basePath . '/../productimages/';
$uploaded = false;
$model=new Image();
if(isset($_POST['Image']))
{
$model->attributes=$_POST['Image'];
$tempSave=CUploadedFile::getInstance($model,'filename');
if($model->validate())
{
$uploaded = $tempSave->saveAs($dir.'/'.$tempSave->getName());
$this->redirect(array('/products/index'));
}
}
$this->render('index', array(
'model' => $model,
'uploaded' => $uploaded,
'dir' => $dir,
));
}
That's it. Many thanks..
modify your controller this way:
if(isset($_POST['Image']))
{
$model->attributes=$_POST['Image'];
$tempSave=CUploadedFile::getInstance($model,'filename');
if($model->validate())
{
$uploaded = $tempSave->saveAs($dir.'/'.$tempSave->getName());
$this->redirect(array('/products/index'));
}
} else {
//initialize defaults
$model->product_id=intval($_GET['product_id']);
}

Auto complete fields of a previous values

I am doing a small application in Yii Framework for that my database is something like this
=== Invoices ===
id (PK)
customer_id
invoice_title
order_no
invoice_issue_date
due_date
description
=== Customers ===
id (PK)
email_address
customer_name
address
city
state
postal_code
description
I have rendered the Customer model in Invoice model so that I can enter all the values for both models in a single Invoice form.But there is one problem,let us assume that I have a customer name xyz which I had saved before.Now when I am going to again fill the Customer name with xyz,it should show all the fields of both models like invoice_title,order_no,invoice_issue_date,due_date,description,email_address,customer_name,address etc. in that input fields of the form so that I don't have to re-enter all the fields again.So how this can be achive in Yii framework.Any help and suggestions will be highly appreciable.More clarification on codes that I have done can be shared if needed.
Please help me out.I am totally stuck here.
To do this as everyone has already mentioned you need ajax, and some javascript. The logic is something like this:
When a value is selected in the dropdown for customer name, trigger an ajax call to retrieve the information about that user. This can be easily done with the ajax option, which is available as an additional htmlOption for some html element helpers in CHtml, as part of clientChange.
echo $form->dropDownList($model,'customer_name',CHtml::listData(Customers::model()->findAll(),'id','customer_name'),
array(// htmlOptions
'ajax'=>array(// special htmlOption through clientChange, for ajax
'type'=>'GET',
'url'=>$this->createUrl('controllername/customerdetails'),// action that will generate the data
'data'=>'js:"id="+$(this).val()',// this is the data that we are sending to the action in the controller
'dataType'=>'json',// type of data we expect back from the server
'success'=>'js:updateFields'// a javascript function that will execute when the request completes successfully
)
)
);
The documentation for the above options for ajax can be seen in jquery's ajax documentation.
Then in the server side find the particular customer, and send a response to the browser. Example:
// in the controllername code an action that will return the values as json
public function actionCustomerdetails($id){
$var=Customers::model()->findByPk($id);
echo CJSON::encode($var);
}
When you receive the server response populate the respective fields. This can be done in the success function callback for ajax, in the above code it was updateFields:
Yii::app()->clientScript->registerScript('update','
function updateFields(data, textStatus, jqXHR){
// select each input field by id, and update its value
$("#Customers_postal_code").val(data.postal_code);
$("#Customers_city").val(data.city);
$("#Customers_address").val(data.address);
// similarly update the fields for the other inputs
}
');
Notes:
Your customer can have many invoices, so the question will be which invoice to select given a customer name. That's something you'll have to handle, i think my answer has enough code to get you going.
To know the input field ids, you can simply check the generated html.
You could do this in two stages, so that:
When the view is initially displayed, the customer is asked for their email address or customer_name.
The Controller Action that the form is submitted to then retrieves data from the Customer model for the submitted email address or customer_name (I'll use email_address in my example below). Once retrieved, you can display your Single Invoice Form View with the data pre-populated for the customer if available.
This concept could then be implemented as follows:
<?php
// file: controllers/InvoiceController.php
class InvoiceController extends CController
{
// ... other controller functions
public function actionCreate($step = null)
{
$invoice = new Invoice;
$customer = new Customer;
# Form has been submitted:
if ( isset($_POST['Customer']) )
{
# The submitted form was Step 1:
if ( $step == 1 )
{
# make sure the submitted email address is valid
$customer->setAttributes($_POST['Customer']);
if ( $customer->validate(array('email_address')) )
{
# retrieve the customer by email_address
$customer = Customer::model()->findByAttributes(array('email_address' => $_POST['Customer']['email_address']));
}
$this->render('createstep2', array('invoice' => $invoice, 'customer' => $customer));
}
# The submitted form was Step 2:
elseif ( $step == 2 )
{
$income->setAttributes($_POST['Invoice']);
$customer->setAttributes($_POST['Customer']);
# save the data
if ( $customer->save() )
{
$invoice->customer_id = $customer->id;
if ( $invoice->save() )
{
$this->redirect(array('view', 'id' => $invoice->id));
}
}
# display any errors
$this->render('createstep2', array('invoice' => $invoice, 'customer' => $customer));
}
}
$this->render('createstep1', array('invoice' => $invoice, 'customer' => $customer));
}
// ... other controller functions
}
?>
You could split that to two separate Controller Actions if you wish.
For Step 1 View, you could then have the following:
<!-- file: views/invoice/createstep1.php -->
<h1>Create Invoice: Step 1</h1>
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'invoice-form',
'enableAjaxValidation'=>false,
'action'=>array('invoice/create','step' => 1)
));
?>
<?php echo $form->errorSummary($customer); ?>
<div class="row">
<?php echo $form->labelEx($customer,'email_address'); ?>
<?php echo $form->textField($customer,'email_address', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'email_address'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Next'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Step 2 view, you could then look like what you already have. Maybe something like:
<!-- file: views/invoice/createstep2.php -->
<h1>Create Invoice: Step 2</h1>
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'invoice-form',
'enableAjaxValidation'=>false,
'action'=>array('invoice/create','step' => 2)
));
?>
<?php echo $form->errorSummary($invoce); ?>
<?php echo $form->errorSummary($customer); ?>
<h2>Customer Details</h2>
<div class="row">
<?php echo $form->labelEx($customer,'email_address'); ?>
<?php echo $form->textField($customer,'email_address', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'email_address'); ?>
</div>
<!-- If the customer already exists, these field should be pre-populated: -->
<div class="row">
<?php echo $form->labelEx($customer,'customer_name'); ?>
<?php echo $form->textField($customer,'customer_name', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'customer_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'address'); ?>
<?php echo $form->textField($customer,'address', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'city'); ?>
<?php echo $form->textField($customer,'city', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'city'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'state'); ?>
<?php echo $form->textField($customer,'state', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'state'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'postal_code'); ?>
<?php echo $form->textField($customer,'postal_code', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'postal_code'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'description'); ?>
<?php echo $form->textField($customer,'description', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'description'); ?>
</div>
<h2>Order Details</h2>
<div class="row">
<?php echo $form->labelEx($invoice,'invoice_title'); ?>
<?php echo $form->textField($invoice,'invoice_title', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($invoice,'invoice_title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'order_no'); ?>
<?php echo $form->textField($invoice,'order_no', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($invoice,'order_no'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'invoice_issue_date'); ?>
<?php $form->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $invoice,
'attribute' => 'invoice_issue_date',
'value' => $invoice->invoice_issue_date,
'options' => array(
'showButtonPanel' => false,
'changeYear' => true,
'dateFormat' => 'yy-mm-dd',
),
)); ?>
<?php echo $form->error($invoice,'invoice_issue_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'due_date'); ?>
<?php $form->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $invoice,
'attribute' => 'due_date',
'value' => $invoice->due_date,
'options' => array(
'showButtonPanel' => false,
'changeYear' => true,
'dateFormat' => 'yy-mm-dd',
),
)); ?>
<?php echo $form->error($invoice,'due_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'description'); ?>
<?php echo $form->textField($invoice,'description', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($invoice,'description'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Create'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Have you checked the Yii Autocomplete widget? And you wouldn't have to worry about AJAX implementation. It does it for you.
Yii Framework: CJui AutoComplete
A more customized autocomplete solution in this link.
Yii Framework: custom-autocomplete-display-and-value-submission

Categories