JavaScript into Drupal Module - php

I'm trying to implement a JavaScript script into a Drupal 7 module and for some reason I keep getting this error here: "Parse error: syntax error, unexpected T_ECHO, expecting ')'"
I've been attempting this for a few hours now, but I'm just at a loss. Any help would be so greatly appreciated.
My code block indented to the far right. The other code is part of a module in Drupal 7 for your reference.
$node->content['actions'] = array(
'#theme' => 'links',
'#prefix' => '<div id="match-actions">',
'#suffix' => '</div>',
'#links' => _match_actions($node),
echo '<script type="text/javascript">'
, 'croll();'
, 'troll();'
, '</script>';
'#attributes' => array(
'class' => array('links', 'match-actions'),
),
'#heading' => t('Match actions'),
'#weight' => -10,
);
The JavaScript I'm trying to insert (as you can see my attempt in the echo above) is
function class_roll() {
// Car Classes
var classes = ["B", "A", "S", "R3", "R2", "R1"],
classToUse = classes[Math.floor(Math.random() * classes.length)];
document.getElementById("croll").innerHTML = classToUse ;
}
function track_roll() {
var tracks = ["Clear Springs Circuit", "Festival North Circuit", "Beaumont Circuit", "Finley Dam Circuit", "Gladstone Circuit", "Clifton Valley Trail", "Gladstone Trail", "Red Rock Descent", "Red Rock Hill Climb"],
trackToUse = tracks[Math.floor(Math.random() * tracks.length)];
document.getElementById("troll").innerHTML = trackToUse ;
}
What exactly am I doing wrong? I've been searching around Stack and all over the net which has enabled me to try different syntaxes, but I just can't get it to work. I'm not an expert in JS and PHP, but I'm trying to learn :). Again, any help is REALLY appreciated.
P.S. - In HTML terms, what I'm trying to do is this:
<p id="croll">Some text here</p>
<p id="troll">Some text here</p>
<button onclick="class_roll(); track_roll();">Class Roll</button>
but it would be great if instead of doing an onclick type of PHP action, it would be an onload type of event, but it would only onload for the first time and stick there and remain static.

You can't put an echo inside of an array.
You should just be able to do:
$links = _match_actions($node);
$links[] = '<script type="text/javascript"> croll(); troll(); </script>'
$node->content['actions'] = array(
'#theme' => 'links',
'#prefix' => '<div id="match-actions">',
'#suffix' => '</div>',
'#links' => $links,
'#attributes' => array(
'class' => array('links', 'match-actions'),
),
'#heading' => t('Match actions'),
'#weight' => -10,
);

As HorusKol said you cannot directly call a JavaScript function inside your module. The reason being modules are written in PHP, and one cannot call functions of other programming language into one.
If you wish to insert JavaScript code, you should use the function drupal_add_js() to do so.
So, you could replace your echo with the following:
echo drupal_add_js('croll();troll();','inline');

The better method, that won't break with things like Drupal AJAX, is to use Drupal behaviors.
(function ($) {
Drupal.behaviors.myModuleName = {
attach : function (context, settings) {
$(".match-actions", context).once('match-actions', function(){
croll();
troll();
})
}
}
})(jQuery);
Place that in a js file and load it with drupal_add_js(drupal_get_path('module', '{my module name}') . '{js file name}');

Related

Correct radio syntax (not checkbox)

I have this syntax to provde a series of checkboxes. This works fine, however no matter what syntax I use to get radios I get nothing, just a blank space.
I've tried 'type' => 'radio', and tried 'type' => 'radiogroup'.
This what I'm using now:
array(
'type' => 'checkbox',
"holder" => "div",
"class" => "",
"heading" => __("Choose your cheese topping", 'rbm_menu_item'),
'param_name' => 'cheesbox',
'value' => array( 'Cheddar'=>'Chedder', 'Gouda'=>' Gouda', 'Bleu'=>' Bleu'),
"description" => __("<br /><hr class='gduo'>", 'rbm_menu_item')
),
Any ideas? Is there a different way to get radios instead of checkboxes?
if you are using visual composer (WPBakery Page Builder) try this:
vc_add_shortcode_param( 'simple_radio', 'xyz_function' );
function xyz_function($param, $value){
if(!empty($value)){
$hval = $value;
}
else{
$hval = '';
}
$ret = '<input type="hidden" value="'.$hval.'" id="xyz'.$param['param_name'].'" name="'.$param['param_name'].'" class="wpb_vc_param_value wpb-input">';
foreach($param['value'] as $key => $p){
if($value==$p){
$checked = ' checked="checked"';
}
else{
$checked = '';
}
$ret.='<div><input type="radio" name="xyz'.$param['param_name'].'" id="'.$param['param_name'].$p.'" value="'.$p.'" class="xyz-vc-radio'.$param['param_name'].'" style="width:auto; margin-right:5px;"'.$checked.'> <label for="'.$param['param_name'].$p.'">'.$key.'</label></div>';
}
$ret.='<script>
jQuery(".xyz-vc-radio'.$param['param_name'].'").change(function(){
var s = jQuery(this).val();
jQuery("#xyz'.$param['param_name'].'").val(s);
});
</script>';
return $ret;
}
I believe that this code, having done some Googling and searching through documentation, is from Visual Composer for WordPress.
It looks like this is an array to be passed to vc_map()'s params key to add your shortcode to the Visual Composer content elements list.
Looking through the vc_map documentation, it looks as if no form of radio buttons exist within Visual Composer, unfortunately.
You could create your own param type but this seems beyond the scope of this answer. Do feel free to comment if you'd like me to go into more detail or ask another question. Hope this helps!

Highlight search result in cakephp

as the title says I need to highlight the input string of a search in the results, I mean if I look for "ome" the results should look like this:
c ome
s ome
Jer ome
s ome one
etc.
Searching on the documentation I have found that I need to activate the "Text" helper and that I should have a code similar to this:
echo $this->Text->highlight($string);
Even though I've tried many possibilities, I can not make it work, I know "Text" helper is working because this works for me at View/Users/index.ctp:
echo $this->Text->autoLinkEmails(h($user['User']['email']));
if it helps, this is the code I've generated for the search which works correctly:
file: Model/Oldcaterm.php
public $actsAs = array(
'Search.Searchable'
);
public $filterArgs = array(
'entry' => array(
'type' => 'like',
'field' => array('entry', 'lemma_tag')
),
'lemma_tag' => array(
'type' => 'like',
'field' => array('entry', 'lemma_tag')
),
);
file: Controller/OldcatermsController.php
public function index() {
$this->Oldcaterm->recursive = 0;
$this->Prg->commonProcess();
$this->Paginator->settings['conditions'] = $this->Oldcaterm->parseCriteria($this->Prg->parsedParams());
$this->set('terms', $this->Paginator->paginate());
}
file: View/Oldcaterms/index.ctp
<?php
echo $this->Form->create(null,array());
echo $this->Form->input('entry', array('label' => 'Cerca coincidència'));
echo $this->Form->end(__('Submit'));
?>
I have read and try many differents ways, but I'm not able to make it work, can somebody please guide me a little, I have found next example at the documentation:
// called as TextHelper
echo $this->Text->highlight(
$lastSentence,
'using',
array('format' => '<span class="highlight">\1</span>')
);
// called as String
App::uses('String', 'Utility');
echo String::highlight(
$lastSentence,
'using',
array('format' => '<span class="highlight">\1</span>')
);
But I don't find the way to make it fit into my code
Thanks in advance.
After a few studies, I realized the css style is not there. Right click on your browser and explore the source code, if it shows <span class="highlight">Your Text Here</span> then everything is just right. Just add followings code to your CSS file
.highlight{
background-color: #FFDF00; /* <-- Choose what colour you want to use. Here is Golden Yellow */
}
If you still have any problem, please share in the comment.

Drupal 7 collapsible fieldset issues with ajax

I am sending data via ajax to my PHP callback function inside my custom module... Everything is working great. The problem I am having is: the html i am returning and rendering in the ajax complete funciton is composed of fieldsets which wont expand/collapse. Things i have tested :
1). If I render the same html ( fieldsets ) into one of the custom blocks in that same module, they work great, the collapse and expand.
2). I have tried including this inside the callback function,
drupal_add_js('misc/form.js');
drupal_add_js('misc/collapse.js');
inside the fieldset render array,
return array(
'#type' => 'fieldset',
'#title' => t($title),
'#attributes' => array(
'class' => $class,
),
'#attached' => array(
'js' => array(
'misc/form.js',
'misc/collapse.js',
),
),
);
The
$class
variable contains collapsed and collapsible. I have also tried using
#theme => 'fieldset'
Instead of #type => 'fieldset'
the javascript files
misc/collapse.js
misc/form.js
are already being included from a different function inside my module. And looking at the source of the page, are indeed being included to the head of the page.
This has to be related to bringing them in via ajax, I know when you bring elements into the document via ajax, in-order to set events for those new elements you have to use
$(document).on('event', 'class', function(){
//code here
});
and I am wondering if this could be the reason that the fieldsets wont collapse/expand.
If you get data with AJAX with jQuery once you have to use Drupal.behaviors like this:
Drupal.behaviors.MYBEHAVIOR = {
attach: function (context, settings) {
$('MYELEMENT.MYBEHAVIOR', context).once('MYBEHAVIOR', function () {
// Apply the MYBEHAVIOR effect to the elements only once.
});
}
};
See more at the js documentation https://drupal.org/node/756722

trying to load a content inside div with jquery using CAKEPHP

Ok i have been looking for a while now... and i wasnt able to find nothing related to jquery and cakephp when loading content to a div using the helper $this->Js->link... so i decided to post my question here in this awesome site... my first question and its so silly (i guess).
So... mechanics works fine, i mean.. it loads the content into a div called "algo" but now i try to add some effects (fadein) and im not being able to find the correct syntaxys for this! im brand new with cake... just 1 month old using it.
How do i add "fadeIn" effect when showing this damn div? i have tried lots of things but so far nothing makes the div load content with fadein effect whatsoever...
echo $this->Js->link('Categoria 1', array('controller' => 'Categories', 'action' => 'categorias1'), array('update' => '#algo'));
this perfectly loads a bunch of pictures that i have on category 1 inside the div that im asking... what should i do to add fadeIn effect? i have added some crazy things to see if they work but... nope... no luck
i have even tried this crazy one:
echo $this->Js->link('Categoria 1', array('controller' => 'Categories', 'action' => 'categorias1'), array('update' => '#algo', array('effect' =>array('fadeIn', array('speed' => 'slow'), true))));
any help will be apreciated! nobody shows examples of divs with cakephp.. or at least i wasnt able to find one that suits my needs!
great site by the way! it helped me a lot all this years!
i finally manage myself to accomplish what i was trying to do and i want to share with you guys what i did:
echo $this->Js->link('categoria 1', array('controller' => 'Categories', 'action' => 'categorias1'),array('update' => '#categorias', 'evalscripts' => true, 'before' => $this->Js->get('#algo,#categorias2')->effect('fadeOut', array('buffer' => false)), 'complete' => $this->Js->get('#categorias')->effect('fadeIn', array('buffer' => false))));
This huge piece of code is doing what i was expecting to, i also have added some editing to my jquery helper in order to pass them more than one div so i can have them all refreshed at the same time.
if you guys want to hack your helper here is the code:
cake/libs/view/helpers/jquery_engine.php
find this line:
$success .= $this-jQueryObject . '("' . $options['update'] . '").html(data);';
and have it replaced with:
if(is_array($options['update'])){
$success .= 'var temp = ' . $this->jQueryObject . '(" <div/>").html(data);';
foreach($options['update'] as $divId){
$success .= $this->jQueryObject . '("' . $divId . '").html(' . $this->jQueryObject . '("' . $divId . '", temp).html());';
}
} else {
$success .= $this->jQueryObject . '("' . $options['update'] . '").html(data);'; //linea que ya estaba
}
//termina agregado
As suggested by Dunhamzzz, I write all my jQuery by hand and never use the helpers. There doesn't seem to be any point tbh.
One useful tip, pass the base URL and any other useful cake variables into your page as a javascript variable. Add this to your layout:
<?php
$baseUrl = Router::url('/');
echo $this->Html->scriptBlock(<<<EOJS
var baseUrl = '{$baseUrl}';
EOJS
); ?>

php sprintf not working as expected

$actions = array(
'EDIT' => sprintf('Edit',
'abf_cm',
'edit_course',
$item['course_id'],
'thickbox edit-box',
'edit_'.$item['course_id']
),
'DELETE' => sprintf('Delete','course_management','do_process','delete',$item['course_id']),
);
In doing so, the edit part is not being displayed.Am i doing anything wrong.
I also tried using the placeholders
'EDIT' => sprintf('Edit',
'abf_cm',
'edit_course',
$item['course_id'],
'thickbox edit-box',
'edit_'.$item['course_id']
),
but still no results. I also noticed that when i remove the class and id attributes in the earlier version, then it works fine.
Can you please give me a satisfactory explanation of this and tell me where am i doing wrong.
EDIT:
Im using this inside Wordpress for creating custom table using WP_List_Table class
function column_course_name($item ) {
//Build row actions
$actions = array(
'EDIT' => sprintf('Edit',
'abf_cm',
'edit_course',
$item['course_id'],
'thickbox edit-box',
'edit_'.$item['course_id']
),
'DELETE' => sprintf('Delete','book_management','do_process','delete',$item['course_id']),
);
//Return the title contents
return sprintf('%1$s%3$s',
/*$1%s*/ strlen($item['course_name'])>0?$item['course_name']:'<span style="color:silver">(No Name)</span>',
/*$2%s*/ $item['course_id'],
/*$3%s*/ $this->row_actions($actions) //row_actions is a method in this class
);
}
update:
Well, its strange to mention but the code works when i use a single class( ie when i delete the space between the two classes for the tag) .
Any thoughts?
Dipesh, maybe you have errors in the code around this snippet.
Try to check your code in isolation. I copied your code to the separate .php script with little set-up and checked $actions array with print_r, like this:
edit_array.php
<?php
$item = array();
$item['course_id'] = 1;
$actions = array(
'EDIT' => sprintf('Edit',
'abf_cm',
'edit_course',
$item['course_id'],
'thickbox edit-box',
'edit_'.$item['course_id']
),
'DELETE' => sprintf('Delete','course_management','do_process','delete',$item['course_id']),
);
print_r($actions);
I ran this script from console and got the following results:
$ php edit_array.php
Array
(
[EDIT] => Edit
[DELETE] => Delete
)
Generated link for $actions['EDIT'] is HTML valid, so one can safely conclude that your code itself is working fine, and error lies somewhere else.

Categories