How to send data to custom block content - drupal-7

I'm trying to create a module that will display some last entries from database. I'd like to send last entry object to template file (guestbook-last-entries.tpl.php), that looks like that
<p><?php render($title); ?></p>
<?php echo $message; ?>
I have a function that implements hook_theme
function guestbook_theme() {
return array(
'guestbook_last_entries' => array(
'variables' => array(
'entries' => NULL,
),
'template' => 'guestbook-last-entries'
),
);
}
one that do preprocess
function template_preprocess_guestbook_last_entries(&$variables) {
$variables = array_merge((array) $variables['entries'], $variables);
}
and functions that implements hook_block_view
function guestbook_block_view($delta = '') {
switch ($delta) {
case 'guestbook_last_entries':
$block['subject'] = t('Last entries');
$block['content'] = array();
$entries = guestbook_get_last_entries(variable_get('guestbook_m', 3));
foreach ($entries as $entry) {
$block['content'] += array(
'#theme' => 'guestbook_last_entries',
'#entries' => $entry,
);
}
break;
}
return $block;
}
function that gets data from database
function guestbook_get_last_entries($limit = 3) {
$result = db_select('guestbook', 'g')
->fields('g')
->orderBy('posted', 'DESC')
->range(0, $limit)
->execute();
return $result->fetchAllAssoc('gid');
}
But in this case I get only one entry displayed. Can anyone tell me how to resolve this, how should I build that $block['content']?
Thank you

This here wont work:
$block['content'] += array(
'#theme' => 'guestbook_last_entries',
'#entries' => $entry,
);
Maybe you want this if you need an array as the result:
// note that I replaced += with a simple = and added two brackets that will create a new element in that array $block['content']
$block['content'][] = array(
'#theme' => 'guestbook_last_entries',
'#entries' => $entry,
);

Related

unable get data from database cakephp

i want get data from database and calculate the average Rating but when i get data by author id i have message find() is null
this my function
public function teacher_average_rating_in_school()
{
$this->autoRender = false;
if($this->request->is('get'))
{
$author_id = $this->request->query('author_id');//
$rate = $this->UserRating->find('all',array('conditions'=>array('author_id'=> $author_id), 'fields'=> array('AVG(UserRating.rstings) as averageRating'), 'recursive' =>-1));
$average = $rate[0][0]['averageRating'];
$result = array('success'=>'1' , 'average' => $average );
}
else{
$result = array('success'=>'0','message'=>'request type is not GET');
}
echo json_encode($result);
}
and this my model
class UserRating extends AppModel {
public $validate = array(
'user_id' => array('rule' => 'notBlank'), 'author_id' => array( 'rule' => 'notBlank') , array('rstings' => 'notBlank' ));
}
why i get find()is null , and how can i solve that ?
Have you load the Modal??
public function teacher_average_rating_in_school()
{
$this->autoRender = false;
if($this->request->is('get'))
{
$this->loadModel('UserRating');
$author_id = $this->request->query('author_id');//
$rate = $this->UserRating->find('all',array('conditions'=>array('author_id'=> $author_id), 'fields'=> array('AVG(UserRating.rstings) as averageRating'), 'recursive' =>-1));
$average = $rate[0][0]['averageRating'];
$result = array('success'=>'1' , 'average' => $average );
}
else{
$result = array('success'=>'0','message'=>'request type is not GET');
}
echo json_encode($result);
}
If you have already loadModel using then check sql_dump.
You can use as follows
//inside controller action
debug($this->UserRating->lastQuery());
//Or inside layout call this
<?php echo $this->element('sql_dump'); ?>

hook_block_view not passing information

I am trying to build my first custom module in Drupal 7. It is a block form for the user to search a DB table for customer information. I've created both the module and info files. My module appears under the modules and blocks section, but when I add the block to Content, the subject and content aren't being passed from my hook_block_view. So, instead of the form being displayed, it just shows the block title and body. Can someone tell me what I'm missing?
<?php
/**
*#file
*
*/
/** Implements hook_block_info().
*
*/
function searchEngine_block_info(){
$blocks = array();
$blocks['searchEngine_form'] = array (
'info' => t("Applicant Search"),
'cache' => DRUPAL_CACHE_GLOBAL,
);
return $blocks;
}
/** Implements hook_block_view().
*
*/
function searchEngine_block_view($delta = ''){
$block = array();
switch($delta) {
case 'searchEngine_form':
$block['subject'] = t('Applicant Search');
$block['content'] = drupal_get_form('searchEngine_form');
break;
}
return $block;
}
function searchEngine_form($form, &$form_state) {
$form['searchOptions'] = array(
'#type' => 'select',
'#title' => t("Select how you would like to search for an applicant."),
'#default_value'=> variable_get("gwf", true),
'#options' => array(
'gwf' => "GWF".t(" Number"),
'email' => t("Email"),
'name' => t("Name"),
'phone_number' => t("Phone Number"),
),
);
$form['data'] = array(
'#type' => 'textfeild',
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function searchEngine_submit($form, $form_state) {
if(isset($form['data'])){
if($form['searchOptions'] == "name"){
$name = preg_split("/[\s,]+/", $form['data']);
$result = db_query('SELECT * FROM tls_active_applicants WHERE first_name = '.$name['0'].' AND last_name = '.$name['1']);
}else{
$result = db_query('SELECT * FROM tls_active_applicants WHERE '.$form['searchOptions'].' = '.$form['data']);
}
print_r($result);
}
}
Passing a renderable array here is fine:
$block['content'] = drupal_get_form('searchEngine_form');
I've just tested your code and the form appears fine for me:
Now we know the code works it makes me wonder if it is just some css or something hiding it?
I would also install the devel module as it will help with debugging.
The you could use this code:
function searchEngine_block_view($delta = ''){
$block = array();
switch($delta) {
case 'searchEngine_form':
$block['subject'] = t('Applicant Search');
$form = drupal_get_form('test_form');
dpm($form); // call to dpm here to log if you are successfully getting the form at this point
$block['content'] = $form;
break;
}
return $block;
}

custom datasource find('list') issue

I am creating a custom datasource and I am having problems when i request find('list'). find('all') returns perfectly what I want within my controller but find('list') just returns an empty array.
The funny thing is if I do a die(Debug($results)) in the datasource within the read function then I get my find('list') array correctly but if I return it i then get an empty array in my controller. Any ideas?
Code below:
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] == 'COUNT') {
return array(array(array('count' => 1)));
}
$this->modelAlias = $model->alias;
$this->suffix = str_replace('Flexipay', '', $model->alias);
if(empty($model->id)){
$this->url = sprintf('%s%s%s', $this->sourceUrl, 'getAll', Inflector::pluralize($this->suffix));
}
$r = $this->Http->get($this->url, $this->config);
if($r->isOk()){
$results_src = json_decode($r->body, true);
if(is_array($results_src)){
//$this->find('list');
if($model->findQueryType == 'list'){
return $this->findList($queryData, $recursive, $results_src);
}
//$this->find('all');
foreach($results_src['PortalMandantenResponses']['portalMandantenResponses'] as $r){
$results[] = $r;
}
if(!empty($results)){
$e = array($model->alias => $results);
return $e;
}
}
}else{
//
}
return false;
}
My response from die(debug(array($model->alias => $results);
(int) 0 => array(
'Mandant' => array(
'ns2.id' => (int) 79129,
'ns2.name' => 'company a'
)
),
(int) 1 => array(
'Mandant' => array(
'ns2.id' => (int) 70000,
'ns2.name' => 'company b'
)
),
Controller Code is here:
public function test2(){
//$a = $this->User->find('list');
//die(debug($a));
$this->loadModel('Pay.Mandant');
$a = $this->Mandant->find('list', array('fields' => array('ns2.systembenutzernr', 'ns2.systembenutzernrBezeichnung')));
die(debug($a));
}
use,
$a = $this->Mandant->find('list', array('fields' => array('ns2.systembenutzernr', 'ns2.systembenutzernrBezeichnung')));
$this->set(compact('a'));
You can use $a for the dropdown creation in view file.
I just had the same problem writing my custom model though I don't know if the cause in your case is the same, though you should probably look in the same place.
in Model.php there is a function _findList($state, $query, $results), my issue was the fields you specify in the find() call must match the $results structure exactly, otherwise at the end of the _findList() function the call to:
Hash::combine($results, $query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath'])
returns the empty array. The keyPath of {n}.MODELNAME.id, etc must match the name of the model specified in $results, for example
[0] => ['MODELNAME'] = array()
[1] => ['MODELNAME'] = array()
In my case my keyPath and valuePath had a different value for MODELNAME than in the results array
Hope that helps

Drupal 7 - Module block with custom template not rendering

I can't seem to get my custom block within my module to render the template file I created. Here is my code:
<?php
include_once 'e_most_popular.features.inc'; //this is from features module
function e_most_popular_block_info() {
$blocks['e_most_popular'] = array(
'info' => t('e_most_popular block TITLE'),
'cache' => DRUPAL_NO_CACHE, //there are a number of caching options for this
);
return $blocks;
}
function e_most_popular_block_view($delta = ''){
switch($delta){
case 'e_most_popular':
if(user_access('access content')){ //good idea to check user perms here
$block['subject'] = t('MYblock_TITLE');
$block['content'] = e_most_popular_block_function_items();
}
break;
}
}
function e_most_popular_block_function_items(){
$items = array();
$items['VAR_ONE'] = array('#markup' => 'VAR_ONE_OUTPUT'); //this is the simplest kind of render array
$items['VAR_TWO'] = array(
'#prefix' => '<div>',
'#markup' => 'VAR_TWO_OUTPUT',
'#suffix' => '</div>',
);
//this is where the $items get sent to your default e_most_popular_block.tpl.php that gets //registered below
return theme('e_most_popular_block_function_items', array('items' => $items));
}
//here you are registering your default tpl for the above block
function e_most_popular_theme() {
$module_path = drupal_get_path('module', 'e_most_popular');
$base = array(
'path' => "$module_path/theme", );
return array(
'e_most_popular_block_function_items' => $base + array(
'template' => 'e_most_popular_block',
'variables' => array('items' => NULL,),
),
);
}
I have confirmed that it does read the template file, since it will error if not named correctly, and I have enabled the and module assigned the block to the sidebar in the block menu. I also clear the cache after making changes. I still get no output. Here is the template file:
Template file Test
<?php
$items = $variables['items'];
print render($items['VAR_ONE']);
Any idea what I am doing incorrectly?
As I mentioned in my comment, the issue is that you are not returning the $block variable in your hook_block_view. That is why nothing is being output.
Check out the documentation for hook_block_view.
Your hook_block_view should be like the following:
function e_most_popular_block_view($delta = ''){
$block = array();
switch($delta){
case 'e_most_popular':
if(user_access('access content')){ //good idea to check user perms here
$block['subject'] = t('MYblock_TITLE');
$block['content'] = e_most_popular_block_function_items();
}
break;
}
return $block;
}

Populating #options, #header for tableselect in ajax callback function

What I am trying to do is display a table with checkboxes on the press of a button by ajax. The table should be initially hidden and get populated on the fly by a function call.
If initially I load $options1 with some dummy values , then after ajax call it throws in an error saying-
Notice: Undefined index: red in theme_tableselect() (line 3285 of
D:\wamp\www\drupal7\includes\form.inc).
where 'red' is the index of a dummy row value and #options don't get populated with the new values. What is the way to get this working ?
Here is the code for the form-
$form['mltag_new']['tag'] = array(
'#type' => 'button',
'#value' => t("Suggest Tags"),
'#ajax' => array(
'callback' => 'mltag_suggest_tags_ajax',
'wrapper' => 'mltag_suggest_tags_table_div',
'effect' => 'slide',
),
);
$options1 = array(); //initial dummy values
$options1['red']['tag'] = "A red row";
$options1['red']['chi'] = "A red row";
$form['mltag_new']['myselector'] = array (
'#type' => 'tableselect',
'#title' => 'My Selector',
'#header' => $header,
'#options' => $options1,
'#prefix' => '<div id="mltag_suggest_tags_table_div">',
'#suffix' => '</div>',
);
return $form;
and the Ajax callback looks something like this-
function mltag_suggest_tags_ajax($form, $form_state) {
//$content has some content
//pass the content to a function
include_once 'includes/content_tag.inc';
$tags = mltag_content_tag($content, variable_get('algo_type'), 20);
if (empty($tags)) {
$output .= t('Content is insufficient to generate Tags using this algorithm. <br>Please choose other algorithm from Settings Page.');
$form['mltag_new']['sample_text']['#markup'] = $output;
return $form['mltag_new']['sample_text'];
}
else {
$algo = variable_get('algo_type');
if ($algo == 1) {
$header = array(
'tag' => t('Tag'),
'frequency' => t('Frequency'),
);
$options = array();
foreach ($tags as $key => $value) {
$options[$key] = array(
'tag' => $key,
'frequency' => $value,
);
}
}
elseif ($algo == 2) {
$header = array(
'tag' => t('Tag'),
'chi' => t('Chi Square Value'),
);
$options = array();
foreach ($tags as $key => $value) {
$options[$key] = array(
'tag' => $key,
'chi' => $value,
);
}
}
$form['mltag_new']['myselector']['#header'] = $header;
$form['mltag_new']['myselector']['#options'] = $options;
return $form['mltag_new']['myselector'];
}
}
I replied to your post on Drupal.org about how I'm working on a somewhat similar problem. Try adding
$form['mltag_new']['myselector'] =
form_process_tableselect($form['mltag_new']['myselector']);
just before your return. Hopefully that helps you more than it did me. Beware that the #options just get rendered when the block reloads from the ajax, but the original $form object doesn't seem to be aware.
I know that this is a few years later, but I found this while searching for my own solution:
The tableselect module creates checkboxes in the $ form that have to be removed. in the example above, they would be in $form['mltag_new']['myselector'] with keys equal to the original $option1 in your original code. If you unset those, then call
$form['mltag_new']['myselector'] = form_process_tableselect($form['mltag_new']['myselector']);
before your return, it will eliminate the dummy rows.

Resources