Update two models of different databases with single view in yii - php

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.

Related

Having Issues Invoking Actions Of Controller On Button Click

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 ...

Yii model not getting posted

I have this weird issue where the values seems to get posted on form submit but still there the controller seems to not find it. I am saving three models with a single form. Both the relations to the main model are HAS_MANY. Here's the controller.
$model=$this->loadModel($id);
$modelunitgroup = $model->userUnitgroups;
$modelunit = $model->userUnits;
if(isset($_POST['User'], $_POST['Userunitgroup'], $_POST['Userunit']))
{
$model->attributes=$_POST['User'];
$modelunit->attributes=$_POST['Userunitgroup'];
$modelunitgroup->attributes=$_POST['Userunit'];
$valid=$model->validate();
if($valid)
{
if($model->save(false))
{
$modelunitgroup->user_id = $model->id;
$modelunit->user_id = $model->id;
if ($modelunitgroup->save() && $modelunit->save())
{
Yii::app()->user->setFlash('success', "User updated!");
$this->redirect(array('view','id'=>$model->id));
}
}
}
}
$this->render('update',array(
'model'=>$model,
'modelunitgroup'=>$modelunitgroup,
'modelunit'=>$modelunit,
));
Here's the relations
'userUnitgroups' => array(self::HAS_MANY, 'Userunitgroup', 'user_id'),
'userUnits' => array(self::HAS_MANY, 'Userunit', 'user_id'),
And the form view
<?php echo $form->errorSummary($model); ?>
<?php echo $form->dropDownListRow($model, 'title', $model->getUtitle(),array('prompt' => 'Select ...'));?>
<?php echo $form->textFieldRow($model,'firstname',array('class'=>'span5','maxlength'=>60)); ?>
<?php echo $form->textFieldRow($model,'lastname',array('class'=>'span5','maxlength'=>60)); ?>
<?php echo $form->textFieldRow($model,'mobile',array('class'=>'span5')); ?>
<?php echo $form->textFieldRow($model,'email',array('class'=>'span5','maxlength'=>160)); ?>
<?php echo $form->passwordFieldRow($model,'password',array('class'=>'span5','maxlength'=>32)); ?>
<?php
foreach ($modelunitgroup as $mgroup) {
echo $form->dropDownListRow($mgroup,
'unitgroup',
$model->getUnitgroups(),
array(
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('user/getunit'),
'update'=>'#Userunit_unit',
)));
}
foreach ($modelunit as $munit) {
echo $form->dropDownListRow($munit,
'unit',
array()
);
}
?>
I keep getting the error "Attempt to assign property of non-object". It seems that the 'Userunitgroup' and 'Userunit' are never posted, which is weird cause I checked the header in Firefox and all the values are correctly being posted. Any help on what may be causing this and how to solve this?
$modelUnitGroup and $modelunit are arrays, yet you are assigning attributes like they are individual models (objects). For more information on how to do batch inserts/updates consult the manual.
I think you have a problem in your models rules in your scenario, in your model class:
public function rules() {
array('title ,name, country, ..., password', 'safe', 'on'=>'thisCustomeScenario'),
...
}
and try to var_dump($_POST) to see what exactly your getting

Yii dropdownlist using $form-> dropdownlist

i want to create a form from 2 different models,
1st is for countries, and the 2nd is for documents.
The problem is that i can't make a dropdown list, i get the errors all the time.
Here's the code, first my controller.php part
$model = new Country;
$model2 = new Product;
$this->performAjaxValidation(array($model, $model2));
if(isset($_POST['Country'],$_POST['Product']))
{
// populate input data to $model and $model2
$model->attributes=$_POST['Country'];
$model2->attributes=$_POST['Product'];
// validate BOTH $model and $model2
$valid=$model->validate();
$valid=$model2->validate() && $valid;
if($valid)
{
// use false parameter to disable validation
$model->save(false);
$model2->save(false);
$this->redirect('index');
}
}
...
$countriesIssued = Country::model()->findAll(array('select'=>'code, name', 'order'=>'name'));
...
$this->render('legalisation', array('model'=>$model, 'model2'=>$model2, 'documents'=>$documents, 'countriesIssued'=>$countriesIssued, 'countries'=>$countries, 'flag'=>$flag));
}
In my view script I use this code
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation'=>true,
)); ?>
<?php echo $form->errorSummary(array($model,$model2)); ?>
<?php echo $form->dropDownList($model, 'countriesIssued',
CHtml::listData($countriesIssued, 'code', 'name'));?>
<?php $this->endWidget(); ?>
but i get this error :
Property "Country.countriesIssued" is not defined.
Ok it's not defined, i try to change it to 'countriesIssued', then i got another error saying Invalid argument supplied for foreach() .
If anybody can help me please.
I know there is more solutions on net, i try it but not understand, Thanks.
By definition, the first param of listData is an array; Your is a object;
<?php
echo $form->dropDownList($model, 'classification_levels_id', CHtml::listData(ClassificationLevels::model()->findAll(), 'id', 'name'),$classification_levels_options);
?>
Make a list variable like this:
In your Model:
$countriesIssued = Country::model()->findAll(array('select'=>'code, name', 'order'=>'name'));
And in your view:
$list = CHtml::listData($countriesIssued, 'code', 'name'));
echo CHtml::dropDownList('Your variable', Your $model,
$list,
array('empty' => '(Select a category'));
dropDownList($model,'state',array('1' => 'Do 1', '2' => 'Do 2'),array('selected' => 'Choose')); ?>
Or Yii 2
field($model,'state')->dropDownList(
array('1' => 'Do 1','0' => 'Do 2'),array('options' => array('0' => array('selected' => true))))
->label('State')
?>

Yii Collect Data For Two Or More Models ( Get_Class() Expects Parameter 1 To Be Object, Array Given )

I get this error when I call CreateController : "get_class() expects parameter 1 to be object, array given "
Controll/actionCreate() is as follows:
public function actionCreate() {
$model = new Ogrenci;
$model2 =new Adresler;
$this->performAjaxValidation($model, 'ogrenci-form');
$this->performAjaxValidation($model2, 'ogrenci-form');
if (isset($_POST['Ogrenci'],$_POST['Adresler'])) {
$model->setAttributes($_POST['Ogrenci']);
$model2->setAttributes($_POST['Adresler']);
if ($model->save(false) && $model2->save(false)) {
if (Yii::app()->getRequest()->getIsAjaxRequest())
Yii::app()->end();
else
$this->redirect(array('view', 'id' => $model->ogrenci_id));
}
}
$this->render('create', array( 'model' => $model,'model2' => $model2));
}
create.php:
<?php $this->renderPartial('_form', array(
'model' => array('model'=>$model,'model2'=>$model2),
'buttons' => 'create'));
?>
And _form.php's fields is as follows:
<div class="row">
<?php echo $form->labelEx($model2,'aciklama'); ?>
<?php echo $form->textField($model2,'aciklama'); ?>
<?php echo $form->error($model2,'aciklama'); ?>
</div><!-- row -->
$this->renderPartial('_form', array(
'model' => array(
'model'=>$model,
'model2'=>$model2
),
'buttons' => 'create'
));
code above means that file _form.php will have access to two variables:
$model - array of two elements, and $buttons - string.
So, to get access to first model you have to write $model['model'], second - $model['model2'].
but in this code
<?php echo $form->labelEx($model2,'aciklama'); ?>
<?php echo $form->textField($model2,'aciklama'); ?>
<?php echo $form->error($model2,'aciklama'); ?>
You are trying to access undefined variable $model2. And this should raise respective error.
The thing that error is not got makes me thinking that somewhere before listed code you access variable $model in the similar way, something like this:
echo $form->labelEx($model,'test');
In the above code $model is array(because you passed array). That is why you receive error that object is expected.
So, you should either pass models or access them in a proper way.
I hope this helps.
I solved another problem.Perhaps someone may be in need..
(CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key)
if ($model->save(false) && $model2->save(false)) {
if (Yii::app()->getRequest()->getIsAjaxRequest())
Yii::app()->end();
else
$this->redirect(array('view', 'id' => $model->ogrenci_id));
}
to
$a=$model2->save(false);
$model->adresler_id=$model2->adresler_id;
if ($a && $model->save(false)) {
if (Yii::app()->getRequest()->getIsAjaxRequest())
Yii::app()->end();
else
$this->redirect(array('view', 'id' => $model->ogrenci_id));
}

connecting pages in codeigniter

i have a simple question i have a form where user enters his details and when the submit button is clicked whit his details submitted to database it will take the user to a different page i am using codeigniter and i am new to this is there an easy way to do this ? tnx for you help. here is my cmv:
controller
<?php
class Info extends CI_Controller{
function index(){
$this->load->view('info_view');
}
// insert data
function credentials()
{
$data = array(
'name' => $this->input->post('name'),
'second_name' => $this->input->post('second_name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
);
$this->info_model->add_record($data);
}
}
?>
model
<?php
class Info_model extends CI_Model {
function get_records()
{
$query = $this->db->get('credentials');
return $query->result();
}
function add_record($data)
{
$this->db->insert('credentials', $data);
return;
}
}
?>
view
<html>
<head>
</head>
<body>
<?php echo form_open('info/credentials'); ?>
<ul id="info">
<li>Name:<?php echo form_input('name')?></li>
<li>Second Name: <?php echo form_input('second_name');?></li>
<li>Phone: <?php echo form_input('phone');?></li>
<li>Email: <?php echo form_input('email');?></li>
<li><?php echo form_submit('submit', 'Start survay!!' );?></li>
</ul>
<?php echo form_close();?>
</body>
</html>
If all you need is a simple redirect upon submission of the form:
$this->info_model->add_record($data);
redirect('controller/method');
You could use the redirect() function from the URL Helper to actually redirect the user
(http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html)
Like this:
$this->load->helper('url');
redirect('/some/other/page');
Note that this has to be called before any data is outputted to the browser.
Another way of doing it is to simply have two different views that you load depending on the context. Normally you want some form validation as well so you can use that to direct the user. I usually end up with something like this in my function, which is used both for posting the data, inserting it to the database and "redirecting":
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required|trim|xss_clean');
/* More validation */
if ($this->form_validation->run() !== FALSE) {
$data = array(
'name' => $this->input->post('name'),
'second_name' => $this->input->post('second_name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
);
$this->info_model->add_record($data);
$this->load->view('some_other_view');
} else {
$this->load->view('info_view');
}
You can also use refresh as a second parameter:
$this->info_model->add_record($data);
redirect('controllerName/methodName','refresh');

Categories