Yii CJuiAutoComplete data from Ajax request - autocomplete

I have a task form for an application I am building which allows me to specify what contact it is assigned to. I had set up a dependent dropdown in Yii with the following code:
echo $form->dropDownList($model,'associationType',
array('none'=>'None','contact'=>'Contact','sale'=>'Sale','account'=>'Account',
'project'=>'Project','case'=>'Case'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('tasks/parseType'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#auto_complete', //selector to update
)
));
What I'm trying to do is use the CJuiAutoComplete widget with the dropDown specifying which array to grab. So the drop down is selected to contacts, it should get a list of contacts etc.
Here is what I have for the CJui widget
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name'=>'auto_select',
'source' => $names,
'options'=>array(
'minLength'=>'2',
'select'=>'js:function( event, ui ) {
$("#'.CHtml::activeId($model,'associationId').'").val(ui.item.id);
return false;
}',
),
));
The variable $names is just a placeholder for now, but in my controller method I pass it a JSON encoded array with id and name. Controller code:
public function actionParseType() {
//if(isset($_POST['TaskChild']['associationType'])){
//$type=$_POST['TaskChild']['associationType'];
$type='sale';
$sql = 'SELECT id, name FROM x2_'.$type.'s';
$cmd = Yii::app()->db->createCommand($sql);
$res = $cmd->queryAll();
echo CJSON::encode($res);
//}
}
Right now I'm forcing it to use "Sale" but I don't get anything when I call the method, and was wondering how I might go about fixing this. I'm still a little new to Yii so I've been mostly reading wiki/forum posts on how these kinds of thing are done. Any help is greatly appreciated, thanks!

Try something like this in your controller action:
$sql = 'SELECT people_id as id, CONCAT(first_name," ",last_name) as value, first_name as label FROM people WHERE first_name LIKE :qterm ORDER BY first_name ASC';
$command = Yii::app()->db->createCommand($sql);
$qterm = $_GET['term'].'%';
$command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
$result = $command->queryAll();
echo CJSON::encode($result); exit;
Then you can check it by using this in your widget 'options' array: 'select'=>'js:function(event, ui) { console.log(ui.item.id +":"+ui.item.value); }'

Related

WordPress API passing email argument issue

Using a WordPress REST API custom endpoint, I am attempting to get user data (or at least the user id) with the following code in the functions.php file:
function getUser(WP_REST_Request $request) {
global $wpdb;
$email = $request->get_param( 'email' );
$query = "SELECT * FROM wp_users WHERE user_email = $email";
$result = $wpdb->get_results($query);
return $result;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'myapi/v1', '/getcustomer/(?P<email>[^/]+)', array(
'methods' => 'GET',
'callback' => 'getUser'
) );
} );
Testing the function with the endpoint /wp-json/myapi/v1/getcustomer/joe#anymail.com it returns with empty brackets [ ]. Am I missing something here? Any help would be greatly appreciated.
There are multiple issues with your code:
You should encode your user emails or send it via POST method.
Your current query is open to SQL Injection
Your value must be enclosed in quotes. Now it translates to .. WHERE user_email = joe#anymail.com and that is SQL syntax error.
So your code should look like this:
$query = "SELECT * FROM wp_users WHERE user_email = %s";
$result = $wpdb->get_results($wpdb->prepare($query, $email));

Retrieve the user id who posts a single entry of Gravity Form

Suppose that I know the entry ID ($lead_id), how can I retrieve the user who creates that entry.
I try to
$lead = RGFormsModel::get_lead( $lead_id );
$form = GFFormsModel::get_form_meta( $lead['form_id'] );
$values= array();
foreach( $form['fields'] as $field ) {
$values[$field['id']] = array(
'id' => $field['id'],
'label' => $field['label'],
'value' => $lead[ $field['id'] ],
);
}
But the user data is not there. I check sql database, and the user data is in wp_rg_lead table, not in wp_rg_lead_detail table.
Can anybody please help?
The information in the *_rg_lead table is accessible in the array that's returned by the get_lead function. So
user_id = $lead['created_by']
Also note that it's better to use the Gravity Forms API for retrieving the entry, specifically the get_entry function:
GFAPI::get_entry( $entry_id )
which will return an Entry object.

cake php habtm select does not set selected values

Hello I have several troubles with HABTM and Form.
I am using CakePHP 2.3 and PHP 5.3.3
This is my code situation for the understanding of the scenario: Albums and Singles related with a HABTM relation. Albums cointains many Singles and Singles belongs to many Albums.
Model Album.php ( don't care about raisins: is my personal plugin for managing images )
App::uses('Raisin', 'Raisins.Model');
App::uses('PastryBehavior', 'Raisins.Model/Behavior');
class Album extends AppModel
{
public $name = 'Album';
public $actsAs = array(
'Tags.Taggable',
'Utils.Sluggable' => array(
'label' => 'title'
),
'Raisins.Pastry',
'SrEngine.Indexable',
'SrEngine.HitCounter'
);
public $hasOne = array(
'Image' => array('className' => 'Raisins.Raisin')
);
public $hasAndBelongsToMany = array(
'Single'
);
public $belongsTo = array(
'Users.User'
);
}
Controller AlbumsController.php ( edit part )
$this->request->data = $this->Album->read(null, $id);
$this->set('singles',$this->Album->Single->find('list'));
View
<?php echo $this->Form->input('Single',array('class' => 'span12','label' => 'Singoli' ) ); ?>
In the view I see the select populated from the values coming from the controller singles set, but the selected item, previously saved, is not highlighted.
Consider that in the database the habtm table contains the correct row populated with the data saved.
I read , somewehere in the middle, that some previous version of cake, prior to 2.3, used to have some problem related to habtm form select input.
I am very stuck at this because I have almost tried every known workaround without sorting any positive effect.
Any help, hint would be very appreciated.
Thanks in advance
Rudy

silverstripe dataobject searchable

I´m trying to have certain DataObjects (News) displayed in the default SearchResult Page. So the result should display normal Pages and News.
Is there an easy way to accomplish that in Silverstripe 3?
Or is it recommended to code it completely custom - I mean a custom controller/action which handles the search request and creates a result list, which I display then in a custom template?
I found this, but obviously search is disabled right now:
https://github.com/arambalakjian/DataObjects-as-Pages
Thx and regards,
Florian
I usually but together a custom search function after enabling FulltextSearchable. So in _config.php I would have
FulltextSearchable::enable();
Object::add_extension('NewsStory', "FulltextSearchable('Name,Content')");
replacing Name and Content with whatever DBField you want to be searchable. And each searchable DataObject have this in their class to enable search indexes (pretty sure this needs to be added and run dev/build before enabling the extension, and only works on MySQL DB).
static $create_table_options = array(
'MySQLDatabase' => 'ENGINE=MyISAM'
);
then in my PageController I have my custom searchForm and results functions.
Here is the search function that returns the search form, called with $search in the template:
public function search()
{
if($this->request && $this->request->requestVar('Search')) {
$searchText = $this->request->requestVar('Search');
}else{
$searchText = 'Search';
}
$f = new TextField('Search', false, $searchText);
$fields = new FieldList(
$f
);
$actions = new FieldList(
new FormAction('results', 'Go')
);
$form = new Form(
$this,
'search',
$fields,
$actions
);
//$form->disableSecurityToken();
$form->setFormMethod('GET');
$form->setTemplate('SearchForm');
return $form;
}
and here the custom results function to handle the queries...
function results($data, $form, $request)
{
$keyword = trim($request->requestVar('Search'));
$keyword = Convert::raw2sql($keyword);
$keywordHTML = htmlentities($keyword, ENT_NOQUOTES, 'UTF-8');
$pages = new ArrayList();
$news = new ArrayList();
$mode = ' IN BOOLEAN MODE';
//$mode = ' WITH QUERY EXPANSION';
//$mode = '';
$siteTreeClasses = array('Page');
$siteTreeMatch = "MATCH( Title, MenuTitle, Content, MetaTitle, MetaDescription, MetaKeywords ) AGAINST ('$keyword'$mode)
+ MATCH( Title, MenuTitle, Content, MetaTitle, MetaDescription, MetaKeywords ) AGAINST ('$keywordHTML'$mode)";
$newsItemMatch = "MATCH( Name, Content ) AGAINST ('$keyword'$mode)
+ MATCH( Name, Content ) AGAINST ('$keywordHTML'$mode)";
//Standard pages
foreach ( $siteTreeClasses as $c )
{
$query = DataList::create($c)
->where($siteTreeMatch);
$query = $query->dataQuery()->query();
$query->addSelect(array('Relevance' => $siteTreeMatch));
$records = DB::query($query->sql());
$objects = array();
foreach( $records as $record )
{
if ( in_array($record['ClassName'], $siteTreeClasses) )
$objects[] = new $record['ClassName']($record);
}
$pages->merge($objects);
}
//news
$query = DataList::create('NewsStory')->where($newsItemMatch);
$query = $query->dataQuery()->query();
$query->addSelect(array('Relevance' => $newsItemMatch));
$records = DB::query($query->sql());
$objects = array();
foreach( $records as $record ) $objects[] = new $record['ClassName']($record);
$news->merge($objects);
//sorting results
$pages->sort(array(
'Relevance' => 'DESC',
'Title' => 'ASC'
));
$news->sort(array(
'Relevance' => 'DESC',
'Date' => 'DESC'
));
//output
$data = array(
'Pages' => $pages,
'News' => $news,
'Query' => $keyword
);
return $this->customise($data)->renderWith(array('Search','Page'));
}
I add all the Page classes I want to be searched and that extend SiteTree in the $siteTreeClasses array, and the News parts can be pretty much copied for any other DataObjectI need searchable.
I am not saying this is the best solution and this can definitely be improved on, but it works for me and this might be a good stating point.
I have adapted #colymba's solution into a silverstripe module: https://github.com/burnbright/silverstripe-pagesearch
It allows setting the pagetype in the url.
You'll need to substantially overwrite SearchForm->getResults().
It uses Database->searchEngine(), but those are tailored towards SiteTree and Page classes.
The "proper" solution is to feed the data into a search engine like Solr or Sphinx.
We have the SS3-compatible "fulltextsearch" module for this purpose:
https://github.com/silverstripe-labs/silverstripe-fulltextsearch
It's going to take some upfront setup, and is only feasible if you can either host Solr yourself, or are prepared to pay for a SaaS provider. Once you've got it running though, the possibilities are endless, its a great tool!

Yii CJuiAutoComplete for Multiple values

I am a Yii Beginner and I am currently working on a Tagging system where I have 3 tables:
Issue (id,content,create_d,...etc)
Tag (id,tag)
Issue_tag_map (id,tag_id_fk,issue_id_fk)
In my /Views/Issue/_form I have added a MultiComplete Extension to retrieve multiple tag ids and labels,
I have used an afterSave function in order to directly store the Issue_id and the autocompleted Tag_ids in the Issue_tag_map table, where it is a HAS_MANY relation.
Unfortunately Nothing is being returned.
I wondered if there might be a way to store the autocompleted Tag_ids in a temporary attribute and then pass it to the model's afterSave() function.
I have been searching for a while, and this has been driving me crazy because I feel I have missed a very simple step!
Any Help or advices of any kind are deeply appreciated!
MultiComplete in Views/Issue/_form:
<?php
echo $form->labelEx($model, 'Tag');
$this->widget('application.extension.MultiComplete', array(
'model' => $model,
'attribute' => '', //Was thinking of creating a temporary here
'name' => 'tag_autocomplete',
'splitter' => ',',
'sourceUrl' => $this->createUrl('Issue/tagAutoComplete'),
// Controller/Action path for action we created in step 4.
// additional javascript options for the autocomplete plugin
'options' => array(
'minLength' => '2',
),
'htmlOptions' => array(
'style' => 'height:20px;',
),
));
echo $form->error($model, 'issue_comment_id_fk');
?>
AfterSave in /model/Issue:
protected function afterSave() {
parent::afterSave();
$issue_id = Yii::app()->db->getLastInsertID();
$tag; //here I would explode the attribute retrieved by the view form
// an SQL with two placeholders ":issue_id" and ":tag_id"
if (is_array($tag))
foreach ($tag as $tag_id) {
$sql = "INSERT INTO issue_tag_map (issue_id_fk, tag_id_fk)VALUES(:issue_id,:tag_id)";
$command = Yii::app()->db->createCommand($sql);
// replace the placeholder ":issue_id" with the actual issue value
$command->bindValue(":issue_id", $issue_id, PDO::PARAM_STR);
// replace the placeholder ":tag_id" with the actual tag_id value
$command->bindValue(":tag_id", $tag_id, PDO::PARAM_STR);
$command->execute();
}
}
And this is the Auto Complete sourceUrl in the Issue model for populating the tags:
public static function tagAutoComplete($name = '') {
$sql = 'SELECT id ,tag AS label FROM tag WHERE tag LIKE :tag';
$name = $name . '%';
return Yii::app()->db->createCommand($sql)->queryAll(true, array(':tag' => $name));
actionTagAutoComplete in /controllers/IssueController:
// This function will echo a JSON object
// of this format:
// [{id:id, name: 'name'}]
function actionTagAutocomplete() {
$term = trim($_GET['term']);
if ($term != '') {
$tags = issue::tagAutoComplete($term);
echo CJSON::encode($tags);
Yii::app()->end();
}
}
EDIT
Widget in form:
<div class="row" id="checks" >
<?php
echo $form->labelEx($model, 'company',array('title'=>'File Company Distrubution; Companies can be edited by Admins'));
?>
<?php
$this->widget('application.extension.MultiComplete', array(
'model' => $model,
'attribute' => 'company',
'splitter' => ',',
'name' => 'company_autocomplete',
'sourceUrl' => $this->createUrl('becomEn/CompanyAutocomplete'),
'options' => array(
'minLength' => '1',
),
'htmlOptions' => array(
'style' => 'height:20px;',
'size' => '45',
),
));
echo $form->error($model, 'company');
?>
</div>
Update function:
$model = $this->loadModel($id);
.....
if (isset($_POST['News'])) {
$model->attributes = $_POST['News'];
$model->companies = $this->getRecordsFromAutocompleteString($_POST['News']
['company']);
......
......
getRecordsFromAutocompleteString():
public static cordsFromAutocompleteString($string) {
$string = trim($string);
$stringArray = explode(", ", $string);
$stringArray[count($stringArray) - 1] = str_replace(",", "", $stringArray[count($stringArray) - 1]);
$criteria = new CDbCriteria();
$criteria->select = 'id';
$criteria->condition = 'company =:company';
$companies = array();
foreach ($stringArray as $company) {
$criteria->params = array(':company' => $company);
$companies[] = Company::model()->find($criteria);
}
return $companies;
}
UPDATE
since the "value" porperty is not implemented properly in this extension I referred to extending this function to the model:
public function afterFind() {
//tag is the attribute used in form
$this->tag = $this->getAllTagNames();
parent::afterFind();
}
You should have a relation between Issue and Tags defined in both Issue and Tag models ( should be a many_many relation).
So in IssueController when you send the data to create or update the model Issue, you'll get the related tags (in my case I get a string like 'bug, problem, ...').
Then you need to parse this string in your controller, get the corresponding models and assigned them to the related tags.
Here's a generic example:
//In the controller's method where you add/update the record
$issue->tags = getRecordsFromAutocompleteString($_POST['autocompleteAttribute'], 'Tag', 'tag');
Here the method I'm calling:
//parse your string ang fetch the related models
public static function getRecordsFromAutocompleteString($string, $model, $field)
{
$string = trim($string);
$stringArray = explode(", ", $string);
$stringArray[count($stringArray) - 1] = str_replace(",", "", $stringArray[count($stringArray) - 1]);
return CActiveRecord::model($model)->findAllByAttributes(array($field => $stringArray));
}
So now your $issue->tags is an array containing all the related Tags object.
In your afterSave method you'll be able to do:
protected function afterSave() {
parent::afterSave();
//$issue_id = Yii::app()->db->getLastInsertID(); Don't need it, yii is already doing it
foreach ($this->tags as $tag) {
$sql = "INSERT INTO issue_tag_map (issue_id_fk, tag_id_fk)VALUES(:issue_id,:tag_id)";
$command = Yii::app()->db->createCommand($sql);
$command->bindValue(":issue_id", $this->id, PDO::PARAM_INT);
$command->bindValue(":tag_id", $tag->id, PDO::PARAM_INT);
$command->execute();
}
}
Now the above code is a basic solution. I encourage you to use activerecord-relation-behavior's extension to save the related model.
Using this extension you won't have to define anything in the afterSave method, you'll simply have to do:
$issue->tags = getRecordsFromAutocompleteString($_POST['autocompleteAttribute'], 'Tag', 'tag');
$issue->save(); // all the related models are saved by the extension, no afterSave defined!
Then you can optimize the script by fetching the id along with the tag in your autocomplete and store the selected id's in a Json array. This way you won't have to perform the sql query getRecordsFromAutocompleteString to obtain the ids. With the extension mentioned above you'll be able to do:
$issue->tags = CJSON::Decode($_POST['idTags']);//will obtain array(1, 13, ...)
$issue->save(); // all the related models are saved by the extension, the extension is handling both models and array for the relation!
Edit:
If you want to fill the autocomplete field you could define the following function:
public static function appendModelstoString($models, $fieldName)
{
$list = array();
foreach($models as $model)
{
$list[] = $model->$fieldName;
}
return implode(', ', $list);
}
You give the name of the field (in your case tag) and the list of related models and it will generate the appropriate string. Then you pass the string to the view and put it as the default value of your autocomplete field.
Answer to your edit:
In your controller you say that the companies of this model are the one that you added from the Autocomplete form:
$model->companies = $this->getRecordsFromAutocompleteString($_POST['News']
['company']);
So if the related company is not in the form it won't be saved as a related model.
You have 2 solutions:
Each time you put the already existing related model in you autocomplete field in the form before displaying it so they will be saved again as a related model and it won't disapear from the related models
$this->widget('application.extensions.multicomplete.MultiComplete', array(
'name' => 'people',
'value' => (isset($people))?$people:'',
'sourceUrl' => array('searchAutocompletePeople'),
));
In your controller before calling the getRecordsFromAutocompleteString you add the already existing models of the model.
$model->companies = array_merge(
$model->companies,
$this->getRecordsFromAutocompleteString($_POST['News']['company'])
);