How to create dynamic Checkboxlist in Yii? - ajax

I would like a help to solve this problem. I'm using Yii 1.1 and trying to create a dynamic CheckBox list in which its elements change depending on the value selected in a DropDown element.
I created this DropDown element with the arguments in Ajax to perform the function update in the Controller. The function in the Controller is doing the lookup in the table according to the value passed.
Up to this point, the code is working fine, generating an array with the values that should be displayed. The problem is that I'm not able to configure the return of these data and I can't even display them in the View.
Below is the code data:
View - DropDown element:
echo CHtml::activeDropDownList($model, 'standard',
array(CHtml::listData(standard::model()->findAll(), 'name','name')),
array('empty'=>'',
'ajax'=>array(
'type'=>'POST',
'url'=>CController::createUrl('/getTeam',array('form'=>'Team','field'=>'standard')),
'update'=>'#Audit_team'),
)
);?>
Controller:
public function actionGetTeam($form,$field) {
$post = $_POST;
$standard = $post[$form][$field];
$Lists = TblAuditStandard::model()->findAll("standard = $standard");
foreach ($Lists as $List){
$AuditTeam[] = $List->name." - ".$List->login;
asort($AuditTeam);
foreach ($AuditTeam as $id=>$value )
echo CHtml::tag('option',array('value'=>$id),$value,true);
}
}
View - Checkbox element:
<div class="row">
<?php echo $form->labelEx($model,'team'); ?>
<?php echo CHtml::activeCheckBoxList($model,'team',array()); ?>
<?php echo $form->error($model,'team'); ?>
</div>
I hope someone can help me solve this problem. Thanks.

Related

Repopulate Dynamic Dropdown with "set_select" after Form Validation fails in Codeigniter?

I was wondering if it is possible to repopulate a dynamic dropdown(specifically the option of a select) after form validation fails which is generated by another dropdown at on change event.
My jQuery is working good on populating dynamic option of a select as well as at server-side when fetching the data, my only problem is when the form is submitted and validation fails, so basically the dynamic select option/s will reset.
Can somebody help me with this issue?
You have 2 options here:
1) You manually set the 2x select fields with CI and repopulate/set them. You would construct these based on the POST values that were incorrect.
Assuming that list A populates list B which populates list C you may not want to do that. In which case you could define some hidden variables such as this:
var field1 = '<?php $_POST['field1']; ?>';
var field2 = '<?php $_POST['field2']; ?>';
var field3 = '<?php $_POST['field3']; ?>';
$(document).ready(function(){
$('#field1').val(field1).trigger('change'); // or whatever on() query event you use
$('#field2').val(field1).trigger('change'); // or whatever on() query event you use
$('#field3').val(field1).trigger('change'); // or whatever on() query event you use
})
Might help? You would do the trigger to then load whichever lists/ajax calls populate each select box.
Yes it is possible,
this example works with Codeigniter 4 but I'm quite sure it works also with Codeigniter 3. Here I wanted to do a multiple dropdown field with Select2
<div class="form-group">
<label>Categories</label>
<?php
$parameters = array('class' => 'form-control select2_cat', "multiple" => "multiple");
$options = array();
foreach ($categories as $cat) {
$options[$cat['name']] = $cat['name'];
}
echo form_dropdown(
'categories[]',
$options,
set_value('categories[]') != "" ? set_value('categories[]') : 0,
$parameters
);
?>
</div>
You see from the code, I'm using set_value() . I'm checking also if set_value is empty string.
You could find more info here: https://www.py4u.net/discuss/37330

load view via ajax cakephp 2.x

i want to load a list of items on my view via ajax here is my code on lst.cpt
<div id='benpane' class='clearfix'>
<script type="text/javascript">
<?php echo $ajax->remoteFunction(array(
'url'=>array('controller'=>'benefits', 'action'=>'display'),
'update'=>'benpane',
'indicator'=>'benIndicator'
)); ?>
</script>
</div>
here is the lst function in my controller
function lst() {
$this->paginate = array('order' => array('ben_name' => 'ASC'),'conditions' => array($this->Benefit->parseCriteria($this->passedArgs)));
$benefit = $this->paginate('Benefit');
$this->set('bens', $benefit);
}
when i try to open the view i get the error
Error: Call to a member function remoteFunction() on a non-object
File: /var/www/hassportal/app/View/Benefits/lst.ctp
Line: 14
what could i be doing wrong?
Besides the fact that the Ajax Helper has been deprecated (and/or perhaps you are not using cakephp 2.x), you seem to be calling the wrong action:
'action'=>'display'
should be:
'action'=>'lst'
Also, I would move the code outside of the DIV that is supposed to be updated with the data coming from that action.
Use this
$this->Ajax->remoteFunction
insited of
$ajax->remoteFunction
Ex:-
<?php echo $this->Ajax->remoteFunction(array(
'url'=>array('controller'=>'benefits', 'action'=>'display'),
'update'=>'benpane',
'indicator'=>'benIndicator'
)); ?>

Yii ClientSide Validation on Render Partial not Working

I have a Yii form which calls a render partial from another model (team has_many team_members). I want to call via ajax a partial view to add members in team/_form. All works (call, show, save) except for ajax validations (server and client side). If i submit form, member's model isn't validating, even in client side, it's not validating the required fields.
Any clue?
//_form
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'team-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true
),
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
//Controller
public function actionMember($index)
{
$model = new TeamMember();
$this->renderPartial('_member',array(
'model'=> $model, 'index'=> $index
)
,false,true
);
}
public function actionCreate()
{
$model=new Team;
$members = array();
if(isset($_POST['Team']))
{
$model->attributes=$_POST['Team'];
if(!empty($_POST['TeamMember'])){
foreach($_POST['TeamMember'] as $team_member)
{
$mem = new TeamMember();
$mem->setAttribute($team_member);
if($mem->validate(array('name'))) $members[]=$mem;
}
}
$this->redirect(array('team/create','id'=>$model->id,'#'=>'submit-message'));
}
$members[]=new TeamMember;
$this->performAjaxMemberValidation($members);
$this->render('create',array(
'model'=>$model,'members'=>$members
));
}
//_member
<div class="row-member<?php echo $index; ?>">
<h3>Member <?php echo $index+1; ?></h3>
<div class="row">
<?php echo CHtml::activeLabel($model, "[$index]name",array('class'=>'member')); ?>
<?php echo CHtml::activeTextField($model, "[$index]name",array('class'=>'member')); ?>
<?php echo CHtml::error($model, "[$index]name");?>
</div>
</div>
ProcessOutput was set to true. No dice.
Switch renderPartial() to render(). No dice.
If you will look at the CActiveForm::run:
$cs->registerCoreScript('yiiactiveform');
//...
$cs->registerScript(__CLASS__.'#'.$id,"jQuery('#$id').yiiactiveform($options);");
Then you will understand that you validation will not work, because you render partial and not the whole page. And these scripts show up at the bottom of the page. So you should solve this by execute these scripts.
After you partial is rendered, try to get activeform script which should be stored at the scipts array:
$this->renderPartial('_member',array('model'=> $model, 'index'=> $index));
$script = Yii::app()->clientScript->scripts[CClientScript::POS_READY]['CActiveForm#team-form'];
after, send it with rendered html to page:
echo "<script type='text/javascript'>$script</script>"
Also remember before you will append recieved html on the page you should include jquery.yiiactiveform.js, if you not already did it(by render another form, or registerCoreScript('yiiactiveform')), on the page from calling ajax request. Otherwise javascript error will raised.
Hope this will help.
Edit:
Sorry I'm not understood that you are render part of form and not the whole. But you validation will not work exactly with the same issue. Because jQuery('#$id').yiiactiveform($options); script was not created for the field.
The actual problem is that the ActiveForm saves its attributes to be validated in the "settings" data attribute. I see you are already using indexes so what you need to add the new elements to this settings object in order for the validation to work. After the ajax response this is what must be done:
//Get the settings object from the form
var settings = $("#form").data('settings');
//Get all the newly inserted elements via jquery
$("[name^='YourModel']", data).each(function(k, v) {
//base attribute skeleton
var base = {
model : 'YourModel',
enableAjaxValidation : true,
errorCssClass : 'error',
status : 1,
hideErrorMessage : false,
};
var newRow = $.extend({
id : $(v).attr('id'),
inputID : $(v).attr('id'),
errorID : $(v).attr('id') + '_em_',
name : $(v).attr('name'),
}, base);
//push it to the settings.attribute object
settings.attributes.push(newRow);
});
//update the form
$("#form").data('settings', settings);
```
This way the ActiveForm will be aware of the new fields and will validate them.
Well, setting processOutput to true in renderPartial (in order to make client validation works on newly added fields) will not help in this case since it will only work for CActiveForm form and you don't have any form in your _member view (only input fields).
A simple way to deal with this kind of problem could be to use only ajax validation, and use CActiveForm::validateTabular() in your controller to validate your team members.

Retrieve product custom media image label in magento

I have a custom block loading products on my front page that loads the four newest products that have a custom product picture attribute set via:
$_helper = $this->helper('catalog/output');
$_productCollection = Mage::getModel("catalog/product")->getCollection();
$_productCollection->addAttributeToSelect('*');
$_productCollection->addAttributeToFilter("image_feature_front_right", array("notnull" => 1));
$_productCollection->addAttributeToFilter("image_feature_front_right", array("neq" => 'no_selection'));
$_productCollection->addAttributeToSort('updated_at', 'DESC');
$_productCollection->setPageSize(4);
What I am trying to do is grab the image_feature_front_right label as set in the back-end, but have been unable to do so. Here is my code for displaying the products on the front end:
<?php foreach($_productCollection as $_product) : ?>
<div class="fll frontSale">
<div class="productImageWrap">
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'image_feature_front_right')->directResize(230,315,4) ?>" />
</div>
<div class="salesItemInfo">
<p class="caps"><?php echo $this->htmlEscape($_product->getName());?></p>
<p class="nocaps"><?php echo $this->getImageLabel($_product, 'image_feature_front_right') ?></p>
</div>
</div>
I read that $this->getImageLabel($_product, 'image_feature_front_right') was the way to do it, but produces nothing. What am I doing wrong?
Thanks!
Tre
It seems you asked this same question in another thread, so to help others who might be searching for an answer, I'll anser it here as well:
I imagine this is some sort of magento bug. The issue seems to be that the Magento core is not setting the custom_image_label attribute. Whereas for the default built-in images [image, small_image, thumbnail_image] it does set these attributes - so you could do something like:
$_product->getData('small_image_label');
If you look at Mage_Catalog_Block_Product_Abstract::getImageLabel() it just appends '_label' to the $mediaAttributeCode that you pass in as the 2nd param and calls $_product->getData().
If you call $_product->getData('media_gallery'); you'll see the custom image label is available. It's just nested in an array. So use this function:
function getImageLabel($_product, $key) {
$gallery = $_product->getData('media_gallery');
$file = $_product->getData($key);
if ($file && $gallery && array_key_exists('images', $gallery)) {
foreach ($gallery['images'] as $image) {
if ($image['file'] == $file)
return $image['label'];
}
}
return '';
}
It'd be prudent to extend the Magento core code (Ideally Mage_Catalog_Block_Product_Abstract, but I don't think Magento lets you override Abstract classes), but if you need a quick hack - just stick this function in your phtml file then call:
<?php echo getImageLabel($_product, 'image_feature_front_right')?>
Your custom block would need to inherit from Mage_Catalog_Block_Product_Abstract to give access to that method.
You could also use the code directly from the method in the template:
$label = $_product->getData('image_feature_front_right');
if (empty($label)) {
$label = $_product->getName();
}

DropDown list in yii

In my form I have following designing
Template dropdown list
name Textbox
from Textbox
subject textbox
content textbox
If i m selecting any template from template then remaining fields like name,from,subject,etc can be changed a per selection of template...
please give the solution for this
<div class="row">
<?php echo $form->labelEx($model,'profile_id'); ?>
<?php echo $form->dropDownList($model,'profile_id', CHtml::listData(Email::model()->findAll(), 'email_id', 'name'), array('empty'=>'---Select Template---')); ?>
<?php echo $form->error($model,'profile_id'); ?>
</div>
Thanks in advance!!!!!
$("#dropdownlist").change(function(
var value = this.val();
switch (value) {
case 'template1':
// change fields
break;
case 'template2':
// change fields
break;
default:
alert("ERROR: this template not exist.");
}
));

Resources