I have two CHtml::submitButton() in my form, namely "Accept" and "Reject". Each of the buttons has a specific ID ... When any of the two are pressed, i would like to trigger an action in my controller. Below are the code snippets.
=========================================================
View
<?php
echo CHtml::beginForm('mycontrollerName/AcceptUserRegistration','get');
?>
<?php echo CHtml::submitButton('Accept', array('id' => 'accept')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Reject', array('id' => 'reject')); ?>
<?php echo CHtml::endForm(); ?>
========================================================
Controller
public function actionAcceptUserRegistration() {
$value = $_GET['id'];
if($value == "accept"){
//will do something here
}
if($value == "reject"){
//will do something here.
}
}
======================================================================
When i implement it this way. the get value in the controller side is empty. What I'm I doing wrong? Or is there any other way around this?
You forgot to give the submit button a name (unless your framework does some magic which we cannot know about - you should really post the generated HTML code!).
If you do so, the value in $_GET['buttonname'] will be its value (not its id), i.e. Accept or Reject. This becomes pretty messy as soon as you get into i18n, so you might want to use different names for the buttons and then check isset($_GET['buttonname1']) and isset($_GET['buttonname2'])
Here is a code example for what you are trying to achive:
VIEW:
<?php
echo CHtml::beginForm('mycontrollerName/AcceptUserRegistration','get');
?>
<?php echo CHtml::submitButton('Accept', array('id' => 'accept', 'name' => 'accept')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Reject', array('id' => 'reject', 'name' => 'reject')); ?>
<?php echo CHtml::endForm(); ?>
Note: I added the name parameter. As name is not displayed to the user, you can use accept instead of Accept.
CONTROLLER:
public function actionAcceptUserRegistration() {
if(isset($_GET['accept'])) {
//accepted
} else if(isset($_GET['reject'])) {
//rejected
}
//I recommend using POST method instead of GET for posting the form.
}
Related
I have tried several solution posted in this forum and others as well but it has not helped so far. So I am posting my question finally. BTW, I am using CakePHP 3.6.
I am trying to pass a variable ($product->id) via submit button in view.ctp to my controller action "addit" but I just get "Undefined variable: id " (I have tried addit($id) and addit() either of case I have the same result.)
view.ctp
<p>
<?php echo $this->Form->create('NULL',['url'=>['controller'=>'products','action'=>'addit']]);?>
<?php echo $this->Form->input('id', ['type' => 'hidden', 'value' => $product->id]); ?>
<?php echo $this->Form->button('Add to cart now');?>
<?php echo $this->Form->end();?>
</p>
Controller:Products
public function addit() {
$this->autoRender = false;
if ($this->request->is('post')) {
// $this->Products->addProduct($this->request->data['Cart']['product_id']);
echo "".$this->Products->get($id);//for test
} else {
echo "".$this->Products->get($id);//for test
}
}
According to Cakephp 3.6
All POST data can be accessed using
Cake\Http\ServerRequest::getData(). Any form data that contains a data
prefix will have that data prefix removed. For example:
// An input with a name attribute equal to 'MyModel[title]' is accessible at
$title = $this->request->getData('MyModel.title');
You can get value of $id variable like this:
$id = $this->request->getData('id');
Further Reading: Request Body Data
Is this what you want to do?
$id = $this->request->getData('id');
debug($this->Products->get($id)); //for test
I'm totally new to Yii and I need help please even if it looks trivial. I have a page where I generate a table from my database, I added a search option and I need to generate the result as a table also.
The problem is that when I click the button nothing happens.
I also tried using submit but it didn't work.
This is my code:
...views/supermarkets/index.php:
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
use app\views\supermarkets\search;
?>
<h1>Supermarkets</h1>
<ul>
<p>
Search by Name
</p>
<INPUT TYPE = "Text" VALUE ="" NAME = "searchname">
<button onclick="myFunction($_POST['searchname'])">Search</button>
<h3> </h3>
<?php
$array = (array) $supermarkets;
function myFunction($sname){
if (isset($sname) && $sname!='') {
$row = Yii::app()->db->createCommand(array(
'select' => '*',
'from' => 'supermarkets',
'where' => array('like', 'Name','%'.$sname.'')
))->queryRow();
$array = (array) $row;
}
echo $array;
$this->render('index',array('supermarkets' => $array));
}
function build_table($array){
// start table
$html = '<table class="altrowstable" id="alternatecolor">';
// header row
$html .= '<tr>';
foreach($array[0] as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
echo build_table($array);
?>
<?= LinkPager::widget(['pagination' => $pagination]) ?>
Even in the debug it doesn't pass through myFunction. Any suggestions please?
You should follow proper Yii syntax, ie define your function inside controller and call that function by creating button on index.php or other view file like:
Button on view file:
<?= Html::a('Search', ['search-function', 'Name' => $this->$sname], ['class' => 'btn btn-success']) ?>
And in your controller:
//As you define your function
public function actionSearchFunction($sname){
if (isset($sname) && $sname!='') {
$row = Yii::app()->db->createCommand(array(
'select' => '*',
'from' => 'supermarkets',
'where' => array('like', 'Name','%'.$sname.'')
))->queryAll();
$array = (array) $row;
I will explain you step by step. First, Note that everything inside <?php ?> tag will be generate at the server BEFORE rendering of the view. So, you can't execute php code on the client. If you need to execute some server code from client, You need to use Ajax(asynchronous JavaScript and XML). I recommend you to learn ajax, because this is very useful in web applications. OK, let's solve your problem. First step is to define an event for button click. You have myFunction already and I change it to this:
<button onclick="myFunction();">Search</button>
And I change your input to this:
<input type="text" value ="" name="searchname", id="searchname">
Now, I write myFunction() body in the <script></script> tag:
<script>
function myFunction()
{
$.ajax({
url: '<?php echo Yii::app()->baseUrl . '/supermarkets/sample' ?>',
type: 'post',
data: {searchname: $("#searchname").val()},
success: function (data) {
alert(data);
}
});
}
</script>
Now, you need to define an action in your controller for ajax request. I supposed you have SupermarketsController. Try to write actionSample() in it like this:
public function actionSample()
{
$array = (array) $supermarkets;
$sname = $_POST['searchname'];
...
echo "ok";
}
You can access the search input value in that function and all of your php code must be there. at the last line of that action, you must echo something(data or message). Everything you put after echo, you can get it as data parameter of success event of ajax request. In my example, you will see "ok" alert in your browser. I hope my explanation can help you to learn ajax. Note you need to include jquery library for using ajax. Good luck friend :)
I'm trying to make dropDownList in _form view.
This is the Controller part
public function actionCreate()
{
$modelCountry = Country::model()->findAll();
$this->render('create',array(
'model'=>$model,'modelCountry'=>$modelCountry,
));
}
Now in _form view I have a TextField which must be modified to dropDownList
<div class="row">
<?php echo $form->labelEx($model,'name_en'); ?>
<?php echo $form->textField($model,'name_en',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'name_en'); ?>
</div>
That means I must modify it to something like this
<?php echo $form->dropDownList($model,'name_en',array('!Variable!A!From_modelCountry!','!Variable!B!From_modelCountry!' )); ?>
I can use foreach loop and inside that loop create some DropDownList but maybe there is some better way to take data out of an array $modelCountry and put them straight to array of that dropDownList?
yes you can do that. In your controller you can write
$list=CHtml::listData($modelCountry,'id','name_en');
$this->render('create',array(
'model'=>$model,'modelCountry'=>$modelCountry,'list'=>$list
));
Now in your View you can write
<?php echo $form->dropDownList($model,'name_en',$list); ?>
You can use Chmlt::listData in your view but that should be a part of controller, thats what MVC is all about.
<?php echo $form->dropDownList($model,'name_en',CHtml::listData(Country::model()->findAll(),'id','name')); ?>
i want to have a drop down list and a submit button, when the button pressed i want to get the text of selected item and store it into db. my drop down code in view is :
<?php
$form=$this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true
),
)); ?>
<?php echo $form->labelEx($model,'actTopic'); ?>
<?php echo $form->error($model,'actTopic'); ?>
<?php
echo CHtml::dropDownList('actTopic', $category,$list,
array('empty' => '... '));
?>
it generates a drop down list fine.
but i don't know how i can get the selected item in my action function.
the action function is:
public function actiongivePoint()
{
$model=new GivePointForm;
if(isset($_POST['GivePointForm'])){
$model->attributes=$_POST['GivePointForm'];
if($model->validate()){
$actTopic=($model->actTopic);
$actPoint=($model->actPoint);
$actId=($model->actId);
$stCode = (int) $_GET['stCode'];
$connection=Yii::app()->db;
$connection->active=TRUE;
$actIdReader =Yii::app()->db->createCommand()
->select ('actID')
->from('refrencepoint')
->where("actTopic=:actTopic")
->queryScalar(array(':actTopic'=>$actTopic));
$search =Yii::app()->db->createCommand()
->select ('count(*)')
->from('point')
->where(array('and', 'actId=:actID', 'stCode=:stCode') )
->queryScalar(array(':actId'=>$actId,':stCode'=>$stCode));
if($search !=0){
$month=CDateFormatter::formatMonth(now());
$year=CDateFormatter::formatMonth(now());
$command =$command->update('point', array(
'year'=>$year,'month'=>$month,
'pcounter'=>new CDbExpression('pcounter + 1'),),
(array('and','actId'=>$actId, 'stCode'=>$stCode))) ;
Yii::app()->user->setFlash('point','....');
}
else{
$month=CDateFormatter::formatMonth(now());
$year=CDateFormatter::formatMonth(now());
$command->insert('point', array('actId'=>$actId,
'stCode'=>$stCode,'year'=>$year,'month'=>$month,
'pcounter'=>new CDbExpression('pcounter + 1')));
Yii::app()->user->setFlash('point','....');
}
}
}
$this->render('givePoint',array('model'=>$model));
}
i should say i don't use active record.
with above codes it looks like everything is ok in view, but when i press submit button nothing happen, no change in db and even no error just the page refresh!!
what is wrong here?
i am so tired of trying....
I think you just use like it.
you first use foreach loop.I am not sure which type of things your are listing. but you need to do work like in below.
It is an example
foreach($model->category as $list) {
$list['id'] = $list->name;
}
echo CHtml::dropDownList($model, 'actTopic', $list);
Now you debug your code.
public function actiongivePoint()
{
$model=new GivePointForm;
if(isset($_POST['GivePointForm'])){
print_r($_POST['GivePointForm']);
exit; //Just check either the form is posted or not and values are coming or not.
$model->attributes=$_POST['GivePointForm'];
if($model->validate()){
$actTopic=($model->actTopic);
echo $actTopic ;
exit ; // Check either your dropdown item id is coming or not.
Hope its help you.
Thanks.
I cannot get the hidden value of form if it is hidden.
My form view:
<?php echo form_input(array(
'class'=>'emp_name',
'name'=>'emp_name',
'id'=>'emp_name',
'value'=>'')
);?>
<?php echo form_hidden('emp_id', ''); ?>
I set employee name by using jquery autocomplete and then set the emp_id value to the returned ID with the name.
My Controller:
$data = array(
'emp_id'=>$this->input->post('emp_id')
);
This conroller is the form of my view above. I can get the emp_name properly but not the emp_id because it is hidden, if I do not use hidden it works fine. Any idea how can I hide the ID by getting the value in my conntroler?
It looks like you are not submitting the form to the system.
You need to open/close and submit the form.
Quick little test:
class Test_form extends CI_Controller
{
function __construct()
{
parent::__construct();
//displays the profiler info to make debugging easy
$this->output->enable_profiler(TRUE);
}
function test_form()
{
echo form_open();
echo form_input(array(
'class'=>'emp_name',
'name'=>'emp_name',
'id'=>'emp_name',
'value'=>'')
);
echo form_hidden('emp_id', '');
echo form_submit();
echo form_close();
}
}