Set options for the dropdown based on radio button select - yii

I have a form in which contains a dropdown field.The options for the dropdown is based on the radio button selection.
Radio Button
<?php
$list=array("1"=>"Assign to Department","2"=>"Assign to user");
echo $form->field($model, 'option')->radioList($list,
[
'template' => '{input}{label}', // put the label behind
]);
?>
Script
<script>
$('input[type=radio]').click(function(){
var Flag=this.value;
if(Flag=='1') {
'<?php $items= ArrayHelper::map($company->Users, 'id', 'fullname');?>';
} else if(Flag=='2') {
'<?php $items= ArrayHelper::map(Department::find()->all(), 'dep_id', 'name'); ?>';
}
alert(Flag);
});
</script>
Drodown
<?php
echo $form->field($model, 'assignee')
->dropDownList(
$items, // Flat array ('id'=>'label')
['prompt'=>''] // options
)->label('');
?>
Expected response is the change of option values according to the drop down selection.But it is not changing even though the flag value is different for radio buttons and changes on click.
Any ideas?

I have tried this for a sample and it works -
<?php
$items1 = range(0, 5); //PHP Array 1
$items2 = range(5, 10); //PHP Array 2
?>
<script>
var arr1 = <?php echo json_encode($items1); ?>; //Javascript Array 1
var arr2 = <?php echo json_encode($items2); ?>; //Javascript Array 2
$(document).ready(function() {
$('input[type=radio]').click(function(){
var Flag = this.value;
setDropdown(Flag);
});
});
function setDropdown(Flag) {
var elem = $('#Skill_order_no'); //Your dropdown element name.
if(Flag == '1') {
elem.empty();
$.each(arr1, function(index, value) {
elem.append($('<option>').text(value).attr('value', value));
});
} else if(Flag == '2') {
elem.empty();
$.each(arr2, function(index, value) {
elem.append($('<option>').text(value).attr('value', value));
});
}
}
</script>

Related

how to get one of the input textfield value through ajaxbutton

how do i get the user's input value and submit it to ajax then to controller? Right now, in my controller it says that id is an undefined index in $_POST['id']
This input textfield is actually within another form, kind of like a form inside a form.
<?php echo $form->textField($model,'email',array('id'=>'email')); ?>
<?php echo $form->error($model,'email'); ?>
<?php echo CHtml::ajaxButton ( 'Request Code',
CHtml::normalizeUrl(array('site/requestResetCode', 'render'=>true),
array (
'type' => 'POST',
//'data'=> array('id'=> 'js:$("#ResetPasswordForm_email").val()'),
'data'=> array('id'=> 'js:$("#email").val()'),
'success'=>'function(data){
if(data.status == "sent")
bootbox.alert("Code is sent. Please check your email.");
else (data.status == "failed")
bootbox.alert("Request Failure");
}',
'error'=> 'function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}',
)
))
?>
controller:
public function actionRequestResetCode()
{
$id = $_POST['id'];
//stuff..
your POST array is empty because value is not being sent. You need to make a javascript function like
<script type="text/javascript">
function getVal()
{
var value= $("#myEmail").attr('value');
alert(value);
return value;
}
</script>
check if the alert shows correct value then remove this alert statement. If it does not show the value then there is a problem with the id of your textfield.
If you get it working then use it like
'data'=> array('id'=> 'js:getVal()'),

How to Redirects with a Drop Down?

I have parent page and there are two child view _sectionhead.php and _classteacher.php i need to renderPartial to those child view when user select from dropdwon how can do this
this is my create from
IF there is any other way i like to know it.i need quick help
In view:
<?php Yii::app()->clientScript->registerScript('some-name', "
$('select').on('change', function (event) {
var url = $(event.currentTarget).val();
if (url != 0)
$.get(url, function (data) {
$('#result').html(data);
});
});", CClientScript::POS_READY) ?>
<?php echo
CHtml::dropDownList("param", "select here", [
'Select here',
$this->createUrl('/testing/action1') => "Add class teacher",
$this->createUrl('/testing/action2') => "Add class techer"
]) ?>
<div id="result"></div>
Assuming you are doing in HTML ,Add below in HTML code
<option onClick="fnCallPage('classteacher')">class teacher</option>
<option onClick="fnCallPage('Section')">Section</option>
Add below in Javascript tag :
function fnCallPage(param){
//Javascript code for sending
}
Based on #Fraz solution:
HTML:
<option onClick="fnCallPage('_classteacher')">class teacher</option>
<option onClick="fnCallPage('_sectionhead')">Section</option>
<div id="divContainerPartial"></div> <!-- View rendered container -->
Javascript:
function fnCallPage(param){
$.ajax({
url: '<?php echo Yii::app()->createUrl('yourModel/renderPageByAjax');?>/' + param,
type: 'GET',
success: function(html){
$('#divContainerPartial').html(html);
},
error: function(data){
alert('Error loading a '+param+' view.');
}
});
}
Controller:
/**
* #param $view String : View name to render.
*/
public function actionRenderPageByAjax($view)
{
$params = array(); // Variables to view.
$this->renderPartial('//myFolderView/'.$view, array(
'params' => $params,
), false, true);
}

How to add a new ZF2' Zend\Form\Element within jQuery ajax

I want to add a new ZF2' Zend\Form\Element within jQuery ajax. But while I use the Zend Form , I don't know how to make it. This is the add.phtml file.
<script type="text/javascript">
$(document).ready(function(){
$(".pid").change(function(){
var id = $('.pid').val();
var $_this = $(this);
$.ajax({
type:"POST",
url:"<?php echo $this->url('Element/default',array('action'=>'change'));?>",
data:"pid="+id,
dataType:'json',
async:false,
success:function(data){
if(data.response){
//here I want to add a new select component after select conponent "pid" using like "$this->formRow($form->get('mid'))" or else .
}
}
});
});
});
</script>
the following is the remaining part of the html.
<?php
$title = 'add';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url(
'Element/default',
array(
'action' => 'add'
)
));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('pid'));
echo $this->formRow($form->get('name'));
echo $this->formRow($form->get('desc'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
How do I add a new zend form element within jquery ajax ? Thanks.
You have script to receive data using ajax and view/html should be received by this script. You need controller/action to rendering data and return as response.
use Zend\View\Model\JsonModel;
//some controller
public function changeAction(){ // your requested action
//1. get partial helper to rendering html;
$partial = $this->getServiceLocator()->get('ViewHelperManager')->get('partial');
$form = new Form();// your form
//2. render html
$html = $partial('path/to/your/file/phtml',['form'=>$form]);
//3. return data as JSON because in your ajax configuration dataType: 'json'
return new JsonModel([
'html' => $html,
]);
}
in your js success function should be:
success:function(data){
if(data.html){
$_this.find('blockToAppend').append(data.html);
}
}

AutoComplete - yii

I am trying to add a field with auto complete functionality , I have used javascript for this
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css " />
<script src="http://code.jquery.com/jquery-1.8.2.js "></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js "></script>
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
function split( val ) {
//document.write(val.length);
return val.split( /,\s*/ );
}
function extractLast( term ) {
//echo (term.length);
//document.write(term.length);
return split( term ).pop();
}
$( "#Tag_tag_name" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
var a=0;
// if (event.keyCode === $.ui.keyCode.TAB)
// {
// a=a+1;
// }
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
// if (event.keyCode === $.ui.keyCode.P)
// {
// alert(a);
// }
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
Now What I want tot do is instead of this static values in AvaialbleTags variable I want values from database ? Plus I want to limit three values to be add by the user.
Can anyone help me with this ?
Here is what i am using multicomplete
$this->widget('ext.widgets.MultiComplete', array(
'model'=>$model,
'attribute'=>$attribute,
'splitter'=>',',
'sourceUrl'=>$this->createUrl($url),
// additional javascript options for the autocomplete plugin
'options'=>array(
'minLength'=>'1',
),
'htmlOptions'=>array(
'size'=>'60'
),
));

How to refilter a dojo DataGrid?

I have a DataGrid that I already filtered using grid.filter(query, rerender). If I add another item, after calling save() I see the new item in the grid even though it shouldn't display because of the filter. I'm thinking "ok, I'll just filter it again when the store finishes saving. But after calling grid.filter with the same query all the rows disappear. Any ideas what I might be doing wrong?
Code to filter the grid:
var filterQuery = dijit.byId("filterTextbox").attr("value");
var grid = dijit.byId("grid");
var queryValue = "*";
if(filterQuery != ""){
queryValue += filterQuery + "*";
}
grid.filter({name: queryValue}, true);
Code to add new items to the grid
function addItemToGrid(newItemName){
var newItem = {name: newItemName};
var grid = dijit.byId("grid");
var store = grid.store;
store.addItem(newItem);
store.save();
}
Try to use:
store.newItem(newItem);
instead of store.addItem(newItem);
(addItem is not a standard method to add items into store)
Inside of your addItemToGrid function, try adding an onComplete listener to your save method and sort or filter the grid in the onComplete function
store.save({onComplete: function() {
grid.filter({name: queryValue}, true);
}
});
I had the same problem and only managed to fix it by running the grid filter periodically in the background with the help of some jQuery. Here is some sample code; hope this helps someone else having problems with this.
// ADD JQUERY
<script src="http://code.jquery.com/jquery-latest.js"></script>
.
// PUT THIS IN THE <HEAD> OF THE PAGE
<script type="text/javascript">
$(document).ready(function() {
function filterTheDataGrid() {
if (dijit.byId("grid") != undefined) {
dijit.byId("grid").filter({color: "Red"});
}
}
// RUN THE filterTheDataGrid FUNCTION EVERY ONE SECOND (1000 MILLISECONDS) //
// LOWER '1000' FOR FASTER REFRESHING, MAYBE TO 500 FOR EVERY 0.5 SECOND REFRESHES //
var refreshDataGrid = setInterval(function() { filterTheDataGrid(); }, 1000);
}
</script>
.
// PUT THIS IN THE <HEAD> OF THE PAGE
<script type="text/javascript">
// SETUP THE LAYOUT FOR THE DATA //
var layoutItems = [[
{
field: "id",
name: "ID",
width: '5px',
hidden: true
},
{
field: "color",
name: "Color",
width: '80px'
}
]];
// Create an empty datastore //
var storeData = {
identifier: 'id',
label: 'id',
items: []
}
var store3 = new dojo.data.ItemFileWriteStore( {data : storeData} );
</script>
.
// PUT THIS IN THE <HTML> OF THE PAGE
<div id="grid" dojoType="dojox.grid.DataGrid" jsId="grid5" store="store3" structure="layoutItems" query="{ type: '*' }" clientSort="true" rowsPerPage="40"></div>
.
<script type="text/javascript">
function addItemToGrid(formdata) {
// THIS FUNCTION IS CALLED BY A DIALOG BOX AND GETS FORM DATA PASSED TO IT //
var jsonobj = eval("(" + dojo.toJson(formData, true) + ")");
var myNewItem = {
id: transactionItemID,
color: jsonobj.color
};
// Insert the new item into the store:
store3.newItem(myNewItem);
store3.save({onComplete: savecomplete, onError: saveerror});
}
</script>