Using Bing Custom Search API with Drupal 7 - drupal-7

We are planning to use Hosted UI version of Bing Search and have found it only supports query parameter 'q'. This parameter cannot be used with Drupal as it clashes with Drupal standard parameter which is also 'q'.
Is there anyway we can still use Bing Search Hosted UI without changing Drupal parameter 'q'?
Thanks

Reiterating the correct answer based on the above comments with #user2574948. Just replace YOUR_QUERY, YOUR_KEY, and YOUR_CUSTOMCONFIG and it works.
$endpoint = 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search';
$term = 'YOUR_QUERY';
$headers = "Ocp-Apim-Subscription-Key: YOUR_KEY\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&customconfig=YOUR_CUSTOMCONFIG&responseFilter=Webpages&mkt=en‌​-us&safesearch=Moder‌​ate", false, $context);

Try using Bing search module.
It provides a search tab which pulls results from the Bing web service. The search query can be limited to a set of sites, and various advanced search query strings can be used (or appended to all search queries).

Related

TaxonomyFields in SPFx

Currently I'm creating a new form in SPFx. When reading the fields of the list there is an taxonomyField.
I'm using the PnP Taxonomy control to display the taxonomy labels.
I would like to get the termset id from the taxonomy field and using the following code
var taxField = field as SP.Taxonomy.TaxonomyField;
ctx.load(taxField);
await new Promise((resolveTax, rejectTax) => {
ctx.executeQueryAsync(()=> {
let termSetID = taxField.get_termSetId();
console.log(termSetID);
resolveTax();
}, (sender,args) =>{
console.log("Could not retrieve taxonomyfield termsset id: " + args.get_message());
rejectTax();
});
});
}
I Always receive the following error:
TypeError: Cannot read property 'TaxonomyField' of undefined
at eval (eval at Type.parse (https://...sharepoint.com/_layouts/15/MicrosoftAjax.js:5:10143), :1:13)
at Function.Type.parse (https://...sharepoint.com/_layouts/15/MicrosoftAjax.js:5:10143)
at SP.ClientRequest.$3K_0 (https://...sharepoint.com/_layouts/15/SP.Runtime.js:2:51794)
at Array. (https://...sharepoint.com/_layouts/15/MicrosoftAjax.js:5:307)
at https://...sharepoint.com/_layouts/15/MicrosoftAjax.js:5:51370
at Sys.Net.WebRequest.completed (https://...sharepoint.com/_layouts/15/MicrosoftAjax.js:5:89652)
at XMLHttpRequest._onReadyStateChange (https://...sharepoint.com/_layouts/15/MicrosoftAjax.js:5:84251)
Anybody a suggestion to fix this?
I suggest to use open source tools to work with SharePoint's Taxonomy, for example react-taxonomypicker
This is an elegant Taxonomy Picker control built with TypeScript for React. Initially built for use in Office 365 / SharePoint.
Features:
Retrieve Terms from a Term Set by Term Set GUID.
Support for large Term Set using Async mode
Use SP.Taxonomy.js
Use Promise (polyfill it if needed IE)
You can test it here: https://jquintozamora.github.io/react-taxonomypicker/

how to add conditions in treeList custom finder in cakephp 3

I am using TreeBehavior for generate tree structure using custom finder treeList custom finder
$this->Categories->find('treeList',['spacer' => '__']);
Now how can i add some conditions like "isactive" =>true. I have checked the documentation there are only 3 param. unable to find the condition param
Thanks in advance
That's less of a "custom" finder, more of a built-in one, given that it ships with the CakePHP core.
That being said, conditions can be added the same way as with any other finder, that is, either via the conditions option passed to the second argument of the find() method, or via the query builders where() method.
Quote from the docs:
Once you’ve started a query you can use the Query Builder interface to
build more complex queries, adding additional conditions, limits, or
include associations using the fluent interface.
// In a controller or table method.
$query = $articles->find('all')
->where(['Articles.created >' => new DateTime('-10 days')])
->contain(['Comments', 'Authors'])
->limit(10);
You can also provide many commonly used options to find(). This can
help with testing as there are fewer methods to mock:
// In a controller or table method.
$query = $articles->find('all', [
'conditions' => ['Articles.created >' => new DateTime('-10 days')],
'contain' => ['Authors', 'Comments'],
'limit' => 10
]);
Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Using Finders to Load Data

How to strip HTML from a field in drupal views

I am trying to add a function to that strips the html from a field in drupal views. I found a function for sql server called "udf_StripHTML" that does that.
http://blog.sqlauthority.com/2007/06/16/sql-server-udf-user-defined-function-to-strip-html-parse-html-no-regular-expression/
I am using the following code:
/**
* Implements hook_views_query_alter().
*/
function cviews_views_query_alter(&$view, &$query) {
// Add a strip html tags from content.
$fields = array('field_data_body.body_value');
foreach ($query->where as $key1 => $value) {
foreach ($value['conditions'] as $key2 => $coditions) {
if (in_array($coditions['field'], $fields)) {
$query->where[$key1]['conditions'][$key2]['field'] = 'dbo.udf_StripHTML(' . $coditions['field'] . ')';
}
}
}
}
When views module converts the query object to a string the field become
from:
'dbo.udf_StripHTML(field_data_body.body_value)';
to:
[dbo].[udf_StripHTMLfield_data_body.body_value]
My question is, how can I add a function there?
Thank you,
You are going way too deep here friend. I'm going to assume that you're using Drupal 7, but for Drupal 8 this should be similar (since views is in core for both).
A few things about your approach:
That function is a user defined function which means that it needs to be defined at a much lower-level (in the SQL database) before you can use it in your query.
This is a red-herring approach, however, because you don't need to even touch the SQL to accomplish what you want (you can do this with PHP with strip_tags!)
You don't need a query alter hook here (we don't need to go to the database to do this). You could do this with one of the preprocess or field hooks from the field API or the views API using the function linked in my previous point.
Even better, you don't even have to touch the code to accomplish this. You can do it right in the Drupal UI.
Under the field settings for the view, select rewrite results and then Strip HTML tags. Presto, no more HTML tags in that field.
Image source: https://www.drupal.org/node/750172
Here is the solution that worked for me:
// Traverse through the 'where' part of the query.
foreach ($query->where as &$condition_group) {
foreach ($condition_group['conditions'] as &$condition) {
if (in_array($condition['field'], $fields)) {
$value = $condition['value'];
$field = $condition['field'];
$condition = array(
'value' => array(),
'field' => t('dbo.udf_StripHTML(!field) like \'#value\'', array(
'!field' => $field,
'#value' => $value)),
'operator' => 'formula',);
}
}
}

Drupal services module JSON response fetched: Backbone.js model attributes turn into string

I've set up web services using Drupal's services module. It outputs JSON for me which I am requesting through a Backbone.js front-end application.
I'm having issues with this set-up. If I request data through Backbone.js' fetch method of a model, the model's attributes are all typed as string after fetching, while there are some attributes that should be e.g. integer.
For example:
I have enabled the user resource, which is standard available in the Drupal services module
I can request a user, e.g.:
http://mydevmachine/services/user/8
...which results in the following response (slimmed down version from the real response):
{"uid":"8","name":"itsme","mail":"me#mydomain.nl"}
What I see in the response from the web service above, all values are quoted, however uid is really not a string but an integer in the database.
If I fetch the same user in my Backbone.js model, by setting the uid field of my model to 8 (integer), then call the fetch method. After fetching the uid field is typed as 'string'.
I assume the above leads to my model ending up with a uid attribute of not integer, but string. It also happens with all other web service resources I have created, using my own entities.
I need correct typing of attributes in my model due to sorting issues using Backbone's collection sorting. I.e. sorting a collection of models using a field of type 'integer' leads to different sorting results when sorting the field with the same values although stored as a string.
I'm not sure exactly where to look:
Is the JSON format output by the Drupal services module according to standards?
Is the JSON output format configurable or overridable in the Drupal services module?
Is it perhaps possible to keep the type of a model's attribute after a fetch in Backbone.js?
Should I provide a specific implementation for Backbone's collection comparator function, which handles this situation (seems hackey)?
Should I introduce other solutions, e.g. like posted here: How can I enforce attribute types in a Backbone model? (feels too heavy).
Thanks for any help.
So I finally managed to crack this issue and I found my solution here: How to get numeric types from MySQL using PDO?. I thought I'd document the solution.
Drupal 7 uses PDO. Results fetched using PDO, using Drupal's default PDO settings result in stringified values.
In Drupal's includes/database.inc file you will find this around lines 40-50:
$connection_options['pdo'] += array(
// So we don't have to mess around with cursors and unbuffered queries by default.
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
// Because MySQL's prepared statements skip the query cache, because it's dumb.
PDO::ATTR_EMULATE_PREPARES => TRUE,
);
The statement here that MySQL's prepared statements skip the query cache is not entirely true, as can be found here: http://dev.mysql.com/doc/refman/5.1/en/query-cache-operation.html. It states MySQL > 5.1.17 prepared statements use the query cache under certain conditions.
I used the info from the other stack overflow question/answers to override the PDO settings for the database connection in Drupal's sites/default/settings.php (please note I only did this for the database I was querying, which is different than Drupal's own database):
'database_name' =>
array (
'default' =>
array (
'database' => 'database_name',
'username' => 'user_name',
'password' => 'user_pass',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
'pdo' => array(
PDO::ATTR_STRINGIFY_FETCHES => FALSE,
PDO::ATTR_EMULATE_PREPARES => FALSE
),
),
),
This resulted in integers being integers. Floats/decimals are incorrectly returned by PDO still, but this is different issue. At least my problems are solved now.

unable to retrieve image from custom content type

I've just started learning how to use Drupal 7. I made a new content type that will be displayed as a feed in my front page. All the data I need are being fetched and displayed correctly except for the image, whose url is always missing the actual file. I have another feed in my front page that uses the default article content type and all the images display properly.
The code I used for both is essentially the same, the only difference being the content type being retrieved.
This set worked:
$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title'))
->condition('n.type', 'article')
->leftJoin('field_data_body', 'u', 'u.entity_id = n.nid');
$query->addField('u', 'body_summary');
$query->orderBy("nid", "desc");
$query->range(0, 3);
$result = $query->execute();
while($row = $result->fetchAssoc()) {
$nid = $row['nid'];
$node = node_load($nid);
echo theme('image_style', array('style_name' => 'home-article-summary', 'path' => ($node->field_image['und'][0]['uri'])));
}
This didn't:
$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title'))
->condition('n.type', 'news') //the only difference between the two is this line
->leftJoin('field_data_body', 'u', 'u.entity_id = n.nid');
$query->addField('u', 'body_summary');
$query->orderBy("nid", "desc");
$query->range(0, 3);
$result = $query->execute();
while($row = $result->fetchAssoc()) {
$nid = $row['nid'];
$node = node_load($nid);
echo theme('image_style', array('style_name' => 'home-article-summary', 'path' => ($node->field_image['und'][0]['uri'])));
}
I tried making the settings of the content type I created the same as the ones for article throught Structure->Content Types but nothing happened. What am I missing? Thank you.
edit:
Upon inspection, I couldn't find a resized version of the image I uploaded for my custom content type. I'm assuming this means no resizing ever actually happened hence why the script didn't return a file. I still don't get why that happened.
edit the second:
never mind. I found the problem. it's all working fine now. was just using the wrong variable.
As a bit of friendly advice for a Drupal newcomer, consider using Views to display lists of content instead of writing heaps of custom database queries. That will save you lots of coding in the long run.
Another argument for Views is that it's going to be included in Drupal 8 core.

Resources