Drupal: Display a list of contribution (posted content) for each user - sql

I’m searching for a way to display on a member profile page, the number of contributions in some content types. Basically it has to display something like this:
Blog(10)
Articles(10)
Questions(19)
Comments(30)
Tips(3)
I’ve installed some different modules (like “user stats”) that I though could help me but haven’t been successful.
I’m wondering if it would be easiest just to hard-code it into my template file by starting taking the uid and just run some queries with the content types I want to display but I’m not sure on how to do that either.
Any help og suggestions would be very much appreciated.
Sincere
- Mestika
Edit:
I found a solution to do it manually with a query for each content type but I'm still very interested in a solution that's more elegant and smoother.
I use this code:
global $user;
$userid = $user->uid;
$blog_count = db_result(db_query("SELECT COUNT(0) AS num FROM {node} n where n.type = 'blog' AND status = 1 AND n.uid = {$userid}"));

If you are using the core Profile module, you could use something like below. It will show the nodes created by the user whose profile is being viewed. As an added benefit, it only needs to execute one custom database query.
Insert this snippet into template.php in your theme's folder and change "THEMENAME" to the name of your theme:
function THEMENAME_preprocess_user_profile(&$variables) {
// Information about user profile being viewed
$account = $variables['account'];
// Get info on all content types
$content_types = node_get_types('names');
// Get node counts for all content types for current user
$stats = array();
$node_counts = db_query('SELECT type, COUNT(type) AS num FROM {node} WHERE status = 1 AND uid = %d GROUP BY type', $account->uid);
while ($row = db_fetch_array($node_counts)) {
$stats[] = array(
'name' => $content_types[$row['type']],
'type' => $row['type'],
'num' => $row['num'],
);
}
$variables['node_stats'] = $stats;
}
Now, in user-profile.tpl.php can add something similar to:
// If user has created content, display stats
<?php if (count($node_stats) > 0): ?>
// For each content type, display a DIV with name and number of nodes
<?php foreach ($node_stats as $value): ?>
<div><?php print $value['name']; ?> (<?php print $value['num']; ?>)</div>
<?php endforeach; ?>
// Message to show for user that hasn't created any content
<?php else: ?>
<?php print $account->name; ?> has not created any content.
<?php endif; ?>
This is just a general idea of what you can do. You can also add restrictions to the content types you look for/display, check permissions for users to see these stats, use CSS to change the look of the stats, etc.
If you are using Content Profile, you could use THEMENAME_preprocess_node() and check that the node is a profile node before executing this code.

Given your simple requirement and the fact that you have the SQL statement in-hand, I'd say just use that. There's no reason to add yet another module to your site and impact it's performance for the sake of a single query.
That said, from a "separation of concerns" standpoint, you shouldn't just drop this SQL in your template. Instead, you should add its result to the list of available variables using a preprocess function in your template.php file, limiting its scope to where you need it so you're not running this database query on any pages but the appropriate profile page.

Related

How to pass a parameter to a scenario in Yii?

How to pass $id to search scenario? Maybe in model look like this, so I can call like in controller like:
$model = new job('search',$id);
I think that you are trying to do a search. Search is one thing, a "scenario" is something else.
Scenarios are used in validation rules in order to be able to validate the same model in multiple ways depending from where you're inserting/adding OR searching data.
There's also a scenario called 'search' that is used by the model's search() method, but I tell you why:
There are a couple of ways to search for something in your database using Yii, I will mention two:
1) By using ClassName::model()->findCommandHere
And there are a couple of them:
ClassName::model()->findByPk($id);
ClassName::model()->findAll("id=$id");
ClassName::model()->findByAttributes(array('id'=>$id));
And so on, more here: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#reading-record
2) By using the model's search() method
This way of finding data is mostly used for easily creating search pages and in combination with data grids.
If you generate CRUD code with the GII code generation tool it will generate all the parts for you, but I will explain each part how it works.
This code is from the blog demo found in Yii files:
In controller it defines a $model using Post class and 'search' as scenario.
$model=new Post('search');
if(isset($_GET['Post'])) // <- checks if there are search params in the URL
$model->attributes=$_GET['Post']; // <- assigns all search params masively to the model (later you'll see why)
$this->render('admin',array(
'model'=>$model,
));
The 'search' scenario here tells Yii what validation rules to use when assigning search parameters directly from $_GET (URL).
You can see that the params are assigned massively to reduce code written but $model->attributes=$_GET['Post'] it is the same as doing:
$model->title=$_GET['Post']['title'];
$model->status=$_GET['Post']['status'];
In the Post model you can find the validation rules for the search scenario. Tells Yii that it is safe to assign title and status fields in order to later use them in the search.
public function rules()
{
return array(
// ... //
array('title, status', 'safe', 'on'=>'search'),
);
}
Then also in the Post model you can see the search() method that will actually be used to get the data:
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('title',$this->title,true);
$criteria->compare('status',$this->status);
return new CActiveDataProvider('Post', array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'status, update_time DESC',
),
));
}
The search method creates a "criteria" and applies the desired way of filtering using the values you have previously assigned to this model. See the $this->title it comes from the $model->attributes=$_GET['Post'] you used in the controller.
The criteria can be used directly on the model, such as Post::model()->findAll($criteria), but in this case the search() method uses something different, a "data provider".
The data provider is a good thing because it provides you a lot of tools in one place, it returns you the data, but also the pagination, and the sorting, so you don't have to manually define more code for that purposes (CPagination, CSort).
Finally, in the view admin.php in this case it will display the results using a grid view:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'name'=>'title',
'type'=>'raw',
'value'=>'CHtml::link(CHtml::encode($data->title), $data->url)'
),
array(
'name'=>'status',
'value'=>'Lookup::item("PostStatus",$data->status)',
'filter'=>Lookup::items('PostStatus'),
),
),
));
Now you can see that in the configuration of the grid it passes $model->search() method as the dataProvider that the grid should use.
Now the grid can access the rest of the dataProvider elements such as sort, pagination and display them on the page.
If you did not want to use the CGridView because it's a very basic table and you want to create your own html markup, you can also retrieve the dataProvider and its components one by one and place them in your HTML code and display data as you want:
$dataProvider=$model->search(); // get the dataprovider from search method
$models=$dataProvider->getData(); // actually get the data (rows) and assign them to a $models variable that you can put in a foreach loop
// show pagination somewhere
$this->widget('CLinkPager', array(
'pages' => $dataProvider->pagination,
));
// create sort links
echo $dataProvider->sort->link('title', 'Title');
So I hope it solves some of your doubts on how to use Yii for displaying/searching data.
I suggest you read the official manual: http://www.yiiframework.com/doc/guide/1.1/en/index
I also suggest to look at the API and so search there all the Yii components to see what methods and params they have: http://www.yiiframework.com/doc/api/
Also exploring the framework codebase manually is quite a good way to learn. If you don't know how CActiveDataProvider works, then find the CActiveDataProvider class file in the code and you'll see all the methods and properties that it uses, so do this for everything you don't understand how it works.
Also for beginners I recommend using a good IDE that auto-completes code and allows you to Ctrl+Click a class name and it will locate the original file where it was defined. I use NetBeans for PHP and after creating a project I add Yii framework files to the project's include paths that way NetBeans knows how to find the framework files for auto-complete and for ctrl+click.
Yes you can define scenario with parameter but that is included within the class constructor of the model
$model = new Job('search'); // creating a model with scenario search
If you wish to include more parameters, then you need to use createComponent -remember, all is a component
$model = Yii::createComponent(array('class'=>'Job','scenario'=>'search'));
I think this will simply do the job without needing any scenario
$model = new job;
$model->search($id);
But If I have failed to understand your problem then you can also try this
$model = new job('search');
$model->search($id);
Think of scenarios as a special variable that you can use in the model.
$userModel = new User("register");
$userModel->setId = 10;
which is the same
$userModel = new User();
$userModel->scenario = 10
$userModel->setId = 10;
And in your model
class Manufacturer extends CActiveRecord
{
// :
if ($this->scenario == 'register') ...
// :
}

MailChimp API Get Subscribers ammount

I have been looking at the mailchimp api, and am wondering how to display the live ammount of subscribers to a list, is this possible? And is it possible to have this counter LIVE? I.e as users join, the number increases in real time?
EDIT:
I have been getting used to the API slightly...
after using Drewm's mailchimp php wrapper its starting to make more sense...
I have so far
// This is to tell WordPress our file requires Drewm/MailChimp.php.
require_once( 'src/Drewm/MailChimp.php' );
// This is for namespacing since Drew used that.
use \Drewm;
// Your Mailchimp API Key
$api = 'APIKEY';
$id = 'LISTID';
// Initializing the $MailChimp object
$MailChimp = new \Drewm\MailChimp($api);
$member_info = $MailChimp->call('lists/members', array(
'apikey' => $api,
'id' => $id // your mailchimp list id here
)
);
But not sure how to display these values, it's currently just saying 'array' when I echo $member_info, this maybe completly because of my ignorance in PHP. Any advice to s
I know this may be old, but maybe this will help someone else looking for this. Latest versions of API and PHP Files.
use \DrewM\MailChimp\MailChimp;
$MailChimp = new MailChimp($api_key);
$data = $MailChimp->get('lists');
print_r($data);// view output
$total_members = $data['lists'][0]['stats']['member_count'];
$list_id = $data['lists'][0]['id'];
$data['lists'][0] = First list. If you have more, then it would be like $data['lists'][1] ect...
And to get a list of members from a list:
$data = $MailChimp->get("lists/$list_id/members");
print_r($data['members']);// view output
foreach($data['members'] as $member){
$email = $member['email_address'];
$added = date('Y/m/d',strtotime($member['timestamp_opt']));
// I use reverse dates for sorting in a *datatable* so it properly sorts by date
}
You can view the print_r output to get what you want to get.

Pull mass name list from database or in script?

I need to fill an input box with a first name and last name. The user will press "Randomize" and it will pull a random first and last name and fill the inputs.
My question is I'm not sure if I should put the names in tables (firstNames, lastNames) or just store them in a javascript file and pull straight from that.
I'm trying to follow the Single Responsibility Principle so I'm inclined to choose the former, but then I have two more models, two more seeders, two more tables, and probably a class to pull all that together. And then do I fill from a CSV file or just from a manually populated seeder? It seems like a lot of work and extra files for a 1-time use.
I know I'll get crap for this being an opinion based question but there is no one or where else to ask.
Also if you know of a place to ask these kind of questions that won't get me ripped apart I'd appreciate that.
I would suggest using the Faker PHP library. That way you wouldn't have to create extra tables, models, or have to worry about finding yourself fake data.
To install it in your project, simply add the dependency in your composer.json file. and run a composer update.
"require-dev": {
"fzaninotto/faker": "1.3.*#dev"
},
Then you can use it to create fake first and last names for you (in your controller most likely)
$faker = Faker\Factory::create();
$firstName = $faker->firstName;
$lastName = $faker->lastName;
Edit:
To add your own names you can either edit or override the name provider file located here.
I would like to suggest Fakerino a new fake generator PHP library, with a modern approach, easy to extend with custom data, custom fake data class, or pre-configured groups of data.
https://github.com/niklongstone/Fakerino
<?php
include ('../Fakerino/vendor/autoload.php');
use Fakerino\Fakerino;
$fakerino = Fakerino::create();
echo $fakerino->fake('Surname')->toJson(); //["Donovan"]
echo $fakerino->fake('NameFemale'); //Alice
//with configuration
$fakerino = Fakerino::create('./conf.php');
print_r($fakerino->fake('fake1')->toArray());
/*
Array(
[0] => Arthur
[1] => Doyle
)
*/
//conf.php
<?php
$conf['fake'] = array(
'fake1' => array('NameMale', 'Surname' => null),
'fake2' => array('NameFemale', 'Surname' => null)
);

how to fetch data from db and display in views

I am new to yii framework.I have just create an app and I want to fetch data from DB based on some condition and then display that in views .For this I have tried few things in my controller :
if(isset($_GET['sku']))
{
$sku=$_GET['sku'];
$data=Products::model()->findAll("sku=$sku");
}
$this->render('checkout',array(
'data'=>$data,
));
and when in my views i try to print data as :
print_r($data);
I shows me a complex array , but i do not want that.
The thing which i want is I can get an array from controllers which includes the data return by query based on some condition and in my views using foreach i can display them according to my need.
So please suggest me some good ways of fetching data from db and can display them in my views.
Thanks !!
In your view use something like this:
<?php echo CHtml::encode($data->fieldname); ?>
Or better, use the Gii code generator to build your CRUD functions, and you will see several good examples for how to build these functions. Here is a link to a very good tutorial: http://www.yiiframework.com/doc/guide/1.1/en/quickstart.first-app
Try to use DAO instead Active Record
$sql = "SELECT * FROM `products` WHERE sku = ".Yii::app()->request->getParam('sku', 0);
$data = Yii::app()->db
->createCommand($sql)
->queryAll();
$this->render('checkout',array(
'data'=>$data,
));
You should have db component in config file(ex. config/main.php)
http://www.yiiframework.com/doc/guide/1.1/en/database.dao

Drupal 6, Views 2: Is it possible to have a filter that only applies to registered users?

Is it possible to create a filter in a Drupal 6 View that is only applied for registered users?
For one filter I need I'm using the user vote (With fivestar and votingapi) to know if they user already voted this node or not, and when the user is annonymous, is working as if all the votes from all the annonymous users where from the same. This is why I need to add this filter, but ignore it in case the user is annonymous.
Thanks a lot in advance for the help!
If you're comfortable with php, download the Views PHP Filter module (http://drupal.org/project/viewsphpfilter). This module allows you to easily write your own custom filters for any view.
After downloading and enabling the module, create a new view and add a "Node: Node ID PHP handler" filter. Now you can add custom php code for any filter you want. Perhaps something like:
global $user;
$allowed = array('authenticated user');
foreach ($user->role as $role) {
if (in_array($role, $allowed)) {
$nids = //Run custom filter query for allowed users
}
else {
$nids = //Run alternate filter query for anonymous users
}
}
return $nids;
The code should return a list of node ids to display.