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.
Related
I have a question about how I can search, for example, by name or surname in the INDEX view.
Is there any plugin or easy-to-use component that does not load the application too much?
Currently, I have a small form in index.ctp with one input field, where I enter what I want to search, and in controller have an if ($ this-> request-> is ('post')) after which to $this->Model->find adds condition WHERE. But I admit that this is not a nice way, it also reload the page.
This is the controller:
public function index()
{
if ($this->request->is('post')) {
$s = '%'.$this->request->getData('Search').'%';
$students = $this->Students->find('all')->where(['OR' => ['name LIKE' => $s, 'lastname LIKE' => $s]]);
$this->set('students', $this->paginate($students));
} else {
$students = $this->paginate($this->Students);
$this->set(compact('students'));
}
}
And this is the index.ctp:
<div class="input-group mb-3">
<?= $this->Form->button(__('<i class="fas fa-search"></i>'), ['escape' => false, 'class' => 'btn btn-primary']) ?>
<?= $this->Form->input('Search', ['type' => 'text', 'class' => 'form-control', 'label' => false]); ?>
<?= $this->Form->end() ?>
</div>
From what I can see you are either after a better solution to handle searching and/or a way of not reloading the page to display your search results.
If this isn't what you are after then please clarify your question to better outline what you would like you solution to look like.
You should be separating your searching out of your index function as that is only to display the content on that page. Adding conditions like you have will end up in you having a really long index function running your whole application based on the differences in the request, which isn't great.
Split out the searching into a separate function which will in turn create a new page for you to display your results.
public function index()
{
$students = $this->paginate($this->Students);
$this->set(compact('students'));
}
public function search()
{
$s = '%' . $this->request->getData('Search') . '%';
$students = $this->Students->find('all')->where(['OR' => ['name LIKE' => $s, 'lastname LIKE' => $s]]);
$this->set('students', $this->paginate($students));
}
This is well described in the tutorial on the CakePHP docs - CMS Tutorial - Creating the Articles Controller and can be related to your application as the index for you contains a form to pass search criteria to your application and the search function/page will then fetch the results and display them for you.
Don't forget to then alter your form to point it to the /search page. - Setting a URL for the Form
You will need to create a search.ctp file in your src/Template/ExampleController folder. Put your html code in there to display the results in a table or however you want to display the search results.
Finally you will need to add a route to your routes.php to allow the /search path in your application.
$routes->connect('/search', ['controller' => 'Example', 'action' => 'search']);
Now if you don't want the page to reload when you use your form then you have to use Ajax and JS/JQuery to make the request to your search method and display the results of the search function on the page dynamically. There are already a lot of good examples of this on stackoverflow and the web for using ajax and jquery for building tables from searches so I won't bother posting them here.
If you want a plugin/library solution then look at this tutorial on having search results displayed in a table using DataTables. - Search Using Datatables
install plugin https://github.com/FriendsOfCake/search
then in search configurations
$this->searchManager()
// Here we will alias the 'q' query param to search the `Students.name`
// field and the `Students.lastname` field, using a LIKE match, with `%`
// both before and after.
->add('q', 'Search.Like', [
'before' => true,
'after' => true,
'fieldMode' => 'OR',
'comparison' => 'LIKE',
'wildcardAny' => '*',
'wildcardOne' => '?',
'field' => ['name', 'lastname']
]);
In both cakephp-1.2 and cakephp-1.3 I have used the following code snippet in an element named head called from the blog layout:
$this->preMetaValues = array(
'title' => __('SiteTitle', true).' '.$title_for_layout,
'desc' => Configure::read('siteTitle').', '.Configure::read('siteSlogan'),
'keywords' => Configure::read('keywords'),
'type' => 'article',
'site_name' => __('SiteTitle', true),
'imageURL' => $html->url('/img/logo.png', true)
);
if(!isset($this->metaValues)){
$this->metaValues = $this->preMetaValues;
}
else{
$this->metaValues = array_merge($this->preMetaValues, $this->metaValues);
}
<?php echo $html->meta('description',$this->metaValues['desc']); ?>
<?php echo $html->meta('keywords', $this->metaValues['keywords']);?>
I used the above code to define or modify meta-tags values from the any view file. The preMetaValues is regarded as the default values. If there is any metaValues defined in the view, this code will modify it and make the metaValues ready to be used.
Now with cakephp-2.4, the described code generates the following error:
Helper class metaValuesHelper could not be found.
Error: An Internal Error Has Occurred.
Indeed, I don't know why CakePHP regards this variable as helper? and how could I fix this issue?
You can do it by setting the variable from your controller action:
$this->set('title_for_layout', 'Your title');
And then in the view, printing it with:
<title><?php echo $title_for_layout?></title>
You have an example of this at the documentation:
http://book.cakephp.org/2.0/en/views.html#layouts
Just treat them as any other variable.
Why you're using $this object? Can't you use a simple solution like this:
$preMetaValues = array(
'title' => __('SiteTitle', true).' '.$title_for_layout,
'desc' => Configure::read('siteTitle').', '.Configure::read('siteSlogan'),
'keywords' => Configure::read('keywords'),
'type' => 'article',
'site_name' => __('SiteTitle', true),
'imageURL' => $html->url('/img/logo.png', true)
);
if(!isset($metaValues)){
$metaValues = $preMetaValues;
}
else{
$metaValues = array_merge($preMetaValues, $metaValues);
}
<?php echo $html->meta('description',$metaValues['desc']); ?>
<?php echo $html->meta('keywords', $metaValues['keywords']);?>
Finally I have found the solution. It is simply about how to set a variable for the layout from a view. It seems that in earlier versions of cakephp the view was processed before the layout while now in cakephp-2.4 the layout is processed first, so any override of any variable defined in the layout from the view will not success.
Hence, the solution will depend on the set method of the view object something as follows:
//in some view such as index.ctp
$this->set('metaValues', array(
'title', 'The title string...',
'desc' => 'The description string...'
)
);
Also as Alvaro regarded in his answer, I have to access those variable without $this, i.e as local variables.
This answer is inspired from: Pass a variable from view to layout in CakePHP - or where else to put this logic?
so I've been trying to get select2Row to work for me forever and I just can't seem to get a hang of it. What I'm trying to do is provide the user with Tags that list a school/university name, while at the same time storing the value of said tag when I save the form. I've noticed that I cannot use both data and tags, else my drop down wont populate so that's not an option. Tags only seem to want text, rather than text and matching values. Any ideas?
<div class="row">
<?php
echo $form->select2Row($model, 'school_id', array(
'asDropDownList'=>false,
'options'=>array(
'tags'=>School::model()->schoolNames,
//'maximumSelectionSize'=>1,
'width'=>'297px',
'tokenSeparators'=>array(','),
),
));
?>
<?php echo $form->error($model,'school_id'); ?>
</div>
And here is the function for schoolNames
public function getSchoolNames()
{
$schools = array();
$result = $this->findAllBySQL("SELECT DISTINCT name FROM School");
foreach($result as $school){
$schools[] = $school->name;
}
return $schools;
}
I've tried using this instead, but the tags won't populate
public function getSchools()
{
$query = "SELECT id,name FROM School";
$results = $this->findAllBySQL($query);
return CHtml::listData($results, 'id', 'name');
}
So at the moment, select2Row is generating a list of tags using getSchoolNames() and that all works fine, except once you submit the form using those tags you'll get this
Please fix the following input errors:
School must be an integer.
Sorry for all the trouble, I'm still a little new to this. I'm sure the answer is probably right in front of me. Thanks either way =)
try this:
echo $form1->select2Row($model, 'school_id', array(
'data' => School::model()->schoolNames,
'multiple' => 'multiple',
'options' => array(
"width" => '70%',
),
));
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}');
$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.