I'm having a problem calling an action in a controller upon button click. So the controller is generated by Gii. All of its actions are the default ones generated by Gii, except for the actionCreate().
Here is the relevant code ::
class ProductsController extends Controller {
public function actionCreate() {
$model = new Products;
if (isset($_POST['params'])) {
// $model->attributes = $_POST['Products'];
//if ($model->save())
// $this->redirect(array('view', 'id' => $model->id));
echo 'Yes Working';
}
$this->render('create', array(
'model' => $model,
));
}
As its clear from the above code snippet this action is calling the view named create.php.
Here is create.php::
<div class="page">
<div class="container">
<div class="row">
<h2>Create Products</h2>
<?php echo $this->renderPartial('_form', array('model' => $model)); ?>
</div>
</div>
And here is the partially rendered form.
<?php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id' => 'products-form',
'action' => Yii::app()->createUrl('products/create'),
'enableAjaxValidation' => false,
));
?>
<div class="form-actions">
<?php
echo CHtml::submitButton('Create', array(
'submit' => 'EasyAesthetics/index.php/products/create',
'params' => '1'
));
?>
</div>
<?php $this->endWidget(); ?>
Now what I want is that upon clicking the button 'Create', it would call the actionCreate() method in the ProductsController. Right now the button is working and I'm being redirected to /demoProject/index.php/products/create, but the echo 'Yes Working' is not displaying.
Can anyone please show me how to achieve this. How can i invoke the create action again with just a button and just a 1 in the $_POST array.
I need to do this so that on clicking create the actionCreate() method will call the relevant components to create the necessary products.
if your "var_dump()"ed your "$_POST" , you would see sensorario answer.
and also you can set your froms send method to post if still not sending post.
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id' => 'products-form',
'action' => Yii::app()->createUrl('products/create'),
'enableAjaxValidation' => false,
'method' => 'post',
));
?>
or get your parameter like this(this sets by $_REQUEST):
$param = Yii::app()->request->getParam('Products' , null);
Take a look at the code generated by your form. When you have model called "Hello" with a field called "world", your form field will be
<input type="text" name="Hello[world]">
Try to change your action in this way:
class ProductsController extends Controller {
public function actionCreate() {
$model = new Products;
if (isset($_POST['Products'])) {
echo 'Yes Working';
}
$this->render('create', array(
'model' => $model,
));
}
}
Pay particular attention to these two lines:
$model = new Products;
if (isset($_POST['Products'])) {
Fields will takes the same name of model. In case of more models:
<input type="text" name="Model1[field1]">
<input type="text" name="Model1[field2]">
<input type="text" name="Model21[field2]">
<input type="text" name="Model2[field2]">
and so on ...
Related
my view.php
<?php
echo
Html::beginForm(['contactpersons/update'], 'post',['id' => 'update-form']) .
'<input type="hidden" name="id" value="'.$model->id.'">
<a href="javascript:{}" onclick="document.getElementById(\'update-form\').submit();
return false;">Update</a>'.
Html::endForm();
?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
])
?>
my controller is
public function actionView($id)
{
$model = $this->findModel($id);
return $this->render('view', ['model' => $model]);
}
How to modify this for getting my view page without id value in the url.
Thanks in advance.
You could change it like this
public function actionView($id = null) {
$model = null;
if ($id !== null) {
$model = $this->findModel($id);
}
return $this->render('view', ['model' => $model]);
}
However in your view you execute the following code: $model->id
this won't work when the model isn't set yo anything. So you could create a new model ($model = new ModelClass()) when the $id is null.
Sidenote: this doesn't look like an view action but more like an edit action, so maybe change your action to actionEdit().
You can send data to your browser by two methods - POST and GET. So, if you want to hide id parameter, then you need to send your id as POST parameter, which is bad solution - it's hard to implement, because POST is usally sends when you submit a form.
I'm trying to update a record of a database.
Here is the code:
On my index page.
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div class="main">
<?php echo $news_item['text'] ?>
</div>
<p>View article</p>
<p>Delete article</p>
<p>Update article</p>
On my update.php page.
<h2>Update a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Update news item" />
</form>
On my news.php page.
public function update($slug)
{
$this->load->helper('url');
$this->news_model->update_news($slug);
redirect ('news', 'refresh');
}
On my news_model.php page.
public function update_news($slug)
{
$this->load->helper('url');
$data = array(
'title' => $title,
'slug' => $slug,
'text' => $this->input->post('text')
);
$this->db->where('title', $slug);
$this->db->update('news', $data);
}
My routing page.
$route['news/update/(:any)'] = 'news/update/$1';
$route['news/delete/(:any)'] = 'news/delete/$1';
$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
I'm trying to update the record the user clicks on.
However, instead of sending the slug to the update page, which has the form on to update the record, the code runs all the way through and updates the record to "0" values.
EDIT:
After a few comments, I can now see your problem. This is how I would fix it;
Your index file seems fine. It's your update function, within your controller where the problem lies. You're expecting to see the update form, but you're not actually loading the view;
Try replace the function, with this one;
public function update($slug)
{
if (!$this->input->post('submit'))
{
// The form was NOT posted
// So we load the view
$data['selected_article'] = $this->news_model->get_by_slug($slug);
$this->load->view('update', $data);
}
else
{
// The form was submitted
$data = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text'),
);
$this->news_model->update_news($slug, $data);
}
}
Shouldn't this:
$data = array(
'title' => $title,
'slug' => $slug,
'text' => $this->input->post('text')
);
be this:
$data = array(
'title' => $this->input->post('title'), //-->post variable
'slug' => $slug,
'text' => $this->input->post('text')
);
Also, are you sure that the $title variable is exactly the same as $slug?
If $title= 'My title', and $slug= 'my-title', they won't match and this won't run as expected:
$this->db->where('title', $slug);
I added a function in my form model file, there I just want to update some of the records that previously have been uploaded in a db:
public function update_records($id_aUsar){
$data = array(
'asunto' => $this->input->post('tema'),
'remite' => $this->input->post('emite'),
'mensaje' => $this->input->post('content'),
'dirigido' => $this->input->post('paraGrupo'),
'fechaEnvio'=> $this->input->post('fechaEnvio'),
'observaciones' => $this->input->post('notas')
);
$this->db->where('id_masivos', $id_aUsar);
$this->db->set('fecha', 'NOW()', FALSE);
$this->db->update('masivos_texto', $data);
}
where $id_aUsar is the primary key id of the row I want to update, I get the id from my session value, in order to keep the same session (my primary key id_masivos is type AUTOINCREMENT), the array entries are the only data to be updated after the user updates some of the fields (all of then including), but only those I show in the function are essential to the records update. Then in my controller I access my model added fuction like this:
$this->forma_model->update_records($id_tarea);
where $id_tarea is the current session id for that user in that session, that´s how I update records without losing the primary key id.
Don't know, if it is a typical problem, but can't figure how to realise it.
3 tables:
Application. It's relations:
return array(
'company_info' => array(self::HAS_ONE, 'AppCompany', 'applicant_id'),
'region'=>array(
self::HAS_ONE,'AppRegion',array('company_region_id'=>'id'),
'through'=>'company_info'
),
'sector'=>array(
self::HAS_ONE,'AppSector',array('company_sector_id'=>'id'),
'through'=>'company_info'
),
);
AppCompany. Relations:
return array(
'application' => array(self::BELONGS_TO, 'Application', 'applicant_id'),
'region' => array(self::BELONGS_TO, 'AppRegion', 'company_region_id'),
'sector' => array(self::BELONGS_TO, 'AppSector', 'company_sector_id'),
'goodsservices' => array(self::HAS_MANY, 'AppGoodsServices', 'company_id')
);
App.GoodsServices. Relations:
return array(
'company'=>array(self::BELONGS_TO, 'AppCompany', 'company_id'),
);
So, one user adds info about his company (company_name, date_of_registration etc), and than add some goods/services that this company produces. How to COLLECT, UPDATE AND VIEW all this information in one form? Is it possible?
How do I see this:
User addes some info and meets the field: "Goods and services and their percentage" and two fields - "GOODS AND SERVICES" and "PERCENTAGE" and ADD MORE button and he has 6 goods that he wants to add. So, he clicks on ADD MORE button and each time the new fields below appear. But the goods limit is 5, so the button becomes inactive after 5 fields have info.
And after SUBMIT button, all this info records to its table. It can be taken from table on UPDATE button and can be viewd in one CDetailView.
Please, how it can be implemented at least in general terms. Thank you
UPDATE
Ok, some work is done (don't know if it right, but...):
I used this extension: http://www.yiiframework.com/extension/esaverelatedbehavior/
Now I have:
public function actionCreate()
{
$model=new Application;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Application']))
{
$model->attributes=$_POST['Application'];
if(isset($_POST['AppGoodsServices']))
{
$model->goodsservices = $_POST['AppGoodsServices'];
}
if ($model->saveWithRelated('goodsservices'))
{
$this->redirect(array('view', 'id' => $model->id));
} else {$model->addError('goodsservices', 'Error occured while saving goods/services.'); }
}
$this->render('create',array(
'model'=>$model,
));
}
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Application']))
{
$model->attributes=$_POST['Application'];
if(isset($_POST['AppGoodsServices']))
{
$model->goodsservices = $_POST['AppGoodsServices'];
}
if ($model->saveWithRelated('goodsservices'))
{
$this->redirect(array('view', 'id' => $model->id));
} else {$model->addError('goodsservices', 'Error occured while saving goods/services.'); }
}
$this->render('update',array(
'model'=>$model,
));
}
public function loadModel($id)
{
$model=Application::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
In my _form.php
<div id="goodsservices">
<?php
$index = 0;
foreach ($model->goodsservices as $id => $goods):
$this->renderPartial('goods/_form', array(
'model' => $goods,
'index' => $id,
));
$index++;
endforeach;
?>
</div>
and subform in goods/_form:
<div style="margin-bottom: 20px; width:100%; clear:left;" class="crow">
<div class="row" style="float: left;">
<?php echo CHtml::activeLabelEx($model, '['.$index.']goods_and_services'); ?>
<?php echo CHtml::activeTextField($model, '['.$index.']goods_and_services', array('size' => 30, 'maxlength' => 150)); ?>
<?php echo CHtml::error($model, '['.$index .']goods_and_services'); ?>
</div>
<div class="row" style="float: left;">
<?php echo CHtml::activeLabelEx($model, '['.$index .']percentage'); ?>
<?php echo CHtml::activeTextField($model, '['.$index.']percentage', array('size' => 5)); ?>
<?php echo CHtml::error($model, '['.$index.']percentage'); ?>
</div>
<div class="row" style="float: left;">
<?php echo CHtml::link('Delete', '#', array('onclick' => 'deleteGoods(this, '.$index.'); return false;'));
?>
</div>
</div>
<div style="clear: both;"></div>
<?php
Yii::app()->clientScript->registerScript('deleteGoods', "
function deleteGoods(elm, index)
{
element=$(elm).parent().parent();
/* animate div */
$(element).animate(
{
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 500,
function() {
/* remove div */
$(element).remove();
});
}", CClientScript::POS_END);
?>
Everything works, but I cant understand how to make a batch CREATE for children (goodsservices) model. Now it only shows me children in UPDATE form (I've made some records straight into DB) with DELETE button near each. But how to implement CREATE? So, one empty row should be visible and I could ADD other rows on click "Add row"?
It is possible. Using javascript you should create additional items in view, in controller action you are getting $_POST with all data, fill and validate all models in one transaction. In update action view you are showing related models with php foreach.
There is an example of code that can be useful for you. See comments also.
I am trying to insert record using Cakephp.My model name is something like User.php.
And My working controller name is SignupsController.I want to insert record using this two but I cant.I am give my some codes below :
View :
<?php echo $this->Form->create('Signups',array('action' => 'registration'));?>
<div class="row-fluid">
<div class="span5">
<label class="">*First Name</label>
<?php echo $this->Form->input('first_name', array('type' => 'text','label' => false, 'class' => 'input-xlarge validate[required]', 'div' => false)); ?>
</div>
<div class="span5">
<label class="">*Last Name</label>
<?php echo $this->Form->input('last_name', array('type' => 'text', 'label' => false, 'class' => 'input-xlarge validate[required]', 'div' => false)); ?>
</div>
</div>
<?php echo $this->Form->end(); ?>
My controller code is given below :
class SignupsController extends AppController {
var $name = 'Signups';
var $uses=array("User");
public function registration()
{
$this->layout="reserved";
$this->Club->create();
if (isset($_POST['registration'])) {
echo "This is";
echo "<pre>";print_r($this->request->data);echo"</pre>";
$this->User->save($this->request->data);
//$this->Session->setFlash(__('Promoter registration has been done successfully'));
//$this->redirect('registration');
//$this->redirect(array('action' => 'registration'));
}
}
}
My model name is different which's name is User.php
I want to insert the record using this above code.Any idea how to insert?
you can do this by loading the users model in current controller just write the following line
$this->loadModel('Name of the Model').
then
$this->nameofmodel->save()
As you are unable to understand see this
Controller::loadModel(string $modelClass, mixed $id)¶
The loadModel() function comes handy when you need to use a model which is not the controller’s default model or its associated model:
$this->loadModel('Article');
$recentArticles = $this->Article->find(
'all',
array('limit' => 5, 'order' => 'Article.created DESC')
);
$this->loadModel('User', 2);
$user = $this->User->read();
Above pasted code is taken from CookBook of Cakephp, if you still do not understand just read it it has complete detailed explanation you can also see this to understand
you can use it with $uses variable in SignupController
class SingupController extends AppController
{
public $uses = array('User');
//rest of stuff
}
Or, if you want, you can load it on-demand inside a method:
$this->loadModel('User'); //now model is loaded inside controller and used via $this->User
EDIT: Your data array has to include the name of the model you're saving. So, replace:
$this->Form->create('Signups',array('action' => 'registration')
with:
$this->Form->create('User',array('url' => array('controller' => 'signups', 'action' => 'registration'));
I have a view (_form.php) with fields (name,summary) submit button. If I click on submit button, it should update Name field of One model and Summary field of another model.Both this models are of different databases.
Can anyone help on this. I tried the following for this
In _form.php(Test)
<?php echo $form->labelEx($model, ‘name’); ?>
<?php echo $form->textField($model, ‘name’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error($model, ‘name’); ?>
<?php echo $form->labelEx(Test1::model(), ‘summary’); ?>
<?php echo $form->textField(Test1::model(), ‘summary’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error(Test1::model(), ‘summary’); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? ‘Create’ : ‘Save’); ?>
In TestController.php
public function actionCreate() {
$model = new Test;
if (isset($_POST['Test'])) {
$model->attributes = $_POST['Test'];
if ($model->save()) {
$modeltest1 = new Test1;
$modeltest1->attributes = $_POST['Test1'];
$modeltest1->Id = $model->Id;
if ($modeltest1->save())
$this->redirect(array('view', 'Id' => $model->Id));
}
}
$this->render('create', array(
'model' => $model,
));
}
This code is not working. How can I make it work for different databases. I followed the below link for this.
http://www.yiiframework.com/wiki/291/update-two-models-with-one-view/
This code actually should work, but its bad.
I assume that you dont understand at all what is model and what its doing in Yii, also how to render and create forms.
I'll try to explain how it should be.
1st of all dont use Test::model() in views, unless you want to call some function from it(but try to avoid it). It can be done by passing it from controller:
public function actionCreate() {
$model_name = new Name;
$model_summary=new Summary;
//something here
$this->render('create', array(
'name' => $model_name,
'summary'=>$model_summary,
));
}
When you make render you passing variables to your view (name_in_view=>$variable)
2nd. In your view you can use your variables.
<?php echo $form->labelEx($name, ‘name’);
echo $form->textField($name, ‘name’, array(‘size’ => 60, ‘maxlength’ => 250));
echo $form->error($name, ‘name’);
echo $form->labelEx($summary, ‘summary’);
echo $form->textField($summary, ‘summary’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
echo $form->error($summary, ‘summary’); ?>
echo CHtml::submitButton($model->isNewRecord ? ‘Create’ : ‘Save’); ?>
3rd. You need to understand what is model. It's class that extends CActiveRecord in this case. Your code in controller should loo like:
public function actionCreate() {
$model_name = new Name;
$model_summary=new Summary;
if (isset($_POST['Name']))
$model_name->attributes=$_POST['Name'];
if (isset($_POST['Summary']))
$model_name->attributes=$_POST['Summary'];
if ($model_name->save()&&$model_summary->save())
$this->redirect(array('view', 'Id' => $model->Id));
$this->render('create', array(
'name' => $model_name,
'summary'=>$model_summary,
));
}
$model->attributes=$_POST[] here is mass assignment of attributes, so they must be safe in rules. You always can assign attributes with your hands (1 by 1), or form an array and push it from array.