Tabular Input Yii - php

I have to input several strings into table in db. Its tabular input yii. Cannot understand, how to do it this way, if i have such controller:
public function actionCreate()
{
$model1=new Section;
$model2=new SectionI18n;
if(isset($_POST['SectionI18n'])){
foreach ($model2 as $i => $m1) {
foreach($_POST['SectionI18n'] as $i => $m1)
{
$m1=new SectionI18n;
$m1->attributes=$_POST['SectionI18n'][$i];
$my[]=$m1->attributes;
}
}
and some layout:
<?php foreach ($model2 as $i=>$m1):?>
<?php ?>
<div class="row">
<?php echo $form->labelEx($model2,'Название'); ?>
<?php echo $form->textField($model2,'[$i]title',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model2,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model2,'Описание'); ?>
<?php echo $form->textArea($model2,'[$i]description',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model2,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model2,'Язык'); ?>
<?php echo $form->dropDownList($model2,'[$i]lang',array('ru'=>'ru','en'=>'en','ua'=>'ua')); ?>
<?php echo $form->error($model2,'lang'); ?>
</div>
<?php ?>
<?php endforeach;?>
Help please

It would be something similar to this:
foreach ( $_POST[Model Name] as $i => $y ){
$var name[$i] = new Model Name;
$var name[$i]->title = $_POST[Model Name][$i][title]
...
}
var_dump the post ($_POST), object makes it easier to see.

Related

Here i want to input fields dynamically

I want to get the input field dynamically based on the Number of field names in the database post your codes.
view page
<?php echo form_open('index.php/product/save_edit') ?>
<?php echo form_hidden('id',$product['id']) ?>
<div class="values">Name</div><br>
<?php echo form_input('name',$product['name']) ?>
<br>
<div class="values">Lenssensor</div><br>
<?php echo form_input('lenssensor',$product['lenssensor']) ?>
<br>
<div class="values">Price</div><br>
<?php echo form_input('price',$product['price']) ?>
<br>
<div class="values">Thickness</div><br>
<?php echo form_input('thick',$product['thick']) ?>
<br><br><br>
<?php echo form_submit('submit', 'Submit'); ?>
<br>
<?php echo form_close(); ?>
Controller edit code function
public function edit(){
$this->load->database();
$this->load->model('product_model');
$data['product'] = $this->product_model->product($this->uri->segment(3))[0];
$this->load->view('product_edit',$data);
}
Change the code to following
<?php echo form_open('index.php/product/save_edit')
$obj = new $this->product_model;
foreach ($obj as $key => $value) {
if($key == "id"){
echo form_hidden($key,$value)
}
else{
echo "<div class='values'>$key</div><br>".form_input($key,$value)."<br>" ;
}
} ?>
<br><br><br>
<?php echo form_submit('submit', 'Submit'); ?>
<br>
<?php echo form_close(); ?>

For each inside other for each on view MVC PHP

I'm trying to give structure to my code and i am facing a problem.
I'm looping through a sql query response and for each element i'm trying to retrieve other related elements. It works in my controller without problem but when i'm trying to repeat in the view I always get the same value for the related element
My controller:
<?php
include_once('class/guide.class.php');
$bdd = new DBHandler();
$req = guide::getGuides($bdd,0,5);
foreach ($req as $results => $poi)
{
$req[$results]['id'] = htmlspecialchars($poi['id']);;
$req[$results]['name'] = nl2br(htmlspecialchars($poi['name']));
$guide = new guide($results['name'],$bdd);
$guidePois = $guide->getGuidePois($poi['id']);
foreach ($guidePois as $res => $re)
{
echo $guidePois[$res]['id'];
echo $guidePois[$res]['name'];
$guidePois[$res]['id'] = htmlspecialchars($re['id']);
$guidePois[$res]['name'] = nl2br(htmlspecialchars($re['name']));
}
}
include_once('listing.php');
here, you see that I echo the ids/names of the related list of element and it works well, the output is correct for each element of the first list.
When i do it in my view:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
Somehow the first list output are the good elements, but for the 2nd list, i always get the related elements of the first item.
Do you have an idea ?
Thanks a lot for your help
This is because you only set:
$guidePois = $guide->getGuidePois($poi['id']);
once in the controller.
If you want it to work in the view, you need to insert this code right after the closing </h3>
<?php $guidePois = $guide->getGuidePois($poi['id']); ?>
So that $guidePois gets a new value in each iteration.
Complete view code:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php
$guidePois = $guide->getGuidePois($poi['id']);
foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>

if else error message always shows else statement message

I think this is a simple problem. But, I don't know how to solve this problem. I have posted my codes below. Here, In this below code if else statement always shows No Sarees. I got the result from mysql table but it always shows with No Sarees text. I have checked this using var_dump($categories) it returns array(0){} . How can I solve this problem?
<?php if ($categories) { ?>
<!--BOF Refine Search Result-->
<div class="refine-search-result">
<?php if (count($categories) <= 5) { ?>
<?php foreach ($categories as $category) { ?>
<div class="refine-block">
<p><?php echo $category['name']; ?></p>
</div>
<?php } ?>
<?php } else { ?>
<?php for ($i = 0; $i < count($categories);) { ?>
<?php $j = $i + ceil(count($categories) / 4); ?>
<?php for (; $i < $j; $i++) { ?>
<?php if (isset($categories[$i])) { ?>
<div class="refine-block">
<p><?php echo $categories[$i]['name']; ?></p>
</div>
<?php } ?>
<?php } ?>
<?php } ?>
<?php } ?>
<div class="clear"></div>
</div><!--EOF Refine Search Result-->
<?php } else {
?>
<div class="refine-search-result">
<div class="refine-block">
<p>No Sarees</p>
</div>
<div class="clear"></div>
</div>
<?php } ?>
If your $categories is empty array then in if($categories) your array is converted to boolean value. If it's empty array (and you say it is) then it's get converted to false.
Check this:
$categories = array(); //empty array
var_dump((boolean)$categories); //this will show what variable will look like after converting to boolean value
if ($categories){
echo '$categories IS NOT empty';
}else{
echo '$categories IS empty';
}

How to validate tabular data in yii?

I have created a form which allows user to save tabular data. I have followed this tutorial . I have managed to add multiple instance for a Model and I am getting the data in the post and it is getting validate. The problem is with the error summary and the AJAX validation.
Below is my controller code, I have created an array for the second Model and passed it to the form.
$model = new UserAccountDetail;
$addresses = array();
array_push($addresses, new UserAddress);
array_push($addresses, new UserAddress);
$this->validateUserAccount($model,$addresses);
if(isset($_POST['UserAccountDetail']) && isset($_POST['UserAddress']))
{
$model->attributes = $_POST['UserAccountDetail'];
$model->validate();
$addresses = array();
for($i=0;$i<2;$i++)
{
if(isset($_POST['UserAddress'][$i]))
{
$address = new UserAddress;
$address->attributes = $_POST['UserAddress'][$i];
array_push($addresses, $address);
$address->validate();
}
}
}
$this->render('accountinformation',array('model'=>$model,'addresses'=>$addresses));
Below is my ajax validation function:
protected function validateUserAccount($model,$addresses)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='user-account-detail-form')
{
echo CActiveForm::validate($model).CActiveForm::validateTabular($addresses);
Yii::app()->end();
}
}
When I run this code the Ajax validation does not work. The onclick validation does work but for the tabular data the messages are not shown in the error summary but the fields are highlighted in red.
I any thing else is required then please let me know.
Thanks for your time. Cheers!!!!!
Update View File:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'user-account-detail-form',
'enableAjaxValidation'=>true,
)); ?>
<?php echo $form->errorSummary($model,$address); ?>
<h2> Account Details </h2>
<div class="row">
<?php echo $form->labelEx($model,'Title'); ?>
<?php echo $form->dropDownList($model,'Title', $model->getAllTitles()); ?>
<?php echo $form->error($model,'Title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'firstName'); ?>
<?php echo $form->textField($model,'firstName',array('size'=>50,'maxlength'=>100)); ?>
<?php echo $form->error($model,'firstName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'middleName'); ?>
<?php echo $form->textField($model,'middleName',array('size'=>50,'maxlength'=>100)); ?>
<?php echo $form->error($model,'middleName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lastName'); ?>
<?php echo $form->textField($model,'lastName',array('size'=>50,'maxlength'=>100)); ?>
<?php echo $form->error($model,'lastName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'displayName'); ?>
<?php echo $form->textField($model,'displayName',array('size'=>50,'maxlength'=>200)); ?>
<?php echo $form->error($model,'displayName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'birthDate'); ?>
<?php echo $form->textField($model,'birthDate',array('size'=>50,'maxlength'=>15)); ?>
<?php echo $form->error($model,'birthDate'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lenderType'); ?>
<?php echo $form->textField($model,'lenderType',array('size'=>50,'maxlength'=>15)); ?>
<?php echo $form->error($model,'lenderType'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'businessName'); ?>
<?php echo $form->textField($model,'businessName',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model,'businessName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'hearAboutUs'); ?>
<?php echo $form->dropDownList($model,'hearAboutUs', $model->getAllHearAbout()); ?>
<?php echo $form->error($model,'hearAboutUs'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'promotionalCode'); ?>
<?php echo $form->textField($model,'promotionalCode',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'promotionalCode'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'mobileNumber'); ?>
<?php echo $form->textField($model,'mobileNumber',array('size'=>50,'maxlength'=>15)); ?>
<?php echo $form->error($model,'mobileNumber'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'workLandline'); ?>
<?php echo $form->textField($model,'workLandline',array('size'=>50,'maxlength'=>15)); ?>
<?php echo $form->error($model,'workLandline'); ?>
</div>
<?php echo $form->textField($model,'thirdAnswer',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'thirdAnswer'); ?>
</div>
<h2>Address </h2>
<?php foreach ($addresses as $i=>$address) { ?>
<div class="row">
<?php echo $form->labelEx($address,"[$i]Flat"); ?>
<?php echo $form->textField($address,"[$i]Flat",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]Flat"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]buildingName"); ?>
<?php echo $form->textField($address,"[$i]buildingName",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]buildingName"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]buildingNumber"); ?>
<?php echo $form->textField($address,"[$i]buildingNumber",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]buildingNumber"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]street"); ?>
<?php echo $form->textField($address,"[$i]street",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]street"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]district"); ?>
<?php echo $form->textField($address,"[$i]district",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]district"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]town"); ?>
<?php echo $form->textField($address,"[$i]town",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]town"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]county"); ?>
<?php echo $form->textField($address,"[$i]county",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]county"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]postCode"); ?>
<?php echo $form->textField($address,"[$i]postCode",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]postCode"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]isCorresppondence"); ?>
<?php echo $form->textField($address,"[$i]isCorresppondence",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]isCorresppondence"); ?>
</div>
<?php } ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Continue'); ?>
</div>
<?php $this->endWidget(); ?>
Update : I have checked the response from the server and it is giving the correct response. Below is the screen shot:
Update :: I have managed to correct the on click validation issue by passing the array of models to the errorSummary() function like:
<?php
$error = array();
array_push($error, $model);
foreach ($addresses as $address)
{
array_push($error, $address);
}
echo $form->errorSummary($error); ?>
But the AJAX validation is still not working. Can any one help me with that.
http://www.yiiframework.com/doc/api/1.1/CActiveForm
The AJAX-based validation has a few limitations. First, it does not
work with file upload fields. Second, it should not be used to perform
validations that may cause server-side state changes. Third, it is not
designed to work with tabular data input for the moment.
So, you need to write custom error handler for tabular data
//view
$form = $this->beginWidget('CActiveForm', array(
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnChange' => false,
'validateOnType' => false,
'validateOnSubmit' => true,
'beforeValidate' => 'js:formBeforeValidate',
'afterValidate' => 'js:formAfterValidate'
),
));
//some js
function formBeforeValidate (form) {
//clean errors
return true;
}
function formAfterValidate(form, data, hasError) {
if (hasError === true) {
//append errors to input
}
return !hasError;
}
There is no inbuilt mechanism in Yii to ajax validation for tabular data. I implemented custom validation using jquery for this purpose. Below is the code that I used to create a custom ajax validation for tabular data.
Controller: It assigns the value passed to the model attribute and returns any error for the attribute.
public function actionValidateData($value,$name)
{
$model = new BusinessPartner;
$model->setAttribute($name, $value);
$model->validate();
echo CHtml::error($model,$name);
Yii::app()->end();
}
Jquery function to make ajax call and show the messages. I have added class 'businessPartner' to all the fields of the model.
$(document).on('blur','.businessPartner',function(e){
e.preventDefault();
var id= $(this).attr('id');
var name= $(this).attr('rel');
$.ajax({
url:"<?php echo Yii::app()->createUrl('user/validatedata'); ?>",
type: "GET",
data: 'value='+$.trim($(this).val())+'&name='+ name,
success :function(data){
if($.trim(data))
{
if(!$('#'+id).hasClass('error'))
{
$('#'+id).addClass('error');
$('#'+id).prev().addClass('error');
$('#'+id).after(data);
}
}
else
{
if(!$('#'+id).parent().hasClass('success'))
{
$('#'+id).removeClass('error');
$('#'+id).prev().removeClass('error')
$('#'+id).next().remove()
$('#'+id).parent().addClass('success');
}
}
},
error:function(){
},
});
});

Yii: How to update multiple models using only 1 form 1 model and 1 action?

I have a model website and a model url.
Each url data is attached to a website data. A url is related to a website via a website_id.
On my web app, I need to check the data before accepting it.
I want to see on screen the entire data regarding a url data and I managed to do this.
Now, I also want to update the entire data that is listed on screen.
On screen I have the entire url data and website data, but when I try to save the data, the website data is empty.
My logic was to add to the url model a property: public $website;
And within the url model, a method aftersave:
protected function afterSave() {
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
//echo '<pre>';
//print_r($w);
print_r($this->website);
$w->link = $this->website['link'];
$w->domain = $this->website['domain'];
$w->description = $this->website['description'];
$w->save(false);
die;
return parent::afterSave();
}
and here is the important code from the _form file:
<div class="row">
<?php echo $form->labelEx($model,'will_expire'); ?>
<?php echo $form->dropDownList($model,'will_expire',array(0=>'No',1=>'Yes')); ?>
<?php echo $form->error($model,'will_expire'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'link'); ?>
<?php echo $form->textField($model_website,'link'); ?>
<?php echo $form->error($model_website,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'domain'); ?>
<?php echo $form->textField($model_website,'domain'); ?>
<?php echo $form->error($model_website,'domain'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'description'); ?>
<?php echo $form->textField($model_website,'description'); ?>
<?php echo $form->error($model_website,'description'); ?>
</div>
There are few questions:
Is the relation url and website being defined in the model such that $url->website of a existing url gives you valid website record?
You form shows, you are not using any website_id, means that you are creating a new website record for every URL, means $w = Website::model()->findByAttributes(array('id' => $this->website_id)); will always return NULL
I assume you have defined a relation of website within your URL model.
Suggested function from my understanding:
protected function afterSave() {
//data is already assigned by the caller
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
if($w)
{
Yii::log("updating existing website data","info");
$this->website->save();
}
else
{
Yii::log("creating new website data","info");
$this->website->save();
$this->website_id = $this->website->website_id;
$this->update(array('website_id')); //save the relation
Yii::log("created new website {$this->website_id}","info");
}
return parent::afterSave();
}
It turned out to be small mistakes like w instead of W, object property instead of array;
Ok, so let me teach you how to do this;
I have 2 models: Url and Website.
Url model has a foreign key website_id and a relation to model Website;
Within the Url model I have a property called website and i declared it like: public $website = array();;
The data gets added thru a bookmarklet that uses a API so the data will be there when the admin comes to update/check it;
In the Url model i have a method afterSave:
protected function afterSave() {
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
if($w)
{
$w->link = $this->website['link'];
$w->domain = $this->website['domain'];
$w->description = $this->website['description'];
$w->save();
}
return parent::afterSave();
}
where $this->website gets populated in the UrlController on actionUpdate like:
public function actionUpdate($id, $type = 'update') {
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Url'])) {
$model->attributes = $_POST['Url'];
$model->website = $_POST['Website'];
if ($model->save())
if ($type == 'update')
$this->redirect(array('view', 'id' => $model->id));
else
$this->redirect(array('/admin/url/approvePublicLink'));
}
$model_website = Website::model()->findByAttributes(array('id'=>$model->website_id));
$this->render('update', array(
'model' => $model,
'model_website' => $model_website,
));
}
and gets passed to the afterSave method later;
this is the _update view:
<div style="padding:20px 20px;">
<h1>Update Url, Website, Keywords ...</h1>
<?php echo $this->renderPartial('_form', array(
'model'=>$model,
'model_website' => $model_website,
)); ?>
</div>
and this is the _form view that gets rendered partial:
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'url-form',
'enableAjaxValidation'=>false,
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'website_id'); ?>
<?php echo CHtml::link($model->relation_website->domain,$model->relation_website->domain,array('class'=>'avia','target'=>'_blank')); ?>
<?php echo $form->error($model,'website_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'link'); ?>
<?php echo $form->textField($model,'link',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textField($model,'description',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'important'); ?>
<?php echo $form->dropDownList($model,'important',array(0=>'Normal',1=>'Important')); ?>
<?php echo $form->error($model,'important'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'views'); ?>
<?php echo $form->textField($model,'views'); ?>
<?php echo $form->error($model,'views'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'created'); ?>
<?php echo $model->created; ?>
<?php echo $form->error($model,'created'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'updated'); ?>
<?php echo $model->updated; ?>
<?php echo $form->error($model,'updated'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'will_expire'); ?>
<?php echo $form->dropDownList($model,'will_expire',array(0=>'No',1=>'Yes')); ?>
<?php echo $form->error($model,'will_expire'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'link'); ?>
<?php echo $form->textField($model_website,'link'); ?>
<?php echo $form->error($model_website,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'domain'); ?>
<?php echo $form->textField($model_website,'domain'); ?>
<?php echo $form->error($model_website,'domain'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'description'); ?>
<?php echo $form->textField($model_website,'description'); ?>
<?php echo $form->error($model_website,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php echo $form->dropDownList($model,'status',array(-1=>'Banned',0=>'Normal',1=>'Active')); ?>
<?php echo $form->error($model,'status'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I hope it helps.

Categories