unable get data from database cakephp - 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'); ?>

Related

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;
}

Cakephp Custom Find Type Pagination

I created a custom find type, and am trying to paginate the results, but the paginator seems to be ignoring the findType setting. Can someone tell me what I'm doing wrong?
(CakePHP 2.X)
In my Controller:
public function list($username=null) {
$this->Paginator->settings = array(
'Question' => array(
'findType' => 'unanswered',
'conditions' => array('Question.private' => 0),
);
$data = $this->Paginator->paginate('Question');
$this->set('data', $data);
);
Custom find type setup in my Model:
public $findMethods = array('unanswered' => true);
protected function _findUnanswered($state, $query, $results = array()) {
if ($state == 'before') {
$query['order'] = array('Question.created DESC');
$query['conditions'] = array_merge($query['conditions'], array('Question.date_answered' => ''));
return $query;
$this->log($query);
} elseif ($state == 'after') {
return $results;
}
}
Edit
I can paginate the query if I remove $this->Paginate->settings, and replace it with this:
$this->paginate = array('unanswered');
However, I want to add some additional conditions., this doesn't work:
$this->paginate = array('unanswered' => 'conditions' => array('Question.user_id' => $id, 'limit' => 4)) );
Is this possible?
findType was added to the paginator component in CakePHP 2.3, I was on 2.0
http://api.cakephp.org/2.3/class-PaginatorComponent.html

How to send data to custom block content

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,
);

passing data to view CakePHP

This might be easy, but I have tried a few ideas but no solution at all, I'm no expert with cakePhp but I'm trying to modify a existing project with limited time.
The problem is that I have a entity called 'centro' but I'm using its model on a different controller, 'rw', but I can't get it to pass that data to the view at all; it seems it's because the variable gets erased when I use a redirect to go back to the 'index'.
I need that data to generate a google map, the method $this->set(.....) is not working.
Here's the code of the 'rw' controller.
<?php
class RwController extends AppController {
var $name = 'Rw';
// var $paginate = array(
// 'Tip' => array(
// 'limit' => 1,
// 'order' => array(
// 'tip.created' => 'desc'
// ),
// ),
// 'Evento' => array(
// 'limit' => 1,
// 'order' => array(
// 'evento.fecha' => 'desc'
// ),
// )
// );
function map() {
$this->helpers[]='GoogleMapV3';
}
function pageForPagination($model) {
$page = 1;
// $chars = preg_split('/model:/', $this->params['url']['url'], -1, PREG_SPLIT_OFFSET_CAPTURE);
// #print_r($chars);
// if(sizeof($chars) > 1 && sizeof($chars) < 3) {
// #echo "Belongs to ".$model.": \n";
// #echo var_dump($chars);
// }
// $params = Dispatcher::parseParams(Dispatcher::uri());
// echo "<p>".var_dump($params)."</p><br />";
#echo $this->params['named']['model'].$model;
#echo $this->params['named']['page'];
$sameModel = isset($this->params['named']['model']) && $this->params['named']['model'] == $model;
$pageInUrl = isset($this->params['named']['page']);
if ($sameModel && $pageInUrl) {
$page = $this->params['named']['page'];
} else {
#echo var_dump($this->passedArgs);
}
$this->passedArgs['page'] = $page;
return $page;
}
function index() {
$this->loadModel('User');
$this->loadModel('Evento');
$this->loadModel('Tip');
$dataEvento = $this->Evento->find('all');
$dataTip = $this->Tip->find('all');
$page = $this->pageForPagination('Evento');
$this->paginate['Evento'] = array(
'contain' => false,
'order' => array('Evento.fecha' => 'desc'),
'limit' => 1,
'page' => $page
);
$dataEvento = $this->paginate('Evento');
$page = $this->pageForPagination('Tip');
$this->paginate['Tip'] = array(
'contain' => false,
'order' => array('Tip.created' => 'desc'),
'limit' => 1,
'page' => $page
);
$dataTip = $this->paginate('Tip');
$this->set('users', $this->User->find('all'));
$this->set('eventos', $dataEvento);
$this->set('tips', $dataTip);
$this->set('rw');
if(isset($this->params['named']['model'])) {
if (strcmp($this->params['named']['model'], 'Evento') == 0) {
if($this->RequestHandler->isAjax()) {
$this->render('/elements/ajax_rw_evento_paginate');
return;
}
} elseif (strcmp($this->params['named']['model'], 'Tip') == 0) {
if($this->RequestHandler->isAjax()) {
$this->render('/elements/ajax_rw_tip_paginate');
return;
}
}
}
}
function about($id = null) {
$this->Rw->recursive = 0;
$this->set('rw', $this->paginate());
}
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('*'));
}
function getCentros($id = null ){
$this->loadModel('Centro');
$this->log('getcentros','debug');
$this->log('el id'.$id,'debug');
if( sizeof($id) > 1){
$this->set('centros', $this->Centro->query("SELECT centros.id, name, latitud ,longitud
FROM `centros`,`centrosmateriales`
WHERE centros.id = centro_id
AND material_id ='".$id[0]."'
OR material_id='".$id[1]."'"));
$this->log('size id > 1 ','debug');
}elseif( sizeof($id) >0) {
if($id == 0){
$this->set('centros', $this->Centro->find('all'));
}else{
$this->set('centros', $this->Centro->query("SELECT centros.id, name, latitud ,longitud
FROM `centros`,`centrosmateriales`
WHERE centros.id = centro_id
AND material_id ='".$id[0]."'"));
}
}
$this->Session->write('saludos', 'Saludando');
$this->redirect(array('action' => 'index'));
}
}
?>
I have been thinking about ajax but I'm not sure.
Anyways, thanks in advance.
Using redirect() sends an actual HTTP redirect to the browser. This causes the browser to send another request to the server, to the URL it has been redirected to.
The data that you pass to set() is only available within that single CakePHP request cycle. All PHP data is wiped from memory afterwards. The only way to pass data to the next request is in the URL or in the session.
In your case you should rethink your design and set() all data you need in the index() action. You could possibly move the logic from getCentros() into your Centro model. Then, in your index() function, you could just do
$this->set(
'centro',
$this->Centro->getCentros();
);

CakePHP - How can I find all languages with tongue twisters?

Model
<?php
class Tonguetwister extends AppModel {
var $name = 'Tonguetwister';
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'language' => array(
'className' => 'language',
'foreignKey' => 'language_alias',
'dependent'=> true
)
);
}
?>
Controller
<?php
class TonguetwistersController extends AppController {
var $name = 'Tonguetwisters';
var $uses = array('Tonguetwister', 'Language');
function index() {
$this->set('languages', $this->Language->find('all'));
}
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid tonguetwister', true));
$this->redirect(array('action' => 'index'));
}
$this->set('tonguetwisters', $this->Tonguetwister->find('all', array('conditions' => array('language_alias' => $id))));
}
}
?>
I only want to see languages on index() that have tongue twisters. How can I do this?
There might be a more efficient way, but here's how to pick only unique languages from the Tonguetwister table:
function index() {
$languageList = $this->Tonguetwister->find(
'list',
array(
'fields' => array( 'language_alias', 'language_alias' ),
'group' => 'Tonguetwister.language_alias',
'recursive' => -1
)
);
// $languageList is now an array that holds the language ids
$this->set(
'languages',
$this->Tonguetwister->Language->find(
'all',
array(
'conditions' => array(
'Language.id' => $languageList
)
)
)
);
}
By the way, you don't need to put Language into $uses. Since they have a relation set you can access the Language model with $this->Tonguetwister->Language.
You don't really need to do two SQL queries for this. If the tables are joined on "language_alias" you can do something like this:
function index() {
$this->Language->recursive = 0;
$this->set('languages', $this->Language->find('all', array(
'conditions' => array($this->Language->alias.'.language_alias' => $this->Tonguetwister->alias.'.language_alias')
));
}
You should just do one query that's going to join the tables properly.

Resources