While i'm creating basic page in drupal i select text format to PHP code. Now I can write PHP code here.
I want to list records from MySQL, How can I include a database-connection here?
Is it good way writing PHP code in content?
you can directly call drupal api functions like db_query() without adding any dbconection in a page. Adding php codes inside a page is not recommented, try to create your own module for that or use views
First: you should not use the PHP-input format. The fact that it is there is highly debated in Drupal, with many people leaning towards removing it entirely. It is both a security nightmare and a maintanance-horror.
That said, the PHP you are looking for is:
<?php
// Create an object of type SelectQuery
$query = db_select('users', 'u');
// Add extra detail to this query object: a condition, fields and a range
$query->condition('u.uid', 0, '<>');
$query->fields('u', array('uid', 'name', 'status', 'created', 'access'));
$query->range(0, 50);
?>
More on dynamic queries is found on Drupal.org. No need to set-up your database, Drupal already handled that.
In case you want your code to connect to a differnt database then the main Drupal-database, you can either add that database to your settings.php:
$databases['gallery']['gallery'] = array(
'driver' => 'mysql',
'database' => 'gallery',
'username' => 'username',
'password' => 'secret',
'host' => 'localhost',
);
This introduces a new database resource called "gallery" using a database "gallery". Useful when you want to use resources from another database, like records from a "gallery application".
You can then query that database using the key in the $options-parameter, like so:
<?php
// Create an object of type SelectQuery
$query = db_select('pictures', 'p', array('target' => 'gallery'));
// Add extra detail to this query object: a condition, fields and a range
$query->condition('p.status', 'published', '=');
$query->fields('p', array('path', 'title', 'date'));
$query->range(0, 50);
?>
Related
I have one view in Drupal 7, which displays user information like (Name, address, Status, etc..). I have one column in this (Table)view as "Published event". Basically events are created by users do I want to make this column sortable. I have attached image for more reference.
I tried with applying relationship but no success.
table settings
my handler code is like below :
$handler->display->display_options['sorts']['event_count_published'] ['id'] = 'event_count_published';
$handler->display->display_options['sorts']['event_count_published'] ['table'] = 'search_api_index_user_search_index';
$handler->display->display_options['sorts']['event_count_published'] ['field'] = 'event_count_published';
$handler->display->display_options['sorts']['event_count_published'] ['order'] = 'DESC';
'mail' => array(
'sortable' => 1,
'default_sort_order' => 'asc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
'event_count_published' => array(
'align' => '',
'separator' => '',
'empty_column' => 0,
'sortable' => 1,
),
above code is in "tcd_reporting.views_default.inc" file, if I put 'sortable => 1', it still does not provide sorting
field is created by below code:
$properties['event_count_published'] = array(
'label' => t('Published Events'),
'description' => t('Number of published events authored by user.'),
'type' => 'integer',
'getter callback' => 'tcd_event_content_type_count_published_get',
'computed' => TRUE,
'entity views field' => TRUE,
);
[Introduction] Which function is responsible for 'click sort' in views?
Click sort -this checkbox from your second screen- in views table settings is function which is enabled only for fields which have properly defined handlers. As you may know each field in views have few handlers (for displaying, filtering, sorting). And for click sort to be possible on specified column its field handler must have two functions defined: click_sortable and click_sort. First one just need to return true, while second need to properly implements sorting on view. For example see handler: [views_module_path]/handlers/views_handler_field.inc.
Your case:
It seems that your column "Published event" have defined handler which does not have click_sortable and click_sort functions (or click_sortable simply returns false).
Possible fix:
Find place where you defined your view source (it depends on how you informed views about it, if I understand its something like "User info" - maybe in hook_entity_info function or hook_views_data function), check what handler is assigned to your "Published event" field and change it.
It's hard to tell where you need to look as it depends on your implementation.
I suggest you to try create hook_views_data_alter function and dpm() it for start. Later you can alter it like that:
mymodule_views_data_alter(&$data) {
$data['some_view_info']['published_event']['field']['handler'] = 'views_handler_field_numeric';
}
Edit 1
First could you tell where this code is? Is it inside handler class, or maybe some views hook? Views gives you a lot of flexibility but this make them hard to understand, and I'm not sure what exactly you achieve and how.
Assuming your field works properly you can try to simply enable click sort.
Example: I created hook_views_data_alter function to see content of views data
function mymodule_views_data_alter(&$data) {
dpm($data,'d');
}
You might need to clear cache to see dpm of *_alter hooks.
Inside dpm'ed array I found "users" for generic example, and its field name looks like this:
I suggest you to try alter your field with click_sortable = TRUE and see what happens. If this wont help please provide more information about your field, how you created it, how it looks in hook_views_data_alter and which handlers it has defined.
Edit 2
Ok, so you have your views exported to code into views_default file. But this only allows you to export view you created from database to code, so it is basically a reflection of what you done in views web editor (eg. page yourwebsite.com/admin/structure/views/view/your_view_name/edit). What you need to do is to change behavior of one of your fields so it became sortable (add click_sortable and click_sort functions in handler class) or change handler of this field to one with sorting option (change field handler to other one like views_handler_field_numeric). If you don't have experience in creating handlers and this is one of generic handlers i suggest you to go back to my Edit 1, examine your dpm, and try to alter $data array to find solution.
Edit 3
Little explanation to prevent confusion. When creating new view you select collection on which this particular view base on (simpliest example - it may be MySQL table, and view will use SQL queries to retrieve data from it). By digging down we have:
Collection - eg. User which is database table user, it is what you select as source when creating new view.
Field - eg. mail which is database column mail, this fields you add to your view.
Field handler - eg. views_handler_field_numeric, this is class name of handler to use by specified field
Now, if you don't created your own handler then your field "Published event" have one of generic views handler. You shouldn't ever change code of contributed modules - especially so widely used as views handlers. That's why my suggestion to add functions click_sortable and click_sort is incorrect. Instead you should change handler responsible for field "Published event".
Best way is to define proper handler in place where you define your field "Published event". If it's somehow impossible the only way I can think of is hook_views_data_alter see docs for more info and examples. I suppose you should try to redefine handler of your field to generic numeric handler views_handler_field_numeric as it should have full sorting functionallity, or try to add click_sortable property to field array as you can see in first image of my post, but I can't provide you fully tested example.
I am changing the data provided by my model in the afterFind() method, so the id is clickable text, like this:
$this->id = CHtml::link($this->id, array('/admin/auditTrail/view', 'id' => $this->id));
However, this changes every single occurrence of id value - it is in lists, in detail page, even in breadcrumbs, which is unwilling of course. How can I decide which format I will use in different views? For example, in breadcrumbs and in view.php I just want the raw value, but in the list (admin.php) I would like to use the html link, like this:
'columns'=>array(
array(
'name' => 'id',
'type' => 'html',
),
On a separate note - is this a good approach in terms of MVC, I mean changing display in a model? Should not be model only used for a database manipulation stuff?
No, this is not a good approach. There are a number of alternative approaches that would be better, for example:
Let the view do the conversion
Don't do anything in the model. When the view wants to display clickable anchors instead of bare ids, it should generate the URLs itself. This is somewhat quick and dirty (it puts the logic of URL generation in the view, which is not ideal) but it's easy and it works well if you only need to do it in one or two places.
Expose the URL as a separate property
Place a calculated read-only property in your model:
public function getAuditTrailUrl()
{
return Yii::app()->createUrl('/admin/auditTrail/view',
array('id' => $this->id));
}
You can then use the auditTrailUrl property in any view. The nice thing about this approach is that the URL generation is opaque to the views and therefore easily modifiable.
You can use this syntax to easily render links from these URLs in your CDataGrid:
'columns' => array(
array(
'class' => 'CLinkColumn',
'urlExpression' => '$data->auditTrailUrl',
)
),
In the above definition $data refers to each model in the grid, as per the documentation.
How it's possible to call MySQL function (like GeomFromText() or SELECT AS) in the Lithium Framework's CRUD? Using database->read() is to inconvenient (I often change the database columns) and including the function in the variable's value only ends up being escaped.
Have you tried putting the function in the fields option?
For example, I do this:
Model::first(array(
'fields' => 'max(id)'
));
To clarify, in your query, try this (i have not tested this):
Model::first(array(
'fields' => array('field1 as myField', 'GeomFromText("POINT(x y)") as geom')
));
I'm new to CakePHP and I'm stuck in reading a Model using other fields. I did a cake bake command to generate a simple users CRUD. I can view the user using the url CakePHP provided.
/users/view/1
I can view the user using id = 1. What if I want to view a user by name instead of id?
/users/view/username
By default the view function reads the User model by id.
$this->User->read(null, $id)
Thank you.
you can use find function or findBy<Field>() in your case findByUsername()
check this
I've never used cakePHP myself but I'm going to suggest that you will likely have to implement a new user model method, something like getUserByUsername($username)
This would then in turn interface with your DAL that would get the details of that user based on the username and return a user object that can be used however you wish...
It seems that CakePHP is focusing to deprecate some functions, such as findAll(). Perhaps soon the magic methods such as findBy<field>() will have the same fate.
I can recommend what martswite is suggesting, you should create your custom function:
function findUser($username=''){
return $this->find('first', array(
'conditions' => array(
'User.username' => $username
)
));
}
Perhaps you have a status field, maybe the profile isn't public, you can add a condition:
function findUser($username=''){
return $this->find('first', array(
'conditions' => array(
'User.username' => $username,
'User.status' => 1
)
));
}
I think that's more modular than findBy<Field>.
We're using the Zend_Log class to update a few different "watchdog" database tables (that log different events: Batch scripts running, new data being processed, files generated, etc.).
Here is my current code (before the issue I'm looking into fixing.)
$writer = new Zend_Log_Writer_Db($db, 'watchdog', array(
'priority' => 'priority',
'message' => 'message',
'owner' => 'owner',
));
$logger = new Zend_Log($writer);
$logger->setEventItem('owner', 'MODULE_NAME');
This works perfectly fine. But, I want to add a database column called datetime that is a call to time() at the time of the event. So, in theory, it would be something like this:
$writer = new Zend_Log_Writer_Db($db, 'watchdog', array(
'priority' => 'priority',
'message' => 'message',
'owner' => 'owner',
'datetime' => 'datetime',
));
$logger = new Zend_Log($writer);
$logger->setEventItem('owner', 'MODULE_NAME');
$logger->setEventItem('datetime', time());
The problem I'm running into is that, obviously, the call to time() runs at the first time Zend_Log::setEventItem is called and not when Zend_Log::info() is called. So, the question is, how do I get the time() to be called and stored in my DB when Zend_Log::info() is called? Will I need to extend Zend_Log_Writer_Db with a more custom class?
Another solution I wanted to put out there is to use Zend_Db_Expr with a MySQL function like NOW() or TIMESTAMP().
$dblog->setEventItem('datetime', new Zend_Db_Expr('NOW()'));
Extending seems the best idea.
I would create a timestampable event, with default columns created_at and updated_at, and change it automatically on each log write.
(this is a Timestampable behaviour from Doctrine)
My_Log_Writer_Db_Timebstampable extends Zend_Log_Writer_Db