can't use multiple ajaxLink for loading CJuiDialog widget - ajax

I have a problem when using multiple ajaxLink for loading CJuiDialog widget in yii. I'm using multiple dropdowns, each dropdown's value determine next dropdown.
Here is my code for viewing first dropdown and a link to create new item using Cdialog widget.
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>false,
)); ?>
<div class="row">
<?php
echo $form->labelEx($model,'uname'); ?>
<?php echo $form->dropDownList($model,'uname',$model- >getUniversityList(),array('onchange'=>'getSchemes(this.value)','empty'=>'Select university')); ?>
<?php echo $form->error($model,'uname'); ?>
<?php //create university dialoge box
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new university',array('university/dialoge'),array(
'success'=>'js:function(data){
$("#createUniversity").dialog("open");
document.getElementById("create_university").innerHTML=data;
}'));
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createUniversity',
'options'=>array(
'title'=>'Create University',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_university'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="scheme">
</div>
</div>
<?php $this->endWidget(); ?>
</div>
<input type="hidden" id="url" value="<?php echo $this->createUrl('scheme/test'); ?>">
this works pretty good.
here is the javascript code for loading next dropdown in the same view file
<script type="text/javascript">
function getSchemes(uid)
{
if(uid==""){
document.getElementById("scheme").innerHTML='';
return;
}
jQuery(function($){
var url=document.getElementById("url").value;
$.post(url, { uid:uid },
function(data){
document.getElementById("scheme").innerHTML=data;
document.getElementById("scheme_link").style.display="block";
});
});
}
The scheme drop down is loaded as the scheme view code is
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<?php
echo "<div class=".'label'."><label for=".'sch'.">Scheme</label></div>";
echo "<select id=".'sch'." onchange='getDepartments(this.value);'>";
echo "<option value=".''.">"."Select Scheme</option>";
foreach($schemes as $s)
{
echo "<option value='".$s->schemeid."' >".$s->scheme_name."</option>";
}
echo "</select>";
?>
<?php
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new Scheme',array('scheme/dialoge','id'=>5),array(
'success'=>'js:function(data1){
$("#createScheme").dialog("open");
document.getElementById("create_scheme").innerHTML=data;
}'));?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createScheme',
'options'=>array(
'title'=>'Create Scheme',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_scheme'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="department">
</div>
<input type="hidden" id="urldepart" value="<?php echo $this->createUrl('department/test'); ?> ">
the second ajaxLink is shown as create new scheme but on clicking the link it shows the old create university dialog box instead of create scheme.

The simplest solution for this is to create the ID of the element that is causing problems as random.
Try adding:
'id' => 'some-element'.uniqid() // avoid mutliple ajax request because of using live
in the $htmlOptions array of ajaxLink

Related

change URL parameter in Codeignitor

I'm trying to change the URL parameter from the row ID to the NAME of the article. here is my code
Controllers
public function view($id=0)
{
if( !isset($id) || !is_numeric($id) ) {
redirect(base_url());
}
$tot = $this->Model_service->service_check($id);
if(!$tot) {
redirect(base_url());
}
and the view is
<?php
foreach ($services as $row) {
?>
<div class="col-lg-4 col-md-6">
<div class="services-item effect-item">
<a href="<?php echo base_url(); ?>service/<?php echo $row['name']; ?>" class="image-effect">
<div class="services-photo" style="background-image: url(<?php echo base_url(); ?>public/uploads/<?php echo $row['photo']; ?>)"></div>
</a>
<div class="services-text">
<h3><?php echo $row['name']; ?></h3>
<p>
<?php echo nl2br($row['short_description']); ?>
</p>
<div class="button-bn">
<?php echo READ_MORE; ?> <i class="fa fa-chevron-circle-right"></i>
please help me with the most simplified answer thank you
Yo need to change your article view function in controller. Lookup article name instead of id. But name might contains spaces which is not URL friendly so using concept of slug will solve this.
public function view($slug='')
{
if($slug == '') {
redirect(base_url());
}
$tot = $this->Model_service->find_service_by_slug($slug);
if(!$tot) {
redirect(base_url());
}
Reference link for concept of slug is https://codeigniter.com/user_guide/tutorial/news_section.html

submit multiple inputs within a forloop in codeigniter

My code is to fetch questions of users saved in the database by a foreach loop and let the admin answer each question and save the answer of each question after checking of validation rules in the database , Here we go :
Model is :
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result();
}
My view is:
foreach ($questions as $id => $row) :
?>
<?php
echo "<h5>".$row->question;
echo "<br>";
echo "from : ".$row->user_name."</h5>";
echo date('Y-m-d H:i');
echo "<br>";
$q_no='save'.$row->id;
$ans_no='answer'.$row->id;
echo "<h4> Answer:</h4>";
echo form_open('control_panel');
?>
<textarea name='<?php echo 'answer'.$row->id; ?>' value="set_value('<?php echo 'answer'.$row->id; ?>')" class='form-control' rows='3'> </textarea>
<input type='hidden' name='<?php echo $q_no ; ?>' value='<?php echo $q_no; ?>' />
<input type='hidden' name='<?php echo $ans_no ; ?>' value='<?php echo $ans_no ; ?>' />
<?php
echo form_error($ans_no);
echo "
<div class='form-group'>
<div >
<label class='checkbox-inline'>
<input type='checkbox' name='add_faq' value='yes' />
Adding to FAQ page .
</label>
</div>
</div>
<p>";
?>
<input type='submit' name='<?php echo 'save'.$row->id; ?>' value='<?php echo 'save'.$row->id; ?>' class='btn btn-success btn-md'/>
<?php
echo 'answer'.$row->id;
?>
<hr>
<?php endforeach; ?>
and my controller is :
$this->load->model('control_panel');
$data['questions']=$this->control_panel->get_questions();
$data['no_of_questions']=count($data['questions']);
if($this->input->post($q_no))
{
$this->form_validation->set_rules($ans_no,'Answer','required|xss_clean');
if($this->form_validation->run())
{
/* code to insert answer in database */
}
}
of course it did not work with me :
i get errors :
Severity: Notice
Message: Undefined variable: q_no
i do not know how to fix it
I am using codeigniter as i said in the headline.
In your controller on your post() you have a variable called q_no you need to set variable that's why not picking it up.
I do not think name="" in input can have php code I think it has to be text only.
Also would be best to add for each in controller and the call it into view.
Please make sure on controller you do some thing like
$q_no = $this->input->post('q_no');
$ans_no = $this->input->post('ans_no');
Below is how I most likely would do lay out
For each Example On Controller
$this->load->model('control_panel');
$data['no_of_questions'] = $this->db->count_all('my_table');
$data['questions'] = array();
$results = $this->control_panel->get_questions();
foreach ($results as $result) {
$data['questions'][] = array(
'question_id' => $result['question_id'],
'q_no' => $result['q_no'],
'ans_no' => $result['ans_no']
);
}
//Then validation
$this->load->library('form_validation');
$this->form_validation->set_rules('q_no', '', 'required');
$this->form_validation->set_rules('ans_no', '', 'required');
if ($this->input->post('q_no')) { // Would Not Do It This Way
if ($this->form_validation->run() == TRUE) {
// Run Database Insert / Update
// Redirect or load same view
} else {
// Run False
$this->load->view('your view', $data);
}
}
Example On View
<?php foreach ($questions as $question) {?>
<input type="text" name="id" value="<?php echo $question['question_id'];?>"/>
<input type="text" name="q_no" value"<?php echo $question['q_no'];?>"/>
<input type="text"name="a_no" value="<?php echo $question['a_no'];?>"/>
<?php }?>
Model
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result_array();
}

Form is not getting submitted when render partial in Yii

I am partially rendering a form in a view in which user can add subaccounts(profiles). The view in which the form is called is another form where all subaccounts are listed as radiolist.
Below is my view.
<div class="inputs">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'selectUser-form',
'enableAjaxValidation' => false,
)); ?>
<?php echo CHtml::activeRadioButtonList($model,'id', $model->getSubAccounts(),array('prompt'=>'Please Select'));?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Book Now' : 'Save'); ?>
<?php echo CHtml::Button('Cancel',array('submit'=>array('cancel','id'=>$model->a_id)));?>
<?php $this->endWidget(); ?>
<div id="data"></div>
<?php echo CHtml::ajaxButton ("Add Users",
CController::createUrl('/user/user/addSubAccount'),
array('update' => '#data'));
?>
Below is my addSubAccount action.
public function actionAddSubAccount()
{
$profile=new YumProfile;
if (isset($_POST['YumProfile']))
{
$profile->attributes = $_POST['YumProfile'];
$profile->user_id=Yii::app()->user->id;
if($profile->save())
$this->redirect(array('/home/create'));}
if(!Yii::app()->request->isAjaxRequest){
$this->render('subaccount_form', array('profile'=>$profile));}
else{
$this->renderPartial('subaccount_form', array('profile'=>$profile));
}
}
Below is subaccount_form.
<?php $this->title = Yum::t('SubAccounts');?>
<div class="wide form">
<?php $activeform = $this->beginWidget('CActiveForm', array(
'id'=>'subaccount-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions' => array(
'validateOnChange' => true,
'validateOnSubmit' => true,
),
));
?>
<div class="row"> <?php
echo $activeform->labelEx($profile,'Firstname');
echo $activeform->textField($profile,'firstname');
echo $activeform->error($profile,'firstname');
?> </div>
<div class="row"> <?php
echo $activeform->labelEx($profile,'Lastname');
echo $activeform->textField($profile,'lastname');
echo $activeform->error($profile,'lastname');
?> </div>
<div class="row"> <?php
echo $activeform->labelEx($profile,'Age');
echo $activeform->textField($profile,'age');
echo $activeform->error($profile,'age');
?> </div>
<div class="row submit">
<?php echo CHtml::submitButton(Yum::t('Add')); ?>
</div>
<?php $this->endWidget(); ?>
My form is rendering. But it's not getting submitted.What am i doing wrong?
After submitting,I need the view to be refreshed and to display the newly added user as an option in the radio list.
EDIT:
I tried like adding the following in the CActiveForm Widget array:
'action' => array( '/user/user/addsubAccount' ),
But still no result.Instead it is saving my data two times when i go through my direct way,meaning render method. :-(
It is because
'enableAjaxValidation'=>true,
Ajax validation is set to true in your form. Set its value to false
'enableAjaxValidation'=>FALSE, and then your form will submit :)
and if you want it to be true only then you should uncomment
$this->performAjaxValidation($model);
in your controller's action
Update 1
if(!Yii::app()->request->isAjaxRequest){
$this->render('subaccount_form', array('profile'=>$profile));}
else{
//change this line
$this->renderPartial('subaccount_form', array('profile'=>$profile),FALSE,TRUE);
}
This link might help you
on renderPartial the action attribute of the form is set to the current page instead of being set to the actual update or create url
My Solution
$form=$this->beginWidget('CActiveForm', array(
'id'=>'country-form',
'action' => Yii::app()->createUrl(is_null(Yii::app()->request->getParam('id'))?'/country/create':'/country/update/'.Yii::app()->request->getParam('id')),

Display Dynamic SKU on configurable product view Magento

I have this script to show the dynamic sku on select option, but i cannot get working.
Is loading the correct sku, but on select nothing happen.
This code get list of sku on Javascript and update a div on select option for product on configurable product view.
<?php
$_product = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
<dl>
<?php foreach($_attributes as $_attribute): ?>
<dt><label class="required"><em>*</em><?php echo $_attribute->getLabel() ?></label></dt>
<dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
<div class="input-box">
<select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select" onchange="return changeSku(this);">
<option><?php echo $this->__('Choose an Option...') ?></option>
</select>
</div>
</dd>
<?php endforeach; ?>
</dl>
<script type="text/javascript">
var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
</script>
<?php endif;?>
<?php
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
echo '<script type="text/javascript">';
echo '
document.observe("dom:loaded", function() {
$("sku-container").update("<strong>Product Id: </strong> Select an option to display Product Id");
});
';
echo ' function changeSku(sel){';
$itemId = array();
foreach($col as $simple_product){
$itemId[] = array($simple_product->getSelectLabel() => $simple_product->getSku());
}
//echo "<pre>";
//print_r($itemId);
//echo "</pre>";
foreach($itemId as $val){
foreach($val as $k => $v){
echo "\n".'if(sel.options[sel.selectedIndex].value == "'.$k.'"){'."\n";
echo '$("sku-container").update("<strong>Product Id: </strong>'.$v.'");'. "\n";
echo '}';
}
}
echo "\n".'if(sel.options[sel.selectedIndex].value == ""){'."\n";
echo '$("sku-container").update("<strong>Product Id: </strong> Select an option to display Product Id");'. "\n";
echo '}';
echo "}";
echo "\n</script>";
?>
I appreciate any help.
Thanks
The script is almost correct except for $simple_product->getSelectLabel() being a wrong key. No such method/property exists in a simple product model. In order to make the script work, this key should be replaced with a right one - a Product Id. Utilizing product id, it is possible to find the sku of the product being selected.
So, first of all you need to reorganize itemId array to make it a "productId => productSku" map:
$productMap = array();
foreach($col as $simpleProduct){
$productMap[$simpleProduct->getId()] = $simpleProduct->getSku();
}
Then you need to change the "onchange" function call to pass Configurable's attribute id to the changeSku() function. Thus the underlying logic is able to search appropriate simple product's attributes.
onchange="return changeSku(<?php echo $_attribute->getAttributeId() ?>, this);">
And after that you need utilize configurable's config in order to map selected simple product's attribute id to the product id selected:
function changeSku(confAttributeId, sel) {
var productMap = <?php echo Mage::helper('core')->jsonEncode($productMap);?>;
var selectedAttributeId = sel.options[sel.selectedIndex].value;
if (selectedAttributeId) {
var options = spConfig.config.attributes[confAttributeId].options;
var productId = options.find(function (option) {return option.id == selectedAttributeId}).products[0]
$("sku-container").update("<strong>Product Id: </strong>" + productMap[productId]);
} else {
$("sku-container").update("<strong>Product Id: </strong> Select an option to display Product Id");
}
}
For your reference, below is the summary of how the whole template looks like (I've beautified it a little):
<?php
$_product = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
<dl>
<?php foreach($_attributes as $_attribute): ?>
<dt><label class="required"><em>*</em><?php echo $_attribute->getLabel() ?></label></dt>
<dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
<div class="input-box">
<select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select"
onchange="return changeSku(<?php echo $_attribute->getAttributeId() ?>, this);">
<option><?php echo $this->__('Choose an Option...') ?></option>
</select>
</div>
</dd>
<?php endforeach; ?>
</dl>
<script type="text/javascript">
var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
</script>
<?php endif;?>
<div id="sku-container"></div>
<?php
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
$productMap = array();
foreach($col as $simpleProduct){
$productMap[$simpleProduct->getId()] = $simpleProduct->getSku();
}
?>
<script type="text/javascript">
document.observe("dom:loaded", function() {
$("sku-container").update("<strong>Product Id: </strong> Select an option to display Product Id");
});
function changeSku(confAttributeId, sel) {
var productMap = <?php echo Mage::helper('core')->jsonEncode($productMap);?>;
var selectedAttributeId = sel.options[sel.selectedIndex].value;
if (selectedAttributeId) {
var options = spConfig.config.attributes[confAttributeId].options;
var productId = options.find(function (option) {return option.id == selectedAttributeId}).products[0]
$("sku-container").update("<strong>Product Id: </strong>" + productMap[productId]);
} else {
$("sku-container").update("<strong>Product Id: </strong> Select an option to display Product Id");
}
}
</script>
This will do the task you originally needed.
Also note the following
Your approach won't work for a configurable product with two or more configurable attributes. For that product a final simple product is not known until a user selects values for all the select inputs. So an approach should be changed to check all the selects before outputting SKU.
The code doesn't consider a case, when user edits product configuration, rather than specifying configuration for a new product. You can go to editing mode from the Shopping Cart clicking the Edit link. In such a case all the select inputs will be pre-filled with previously chosen values. But the text will say "Select an option to display Product Id". The script might also produce other Javascript errors in Edit mode. The code should be slightly modified in order to support Edit mode as well.
The template is overfilled with logic. A Magento template should have only simple prints and foreach-iterations. All the methods like $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions() are better to be moved to block. This reduces code complexity.
Hope it helps.

Subcategories with Ajax and Codeigniter

I have select box with categories and I want to display subcategories in another select box using ajax an CodeIgniter.
This is part of my view:
<script type="text/javascript">
$(document).ready(function(){
$('#tip_category').change(function(){
msg = 'category_id='+$(this).val();
$.ajax({
type : 'POST',
url : '<?php echo base_url().'admin/tips/ajax_subcategory';?>',
data : msg
});
});
});
</script>
Category:<br/>
<select name="tip_category" id="tip_category">
<?php foreach($categories as $category): ?>
<option value="<?php echo $category['id'] ?>"><?php echo $category['name'] ?>
</option>
<?php endforeach; ?>
</select><br/>
Subcategory:<br/>
<select name="tip_subcategory"
<?php if(isset($subcategories)): ?>
<?php foreach($subcategories as $subcategory): ?>
<option value="<?php echo $subcategory['id'] ?>"><?php echo $subcategory['name'] ?>
</option>
<?php endforeach; ?>
<?php endif; ?>
</select><br/>
This is part of my controller:
public function ajax_subcategory() {
$this->load->model('tips_model');
$data['subcategories'] = $this->tips_model->get_subcategories($this->input->post('category_id'));
}
My problem is that i dont know how to send data ($data['subcategories']) back to view and display subcategories. Thx for help !
I think you are just missing the return (in whatever format you need):
return $data;
You can modify your controller to:
public function ajax_subcategory() {
$this->load->model('tips_model');
$data['subcategories'] = $this->tips_model->get_subcategories($this->input->post('category_id'));
return $this->output->set_output($data);
}

Resources