Yii dropdownlist using $form-> dropdownlist - php

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')
?>

Related

Yii dropdown with AJAX not working as expected

I have the following view named 'findreseller.php':
<?php
$countries = CHtml::listData(Country::model()->findAll(), 'id', 'name');
echo CHtml::dropdownlist('find_reseller', '', $countries,
array('ajax'=>array(
'type'=>'POST',
'url'=>Yii::app()->getController()->createAbsoluteUrl('/webcare/reseller/loadAjaxData'),
'update' =>'#data',
)
)
);
?>
<div id="data">
<?php $this->renderPartial('_ajaxContent', array('dataProvider'=>$dataProvider))?>
</div>
_ajaxContent just echoes the result, nothing special there...
The dropdown, as you can see is generated with CHtml because I dont't need a form. I just need an onChange event to do something...
As per the code that follows, in '/webcare/reseller/loadAjaxData' I have:
public function actionLoadAjaxData() {
$country = $_POST['find_reseller'];
//do something...
$dataProvider=new CArrayDataProvider($country_reseller);
$this->render('findreseller', array('dataProvider' => $dataProvider));
}
I can tell that I am missing something, but I am not sure what exactly.
Edit
Modified like this:
<?php
//CHtml::form();
$countries = CHtml::listData(Country::model()->findAll(), 'id', 'name');
echo CHtml::dropdownlist('find_reseller', '', $countries,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('/webcare/reseller/loadAjaxData'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city_id', //selector to update
'data'=>'js: $(this).val()',
//leave out the data key to pass all form values through
)
)
);
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city_id','', array());
//CHtml::endForm();
?>
<div id="data">
<?php $this->renderPartial('_ajaxContent', array('dataProvider'=>$dataProvider))?>
</div>
And now I get:
http://prntscr.com/42wwx6
And I have the following controller action:
public function actionLoadAjaxData() {
$country = $_POST['country_id'];
...
$dataProvider=new CArrayDataProvider($country_reseller);
$data = User::model()->findAll('country_id=:country_id AND reseller=:reseller',
array(':country_id'=>(int) $_POST['country_id'], ':reseller'=>1));
$data=CHtml::listData($data,'city','city');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
$this->render('action_name', array('dataProvider' => $dataProvider));
}
Edit 2
If I write a die in actionLoadAjaxData(), right at the beginning, the method is loaded fine, the action is ok and the server answers 200.

Update two models of different databases with single view in yii

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.

Form made in Yii returns error, Property is not defined

I have controller EcommerceController.php
and it looks like this:
public function actionLegalisation()
{
$model = new Product();
$this->render('legalisation', array('model'=>$model, 'documents'=>$documents, 'countriesIssued'=>$countriesIssued, 'countries'=>$countries, 'flag'=>$flag));
}
And in Legalisation view i have:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'legalisationForm',
'action' => $this->createUrl($this->id."/".$this->action->id),
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit'=>true,
'validateOnChange'=>true,
'validateOnType'=>false,
),
)); ?>
<table>
<tr>
<td>
<?php echo $form->dropDownList($model, 'countriesIssued', $select = array($_POST['countriesIssued'])); ?>
</td>
</tr>
</table>
this code return me an CExeption Property "Product.countriesIssued" is not defined.
When i do all of this using Chtml everything is good and a got a dropdown list full with countries name, like this:
<?php echo CHtml::dropDownList($form, 'countriesIssued', $select = array($_POST['countriesIssued']),
CHtml::listData($countriesIssued, 'code', 'name')); ?>
I need the dropdown list to be field with values (countries) Can anyone help me?
Thanks.
This bellow code will give some assistance to overcome the error that you are facing.
Wring this in your Controller
$criteria = new CDbCriteria;
$criteria->order = 'country_name ASC';
$locations = Countries::model()->findAll($criteria);
$dataAry['countries'] = CHtml::listData($locations, 'id', 'country_name');
$this->render('index', $dataAry);
Write this in your Form
echo $form->dropDownList($model, 'attribute', $countries, array('prompt' => 'Select Country'));
echo $form->error($model, 'attribute');
For more information please visit http://www.yiiframework.com/forum/index.php/topic/9693-cactiveform-dropdownlist-selectedselected/

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));
}

Symfony 1.4 form won't validate

I'm hoping someone can point me in the right direction here. This is my first Symfony project, and I'm stumped on why the form won't validate.
To test the application, I fill out all of the form inputs and click the submit button and it fails to validate every time. No idea why.
Any help will be appreciated!
The view -- modules/content/templates/commentSuccess.php :
<?php echo $form->renderFormTag('/index.php/content/comment') ?>
<table>
<?php echo $form['name']->renderRow(array('size' => 25, 'class' => 'content'), 'Your Name') ?>
<?php echo $form['email']->renderRow(array('onclick' => 'this.value = "";'), 'Your Email') ?>
<?php echo $form['subject']->renderRow() ?>
<?php echo $form['message']->renderRow() ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
The controller -- modules/content/actions/actions.class.php :
public function executeComment($request)
{
$this->form = new ContentForm();
// Deal with the request
if ($request->isMethod('post'))
{
$this->form->bind($request->getParameter("content"));
if ($this->form->isValid())
{
// Do stuff
//$this->redirect('foo/bar');
echo "valid";
}
else
{
echo "invalid";
}
}
}
The form -- /lib/form/ContentForm.class.php :
class ContentForm extends sfForm {
protected static $subjects = array('Subject A', 'Subject B', 'Subject C');
public function configure()
{
$this->widgetSchema->setNameFormat('content[%s]');
$this->widgetSchema->setIdFormat('my_form_%s');
$this->setWidgets(array(
'name' => new sfWidgetFormInputText(),
'email' => new sfWidgetFormInput(array('default' => 'me#example.com')),
'subject' => new sfWidgetFormChoice(array('choices' => array('Subject A', 'Subject B', 'Subject C'))),
'message' => new sfWidgetFormTextarea(),
));
$this->setValidators(array(
'name' => new sfValidatorString(),
'email' => new sfValidatorEmail(),
'subject' => new sfValidatorString(),
'message' => new sfValidatorString(array('min_length' => 4))
));
$this->setDefaults(array(
'email' => 'me#example.com'
));
}
}
Thanks in advance! I'll edit this post as needed during progress.
EDIT
I've changed my view code to this:
<?php echo $form->renderFormTag('/frontend_dev.php/content/comment') ?>
<table>
<?php if ($form->isCSRFProtected()) : ?>
<?php echo $form['_csrf_token']->render(); ?>
<?php endif; ?>
<?php echo $form['name']->renderRow(array('size' => 25, 'class' => 'content'), 'Your Name') ?>
<?php echo $form['email']->renderRow(array('onclick' => 'this.value = "";'), 'Your Email') ?>
<?php echo $form['subject']->renderRow() ?>
<?php echo $form['message']->renderRow() ?>
<?php if ($form['name']->hasError()): ?>
<?php echo $form['name']->renderError() ?>
<?php endif ?>
<?php echo $form->renderGlobalErrors() ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
This gives a required error on all fields, and gives " csrf token: Required.
" too.
My controller has been updated to include $this->form->getCSRFToken(); :
public function executeComment($request)
{
$this->form = new ContentForm();
//$form->addCSRFProtection('flkd445rvvrGV34G');
$this->form->getWidgetSchema()->setNameFormat('contact[%s]');
$this->form->getCSRFToken();
// Deal with the request
if ($request->isMethod('post'))
{
$this->form->bind($request->getParameter("content[%s]"));
if ($this->form->isValid())
{
// Do stuff
//$this->redirect('foo/bar');
echo "valid";
}
else
{
$this->_preWrap($_POST);
}
}
}
Still don't know why it's giving me an error on all fields and why I'm getting the csrf token: Required.
When you take full control of a Symfony form, as you are doing according to the code snippets in your OP, you will have to manually add the error and csrf elements to your form:
// Manually render an error
<?php if ($form['name']->hasError()): ?>
<?php echo $form['name']->renderError() ?>
<?php endif ?>
<?php echo $form['name']->renderRow(array('size' => 25, 'class' => 'content'), 'Your Name') ?>
// This will echo out the CSRF token (hidden)
<?php echo $form['_csrf_token']->render() ?>
Check out Symfony Docs on custom forms for more info. Also, be sure to add CSRF back to your form, there is no reason to leave it out, and will protect from outside sites posting to your forms.
It might be wise to render any global form errors:
$form->renderGlobalErrors()
Don't you have a typo in your executeComment function ?
$this->form->getWidgetSchema()->setNameFormat('contact[%s]');
and later:
$this->form->bind($request->getParameter("content[%s]"));
You should write:
$this->form->getWidgetSchema()->setNameFormat('content[%s]');
But this line is not necessary you can delete it (the NameFormat is already done in your form class).
And the $request->getParameter("content[%s]") will not word ("content[%s]" is the format of the data sent by the form), you should use:
$this->form->bind($request->getParameter("content"));
Or best, to avoid this kind of typo:
public function executeComment($request)
{
$this->form = new ContentForm();
// Deal with the request
if ($request->isMethod('post'))
{
$this->form->bind($request->getParameter($this->form->getName()));
if ($this->form->isValid())
{
// Do stuff
//$this->redirect('foo/bar');
echo "valid";
}
else
{
$this->_preWrap($_POST);
}
}
}
I ran into the same problem with an admin generated backend form. When I tried to apply css schema changes with this code, it broke the token. It didn't break right away. That signals to me this is a bug in Symfony 1.4
$this->setWidgetSchema(new sfWidgetFormSchema(array(
'id' => new sfWidgetFormInputHidden(),
'category' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('RidCategories'), 'add_empty' => false)),
'location_id' => new sfWidgetFormInputText(),
'title' => new sfWidgetFormInputText(array(), array('class' => 'content')),
'content' => new sfWidgetFormTextarea(array(), array('class' => 'content')),
'content_type' => new sfWidgetFormInputText(),
'schedule_date' => new sfWidgetFormInputText(),
'post_date' => new sfWidgetFormInputText(),
'display_status' => new sfWidgetFormInputText(),
'parent_id' => new sfWidgetFormInputText(),
'keyword' => new sfWidgetFormInputText(),
'meta_description' => new sfWidgetFormInputText(),
'update_frequency' => new sfWidgetFormInputText(),
'keywords' => new sfWidgetFormInputText(),
'allow_content_vote' => new sfWidgetFormInputText(),
'rating_score' => new sfWidgetFormInputText()
)));

Categories