I have a problem integrating Yii and jQuery when trying to dynamically add fields generated by Yii to my form.
Namely, statically I use this code to have a dropdownlist on my form:
echo $form->label($model,Yii::t('candidates', 'Contact type'));
$options = CHtml::listData(HrpContactTypes::model()->findAll(),'id','type');
$ct = array();
$b=1;
for($i=0;$i<=count($options)-1;$i++) {
$ct[$b] = Yii::t('candidates', $options[$b]);
$b++;
}
echo $form->dropDownList($model,'contact_type_id',$ct,array('class'=>'form-control'));
and I use this code to have a text-input on my form:
echo $form->label($model,Yii::t('candidates', 'Contact')); ?>
echo $form->textField($model,'contact', array('required'=>'required', 'class'=>'form-control' ));
Then, I use this code to dynamically add elements to my form:
$('#addContact').click(function() {
$('#row').append(
'<br><div class="col-md-6">contact type</div><div class="col-md-6">contact</div>'
);
return false;
});
MY QUESTION IS: HOW TO DYNAMICALLY ADD YII DROPDOWNLIST AND YII TEXT-INPUT WITH THE HELP OF JQUERY?
At first please pay attention on coding.
Second parameter of CActiveForm::label() must be attribute, and translate it you must in your model class (overriding method attributeLabels()), not in form:
public functions attributeLabels() {
return array(
'candidates' => Yii::t('candidates', 'Contact type'),
ATTRUBUTE_NAME => ATTRIBUTE_LABEL
);
}
Read about loops in php. Instead of declaring additional varaible $b you can use loop varaible $i, also you get values from $optios starting from 1, so your last element of $ct always null, I think you want to write this:
$options = CHtml::listData(HrpContactTypes::model()->findAll(),'id','type');
$ct = array();
for($i=0; $i<count($options); $i++) {
$ct[$i+1] = Yii::t('candidates', $options[$i]);
}
Thanks.
Related
I have managed to get this code to work for an application -- http://twitter.github.io/typeahead.js/ but, the problem I have run into, is that I need to be able to re-load the data. I would rather not duplicate the code to do this, although it's an option, it seems kind of silly. I have inserted some PHP into my JavaScript to create an array for the dropdown list, and it works great. But if I stuff it into a function, and then try to call the function in the document open, it doesn't work (nothing appears to happen).
$(document).ready(function()
{
// call function when page loads(?)
getAwards();
}); // end document.ready ...
This is the PHP code, if I comment out the JavaScript function parts it runs and the typeahead code sees the value of the array. If I put it into the function, it doesn't execute despite being called above, and I have no data for the typeahead code ...
function getAwards(
{
// build array for use with typeahead:
<?php
$sql_statement = "select title from awards order by title desc limit 1";
$aw_result = mysqli_query( $connect, $sql_statement );
$aw_row = mysqli_fetch_array( $aw_result );
$last_award = $aw_row["title"];
// need to rewind table:
mysqli_data_seek( $aw_result, 0);
// start from the top:
$sql_statement = "select title from awards order by title";
$aw_result = mysqli_query( $connect, $sql_statement );
$count = 0;
$out = 'awards = [';
while ( $aw_row = mysqli_fetch_array( $aw_result ) )
{
// the quotes deal with forcing this to handle
// branch names with apostrophes in them ...
$count++;
$out .= '"'. $aw_row["title"] . '"';
if( $aw_row["title"] != $last_award )
{
$out .= ',';
}
}
$out .= ']';
echo $out . "\n";
?>
})
I need to be able to update the data, and reload the list while working on the form (I am working that out in my fuzzy brain, but anyway I'll get to that -- currently intend to click a button to update the list used by the typeahead, which is why I want a function ...)
Any suggestions are gratefully accepted. I am at a loss ...
I've got a complicated little problem here.
I'm building a WordPress plugin where I select a "parent" post (of a custom type that I made called 'step') and then an AJAX function shows a new select bar with all of the children of that parent. I do this by outputting the new and elements in the PHP file that's called in the AJAX function. This works, but now I want to repeat the process to run a function from the same JQuery file when this new outputted element is added to the page. (See Javascript code)
Main php plugin file (in a folder within the plugin directory):
<?php
/*
Plugin Name: n8jadams Step by Step Plugin (WIP)
Plugin URI:
Description:
Author: Nathan James Adams
Author URI: http://nathanjamesadams.com
Version: 0.0.1a
*/
//Exit if accessed directly
if(!defined('ABSPATH')) {
exit;
}
//My custom post type, it works fine
require_once(plugin_dir_path(__FILE__).'n8jadams-step-funnel-cpt.php');
require_once(plugin_dir_path(__FILE__).'n8jadams-ajax.php');
//Add my javascript
function n8jadams_init_javascript() {
wp_register_script('n8jadams_javascript', plugin_dir_url(__FILE__).'n8jadams-scripts.js', array('jquery'),'1.1', false);
wp_enqueue_script('n8jadams_javascript');
}
add_action('wp_enqueue_scripts', 'n8jadams_init_javascript');
//Adds a plugin menu to the wordpress sidebar
function n8jadams_add_plugin_menu() {
add_menu_page('', 'Steps Settings', 4, 'steps-settings', 'n8jadams_steps_settings', '');
}
add_action('admin_menu', 'n8jadams_add_plugin_menu');
//The actual function for the menu page
function n8jadams_steps_settings() {
//Access the database and the tables we want
global $wpdb;
$posts = $wpdb->prefix.'posts';
//Get the user id
$user = wp_get_current_user();
$userid = $user->ID;
//Initialize javascript (it works here!)
n8jadams_init_javascript();
/* Get all the parents */
$parentsquery = "
SELECT `ID`, `post_title`
FROM $posts
WHERE `post_author` = $userid
AND `post_parent` = 0
AND `post_status` = 'publish'
AND `post_type` = 'step'
";
$parentsarray = $wpdb->get_results($parentsquery);
?>
<h4>My Forms:</h4>
<select id="parentselect">
<option id="-1"> - Select Your Step Form - </option>
<?php
//output the parents
for($i=0;$i<sizeof($parentsarray);$i++) {
echo '<option id="'.$parentsarray[$i]->ID.'">'.$parentsarray[$i]->post_title.'</option>';
}
?>
</select>
<div id="displayChildren"></div>
<?php
}
?>
Javascript (n8jadams-scripts.js):
(function($){
$('#parentselect').change(function(s) {
var thisID = s.target[s.target.selectedIndex].id;
var outputDisplay = document.getElementById('displayChildren');
if(thisID != '-1') {
$.ajax({
type: 'POST',
url: 'admin-ajax.php',
data: {
action: 'n8jadams_get_children',
id: thisID
},
success: function(response){
if(response == "") {
outputDisplay.textContent = "This form has no children. Add them in the sidebar menu of this step form.";
} else {
outputDisplay.innerHTML = response;
}
},
error: function(errorThrown) {
alert(errorThrown);
}
});
} else {
outputDisplay.textContent = '';
}
});
// I want this function to work
/*
$('#childselect').change(function(t) {
console.log("test");
});
*/
})(jQuery);
PHP file called by AJAX (n8jadams-ajax.php):
<?php
function n8jadams_get_children() {
//Get the id of the parent
$parent_post_id = $_POST['id'];
//Sanitize the input (Added after question was answered)
$parent_post_id = preg_replace("/[^0-9]/","",$parent_post_id);
//Access database
global $wpdb;
$posts = $wpdb->prefix.'posts';
$user = wp_get_current_user();
$userid = $user->ID;
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
//Retrieve the children associated with this parent
$childrenarray = $wpdb->get_results($childrenquery);
//Initialize Javascript (it doesn't work here!)
n8jadams_init_javascript();
if(!empty($childrenarray)) { ?>
<h4>My Steps:</h4>
<select id="childselect">
<option id="-1"> - Select Your Step - </option>
<?php
//output the children of the parent
for($i=0;$i<sizeof($childrenarray);$i++) {
echo '<option id="'.$childrenarray[$i]->ID.'">'.$childrenarray[$i]->post_title.'</option>';
} ?>
</select>
<?php wp_die();
}
}
add_action('wp_ajax_n8jadams_get_children', 'n8jadams_get_children');
add_action('wp_ajax_nopriv_n8jadams_get_children', 'n8jadams_get_children');
?>
Screenshot of Plugin Menu
I cannot figure out why my javascript file isn't working in the PHP file that's called by AJAX. Maybe the vast wisdom of the StackOverflow can help me. Thanks for the help in advance. :)
You are hooking into wp_enqueue_scripts, which is only run for the frontend of Wordpress (the part the average visitor sees). If you want to load a script into wp-admin, the backend of Wordpress, use the admin_enqueue_scripts action.
Since this code does not work in /wp-admin/, you don't need to use admin_enqueue_scripts. I guess the whole problem would be that you are attaching a handler to $('#childselect'), while no such element exists on the page at that time. Use deferring with $(..).on(..):
$(document).on('change', '#childselect', function(e) {
//Black magic
});
Side note: As already mentioned in the comments, the following part contains an unsanitised variable which will allow an attacker to perform sql injections.
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
Use WP_Query if at all possible. If this is only used from the backend of Wordpress, don't use wp_ajax_nopriv_*, because users that are not logged in into your site have no right to use that anyway.
I have created a list, generated from a query, that works (no problem here).
What i would like to do is to trigger an event (probably with jQuery, that I know little about) that would set a php variable.
Let's say I have a table with two columns, 'column 1' and 'column 2'.
The list has various links with the valor of 'column 2' displayed on them.
I want that, as you click to one of those links, you could set a valor to a variable that equals to the valor in 'column 1' of that row.
This is what I wrote in my index page:
<div class="example">
<?php
$test = new Test();
$list = $test->getValors($user_id);
echo '<div id="mylist">';
foreach ($list as $element) {
echo '' . $element->COLUMN2 . '';
}
echo '</div>';
$variable = ?;
?>
</div>
I have nothing in my JavaScript file about it because I don't know how to begin.
Can you give me some directions?
EDIT
I resolved partially, even if this is not complete, i include my new code:
index.php
<?php
$test = new Test();
$list = $test->getValors($user_id);
echo '<div id="mylist">';
foreach ($list as $element) {
echo '' . $element->COLUMN2 . '';
}
echo '</div>';
$variable = ?;
?>
Javascript
$(document).ready(function () {
$("a.pointer").click(function() {
var variablename = $(this).attr("id");
$.post("ajax/filewithajax.php", {"postname": variablename});
$("#content").load("ajax/filewithajax.php");
});
});
You could put a event onclick on <a> and call a php function in a other page with jQuery (search about ajax). The php function could return a value that you can use in your main page.
I found a couple of similar questions but nothing with the same "variables" so here we go:
I have a simple form where I enter a name and I need the rest of the form to be completed automatically (ID).
Fetching the data in the DB is not an issue, I'm able to return Json using PHP (Search.php):
//get search term
$searchTerm = $_GET['term'];
//get matched data from table
$query = $db->query("SELECT * FROM info_employer WHERE Prenom LIKE '%".$searchTerm."%' ORDER BY Prenom ASC");
while ($row = $query->fetch_assoc()) {
$data[] = array( Nom => $row['Prenom'] . ' ' . $row['Nom'], Num => $row['Num'] );
}
//return json data
echo json_encode($data);
This give me an array that look like this:
[{"Nom":"Andre Nadeau","Num":"104J"},{"Nom":"Andre Potvin","Num":"130J"},{"Nom":"Andre Thibodeau","Num":"91J"}]
Friends told me that I should use Jquery and Ajax to use this array to fill my form but I have 2 issue.
First If I return an Array instead of "just the name" my autocomplete form don't work anymore. It give me X numbers of blank space (depending the number of results).
And of course my biggest problem is that i'm not able to send the ID (Num) in the form
Javascript i'm using to autocomplete the name :
<script>
$(function() {
$( "#Nom" ).autocomplete({
source: 'Search.php',
})
})
</script>
You need to change the return object to make it match the spec here
$data[] = array( "label" => $row['Prenom'] . ' ' . $row['Nom'], "value" => $row['Num'] );
This should result in an array of objects with a 'label' and 'value' key. This will work with your autocomplete.
This is my first time working with php. I was trying to optimize js in a website where I saw headscript() to append js file.
echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js');
In this I am trying to add an attribute the script tag appended
$this->headScript()->setAllowArbitraryAttributes(true);
echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js',
I also tried
$this->headScript()->setAllowArbitraryAttributes(true);
echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js',$attrs = array("async" => "true"))
array("async" => "true"));
php portion in the file
<?php
$this->headScript()->setAllowArbitraryAttributes(true);
echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js', $attrs = array("async" => "true"));
?>
I expected output to be
<script async="true" src="/js/image-gallery/jquery.simplemodal.1.4.4.min.js"></script>
Instead I got
<script type="Array" src="/js/image-gallery/jquery.simplemodal.1.4.4.min.js"></script>
How to solve it? I was not able to find any samples where attributes are added via headscript();
You need to pass the attributes as the third argument
$this->headScript()->appendFile(
'/js/image-gallery/jquery.simplemodal.1.4.4.min.js',
null,
array('async' => 'true', 'foo' => 'bar')
);
null here is the 'type' attribute, which will default to text/javascript
Looks like you are using Zend framework. If so please refer HeadScript Helper
You need to pass the attributes as $attrs = array()
appendFile($src, $type = 'text/javascript', $attrs = array())
So your code should be
UPDATED CODE
echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js', $type = 'text/javascript', $attrs = array("async" => "true"));
instead of
echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js', array("async" => "true"));
Arbitrary attributes are disabled by default. To allow such attributes, you can enable them via the setAllowArbitraryAttributes() method:
$this->headScript()->setAllowArbitraryAttributes(true);
Then
echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js', null, array("async" => "true"));