How do I code a MVC3 Helper - database

I’ve just build my first Helper in MVC, it’s very basic and just displays a string where ever I use it. So it’s a .cshtml file in my App_Code folder, I think that is how it's supposed to be set up, with the following code in it,
#helper DisplaySelect() {
#:This text is coming from an helper class.
}
Now I am a wiz with helpers how do I make it do things. E.g.. say I want it to query the database and display something, I would normally do that work in my controller. How do I do that with helpers, do I create a helper controller and then treat the helper like a partial view???
Any help would be greatly appreciated.
Cheers,
Mike.
Thanks guys,
I’ve asked that question before Shark “Why would you use a helper and not a partial view” the answer I got there was a partial view is more for just displaying common HTML where as a Helper can have a bunch of code in it and do all kinds of great processing stuff. Now it seems that’s not true and they are pretty much the same thing, in some respect, except in Link664’s case!
I like what you’re saying Link664 that makes sense as it cleans up the code nicely.
What I was going to do was try and populate a drop down list in a helper and then use it in multiple places, but from my research today that’s not what helpers are for.
Cheers,
Mike.

I'm a bit confused by what you want to do and why you want to do it but I'll give it a go. As you mentioned, you would normally do that work in your controller. It is very poor design to make database calls from a partial view/html helper created client-side.
The #helper syntax is to be used only for simplifying view code, not for implementing code that should be in the controllers or models in the view. See this article for a better idea of when you should be using them.
As for your example, I recommend you pass the data that you want from your controller and create an extension method on HtmlHelper to render it in your view. For example if you wanted to display a list of the most recent 10 posts on your view:
public static HtmlString RecentPostsDisplay(this HtmlHelper html, string name,
List<Post> values, object htmlAttributes)
{
var tag = new TagBuilder("ul");
...
//build list content by looping through values and adding to TagBuilder
...
return new HtmlString(tag.ToString(TagRenderMode.SelfClosing));
}
and in your controller
public ActionResult Blah()
{
ViewBag.posts = _db.GetMostRecentPosts();
return View();
}
Then in your view you can put
#Html.RecentPostsDisplay(ViewBag.RecentPosts)
Hopefully that is what you are looking for, if not update your question so it's not so ambiguous and I'll try again!

Related

Dynamic in xaml Data Template selector

Ok I found this wonderful idea on code project.
link
The idea is great add all your data templates to collection in your list box. Tell each one what to look for (a type) and what data template to use when it runs into that type. The problem is that the included source code is different from the on page code and I can't seen to get any combination of it to work. Even adding the missing quotation marks and changing the type to a local class instead of the non-accessible string and int32 classes.
So the question is. What am I doing wrong?
Bryan
Should be totally redundant when you have DataTemplate.DataType.
(Example)

How to create a simple 'Hello World' with two language in cakephp?

i have been searching for easy sample of multi language project in cakephp.
but i can't find this sample. i think should use i18n but i can't use.
can help me for this sample?
Basically you've to combine the link that Matt gave you, which is the way to use translation on static texts on your website for ex. like links "More..." etc, with Translate behavior, which as mentioned before is based of i18n and will give you the possibility to use Translation on your models stored in DB.
Please check this page in book: http://book.cakephp.org/1.3/en/The-Manual/Core-Behaviors/Translate.html hope this will be helpfull
you need to create a controller in app>controllers> (create the controller here)
Then you need to declare an action in the controller.
For example in the examples_controllers.php controller file:
ExamplesController extends AppController{
function anyName() {
var $uses = null;
$this->set('hello', "hello world");
}
}
to call this from view:
create a folder under views (make sure give the name same as the controller name)
For above controller, the folder name will be examples.
Then in the folder, create "any_Name.ctp" file. (the name should be as the action name)
In that ctp file just call that variable hello. That will do.
I surfed through the web and got a complete solution in here, on my site:
http://www.getallthing.com/cake-php-hello-world/
Best of luck! Cheers!

CakePHP custom function (but not global)

I have a module that handles translations.
It is not bound to any database, the file is purely and simply something like this:
$arr["key1"]="text";
...
I need to make Ajax calls in order to edit that file. That file will be imported each time a page is accessed in order to deliver any text content that I need (it may not be the best thing of the world but it does the job, and it's supposed to be really fast since there's no "XML parsing" kind of thing, it is simply stored in a standard .php file).
To handle these ajax calls that will have actions like Add/Edit operations, I have made a TranslationController that is Model-less:
class TranslationsController extends AppController {
public $uses = array(); // Model-less
public $components = array('RequestHandler');
public $helpers = array('Session');
protected $translationFilePath;
public function setItem() {
}
public function backupFile() {
}
}
My problem is simple: where do I put custom functions that are used to open/write/find in files?
For example I have a function that extracts a key from the line that is being read.
I've seen some posts where we are advised to place the data inside the model but in my case I have no model AND it's these functions are not linked to the data. So it shouldn't be in the model, right? I do not want it to be global.
Thank you for your help.
Why are you not using the built in translation stuff that comes with CakePHP and is based on the more or less standard gettext tools?
What you're doing is just re-inventing the wheel and probably coming up with a non tested customized translation implementation that is obviously lacking feature that CakePHP alreay offers you. For example how do you handle plurals?
CakePHP offers you __(), __d(), __n(), __dn() for translations and the translation files are stored in APP/Locale/ as plain text files and are edited with poedit.
See http://www.gnu.org/software/gettext/ and http://book.cakephp.org/2.0/en/core-libraries/internationalization-and-localization.html
Sounds like a use case for a custom datasource: http://book.cakephp.org/2.0/en/models/datasources.html.
Personally, I would just create a normal PHP class in the app/Lib folder of your application.

How to add a custom field into template.php using Zen sub theme

First time poster here, I'm a designer not skilled at all with php and I have a small issue I don't seem to be able to solve. I'm making a site in drupal 7 using a sub theme on zen.
Btw this is a great CMS, even though people say it's really more a developers CMS. I have no trouble to do what I need using views, rules, display suite etc. So a big thank you for all the developers out there making this such a good CMS. But for this apparently simple problem... no module will help me (I think) and I'm kinda stuck.
So here it is: I'd like to add a subtitle next to the title in all my pages.
So what I did was to add a custom field into the content type basic page (machine name: field_sub_title) which is a simple text field.
I uncommented the following line in my template.php
function mytheme_preprocess_page(&$variables, $hook) {
$variables['sub_title'] = t('field_sub_title');
}
Now my question is how do I load the content of my custom field into that variable?
I know i need to change the second part, but I don't have a clue as into what I need to change this.
Displaying the variable into the the page.tpl.php is something I know about so I only need help with the first part.
{EDIT}
Ok I found how to do this :)
I was looking for a solution in the wrong place. I don't need to change any thing in the template.php file.
Just needed to add this bit of code into my page.tpl.php:
<?php
print $node->field_sub_title['und'][0]['value'];
?>
So I'm posting this here for other Drupal newbies struggling with this....
Your solution may work for now, but there may be a more Drupal-y way to handle a problem like this. If you haven't noticed any problems yet, you may find one or more of the following issues down the road:
Someone who doesn't know php or Drupal theming may need to change the way this works.
If you're like me, you may forget where exactly in code this was implemented.
You may see superfluous markup and/or errors on nodes (content) that do not have this sub-title field (ie. event content not having a sub-title field while basic pages and news articles do).
When you add a field to a content type, it will automatically appear anytime content in that content type is displayed. You should be able to add the sub-title field for your page, event or whatever else you need and have it automatically appear in the markup.
You can 'manage display' of a content type to drag and drop the order for fields to appear. You could take it a step further by using a module like Display Suite to add formatting or layout per-content type.
If you feel like this isn't good enough and the markup for the subtitle must be at the same level as the page title (which is rare), at least add an if statement to make your code check to see if the variable is present before trying to print it. I'd also add a new variable and comments for code readability.
<?php
$subtitle = $node->field_sub_title['und'][0]['value'];
if($subtitle){
print $subtitle;
}
?>
Consider using field_get_items or field_view_value, or at least use the LANGUAGE_NONE constant instead of 'und'
See https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field_get_items/7 and https://api.drupal.org/api/drupal/modules!field!field.module/function/field_view_value/7
This has the added benefit of reducing the number of potential security holes you create.

Drupal: D7 rewriting values returned by views

I have a requirement to perform an indexed search across content which must include a couple of tags in the result. The tags must be a random selection. The platform is Drupal 7.12
I have created a view that manages the results of a SOLR search through the search_api. The view returns the required content and seems to work as intended. I have included a couple of Global: custom text fields as placeholders for the tag entries.
I am now looking for a solution to manage the requirement to randomise the tag values. The randomisation is not the issue, the issue is how to include the random values into the view result.
My current approach is to write a views_pre_render hook to intercept the placeholders which appear as fields ([nothing] and [nothing_1]). The test code looks like the following
function MODULE_views_pre_render( &$view )
{
$view_display = $view->display['default'];
$display_option = $view_display->display_options;
$fields = $display_option['fields'];
foreach( $view->result as $result )
{
$fields['nothing']['alter']['text'] = sprintf("test %d", rand(1,9));
}
}
I am currently not seeing any change in the placeholder when the view is rendered.
Any pointers to approach, alternate solutions etc would be gratefully received as this is consuming a lot of scarce time at the moment. Calling print_r( $view ) from within the hook dumps over 46M into a log file for a result set of 2 items.
There are two possible solutions for your task.
First approach is do everything on the template level. Define a template for the view field you want to randomize. In advanced settings of your display go to Theme: Information. Make sure that the proper theme is selected and find the template suggestions for your field. They are listed starting from most general to the most specific and you can choose whatever suits you better.
I guess the most specific template suggestion for your field would be something like this: views-view-field--[YOR VIEW NAME]--[YOUR DISPLAY NAME]--nothing.tpl.php. Create the file with that name in the theme templates directory and in this template you can render what ever you want.
By default this template has only one line:
print $output;
you can change this to:
print sprintf("test %d", rand(1,9));
or to anything else, whatsoever :)
Second approach is to go with Views PHP module. WIth this module you can add a custom PHP field in which you can do whatever you want. Even though the module hasn't been released it seems to work quite well for the most of the tasks and most certainly for such a simple task as randomizing numbers it will work out for sure.
I stumbled upon this while searching for another issue and thought I would contribute.
Instead of adding another module or modifying a template, just add a views "sort criteria" of "Global: Random".

Resources