I am developing a custom module in Drupal 8. It shows data regarding some organizations that make use of our service. For this I have created a Controller that shows data from the database, which is put there by another module. From the scarce information and tutorials available on Drupal 8 developement I've been able to create the following. In the .routing.yml file I have created a path to this overview table like so (it doesn't properly copy here but the indents are okay):
OrganizationOverview.world:
path: '/world'
defaults:
_controller: 'Drupal\OrganizationOverview\Controller\OrganizationOverviewController::overview'
_title: 'World'
requirements:
_role: 'administrator'
_permission: 'access content'
So now the overview is accessible with the URL site.com/world. But what we want is to show it on the frontpage or show it anywhere else on the site. For this it needs to be a Block. For this I have created an OrganizationOverviewBlock class in OrganizationOverview/src/Plugin/Block/OrganizationOverviewBlock.php which is the proper way according to the PSR-4 standard. The class looks like this:
<?php
namespace Drupal\OrganizationOverview\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Session\AccountInterface;
/**
* Provides a 'OrganizationOverviewBlock' block.
*
* #Block(
* id = "organization_overview_block",
* admin_label = #Translation("OrganizationOverviewBlock"),
* category = #Translation("Custom")
* )
*/
class OrganizationOverviewBlock extends BlockBase
{
public function build()
{
return array(
'#markup' => 'Hello World',
);
}
public function blockAccess(AccountInterface $account)
{
return $account->hasPermission('access content');
}
}
So now it should show up in the Blocks Layout page (after flushing cache, which I do consistently) at site.com/admin/structure/block/ as "Organization Overview Block" where I should enable it, according to plenty sources (Create custom Block, Block API Drupal 8). But it doesn't show up there. I've tried implementing ContainerFactoryPluginInterface with some of those methods but that changes nothing. It does not show up. I've tried making a new test module with a block with the same code but a simpler name and it does not show up. I've copied the code to another platform (the production site) but it also doesn't show up there. What am I doing wrong? Can someone help me? I know Drupal 8 is new but this module really needs to be published soon.
You'll find a working example of building custom block in the Drupal Examples Project. So:
Get the Drupal 8 examples project
Enable the Block Example Module
Double check the working code
With that, you should get your block available in your own module
You can also take advantage of what explained here, where a single php file do the all job. Check files and folders path also.
Not require routing file for custom block.
<pre>
class TestBlock extends BlockBase {
/*
** {#inheritdoc}
*/
public function build() {
return array(
'#markup' => $this->t('Welcome page!'),
);
}
}
</pre>
http://drupalasia.com/article/drupal-8-how-create-custom-block-programatically
You should respect the Drupal coding standard recommendations:
No camelCase naming convention in module name.
OrganizationOverview actually is an error, you should use organization_overview (lowercase/underscore) naming conventions.
Related
I've installed Wordpress inside my Laravel app to manage blog content and other stuff.
Now I need user Laravel authentication for accessing wordpress. Is it possible to do that ? If yes, how?
As per my understanding you need Laravel authentication for accessing wordpress blog. Unauthenticated users should not be able to access it.
If this is the case. Solution is listed below.
Your Blog url: site_url/blog { it can be wordpress folder name inside laravel }
Edit ( routes/web.php )
Route::get('/blog', 'AdminPagesController#blog');
AdminPagesController
namespace App\Http\Controllers;
use Request;
use Carbon\Carbon;
class AdminPagesController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
//It will check if logged in, if not redirect to login page
$this->middleware('auth');
}
public function blog(){
// Simple return, wordpress will handle rest if authenticated person access the url
return;
}
}
The only way I can think of to make this work is reading the index.php from WordPress inside your Laravel controller with
ob_start();
require '/path/to/wp/index.php';
$html = ob_get_clean();
return response($html);
However if you want to use Laravel with a CMS, there are better (native) options like October CMS.
I need a simple way to fallback on a default template if no mobile version exists.
With some regular expressions I recognize mobile platforms and want to render a template with the following pattern:
<template_name>.mobile.html.twig
But if this template doesn't exist, I want it to automatically fallback on:
<template_name>.html.twig
which always exists.
I tried nearly all the answers from this post:
Symfony 2 load different template depending on user agent properties
but with no success. Unfortunately there are no version numbers referenced.
At the moment I am trying to copy and modify the default twig loader.
By the way, What I want to achieve with this is the possibility to deploy different templates for mobile devices by just adding a template of the same name and adding a .mobile.
UPDATE:
http://www.99bugs.com/handling-mobile-template-switching-in-symfony2/
This one is also a good approach. It modifies the format property of the request object which affects the automatic template guessing when you don't specify a template in the controller with the render function (or annotation) but just return an array.
Resulting template name:
view/<controller>/<action>.<request format>.<engine>
So you could switch the request format from html to mobile.html based on the device detection.
The downside of this is that every template needs a mobile.html pendant (which then could just include the non-mobile version if not needed).
UPDATE:
Besides using a custom templating provider there is also the possibility to hook into the kernel.view event.
You could create a service to handle it and then use it in the same way that you do the templating service like so..
Create a service with the templating and request service injected into it..
Service (YAML)
acme.templating:
class: Acme\AcmeBundle\Templating\TemplatingProvider
scope: request
arguments:
- #templating
- #request // I assume you use request in your platform decision logic,
// otherwise you don't needs this or the scope part
- 'html'
Class
class TemplatingProvider
{
private $fallback;
private $platform;
... __construct($templating, $request, $fallback) etc
private function setPlatform() ... Your platform decision logic
private function getPlatform()
{
if (null === $this->platform) {
$this->setPlatform();
}
return $this->platform;
}
private function getTemplateName($name, $platform)
{
if ($platform === 'html') {
return $name;
}
$template = explode('.', $name);
$template = array_merge(
array_slice($template, 0, -2),
array($platform),
array_slice($template, -2)
);
return implode('.', $template);
}
public function renderResponse($name, array $parameters = array())
{
$newname = $this->getTemplateName($name, $this->getPlatform());
if ($this->templating->exists($newname)) {
return $this->templating->render($newname);
}
return $this->templating->renderResponse($this->getTemplateName(
$name, $this->fallback));
}
And then you could just call your templating service instead of the current one..
return $this->container->get('acme.templating')
->renderResponse('<template_name>.html.twig', array());
Can't you check if the template exist before ?
if ( $this->get('templating')->exists('<templatename>.html.twig') ) {
// return this->render(yourtemplate)
} else {
// return your default template
}
OR :
You can create a generic method, to insert in your root controller like :
public function renderMobile($templateName, $params)
{
$templateShortName = explode('.html.twig', $templateName)[0];
$mobileName = $templateShortName.'.mobile.html.twig';
if ( $this->get('templating')->exists($mobileName) ) {
return $this->renderView($mobileName, $params);
} else {
return $this->renderView($templateName, $params)
}
}
with this you can do :
return $this->renderMobile('yourtemplate', [yourparams]);
You can easily do this by harnessing the bundle inheritance properties in Symfony2 http://symfony.com/doc/current/cookbook/bundles/inheritance.html
create a bundle which holds your desktop templates (AcmeDemoDesktopBundle)
create a bundle which will hold your mobile templates (AcmeDemoMobileBundle) and mark the parent as AcmeDemoDesktopBundle
Then when you render a template simply call AcmeDemoMobileBundle:: - if the template exists, it'll be rendered otherwise you'll neatly fall back to the desktop version. No extra code, listeners or anything none-obvious required.
The downside of this of course is that you move your templates out of the individual bundles.
The fallback behavior you describe isn't that easy to implement (we found out the hard way..). Good news is we wanted the same setup as you ask for and ended up using the LiipThemeBundle for this purpose. It allows you to have different "themes" based on for example a device. It will do the fallback part for you.
For example:
Rendering a template:
#BundleName/Resources/template.html.twig
Will render and fallback to in order:
app/Resources/themes/phone/BundleName/template.html.twig
app/Resources/BundleName/views/template.html.twig
src/BundleName/Resources/themes/phone/template.html.twig
src/BundleName/Resources/views/template.html.twig
Edit: so with this approach you can have default templates that will always be the final fallback and have a special template for mobile where you need it.
At my website there is "Login or register to post comments.."
I want to change the message to:
"Login or register to post comments(comments will be moderated).."
Because plenty of spammers are just creating logins to post spam comments.
Although all comments are moderated now. Putting this message will give clear info that spamming may not be possible and spammers will not create logins.
Assuming you are using Drupal 6, the code that creates the comment form is in the file comments.module in the Drupal module directory. Fortunately, the function allows for theming.
What you can do is copy and paste the function theme_comment_post_forbidden($node) and place it in the template.php file in your theme directory. You will also need to rename the function, replacing 'theme' with your theme name.
For example, say your theme name is 'utilitiesindia'. Then you will rename your function to utilitiesindia_comment_post_forbidden.
So, in your template.php file in a theme named utilitiesindia, use this function:
/**
* Theme a "you can't post comments" notice.
*
* #param $node
* The comment node.
* #ingroup themeable
*/
function utiltiesindia_comment_post_forbidden($node) {
global $user;
static $authenticated_post_comments;
if (!$user->uid) {
if (!isset($authenticated_post_comments)) {
// We only output any link if we are certain, that users get permission
// to post comments by logging in. We also locally cache this information.
$authenticated_post_comments = array_key_exists(DRUPAL_AUTHENTICATED_RID, user_roles(TRUE, 'post comments') + user_roles(TRUE, 'post comments without approval'));
}
if ($authenticated_post_comments) {
// We cannot use drupal_get_destination() because these links
// sometimes appear on /node and taxonomy listing pages.
if (variable_get('comment_form_location_'. $node->type, COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_SEPARATE_PAGE) {
$destination = 'destination='. rawurlencode("comment/reply/$node->nid#comment-form");
}
else {
$destination = 'destination='. rawurlencode("node/$node->nid#comment-form");
}
if (variable_get('user_register', 1)) {
// Users can register themselves.
return t('Login or register to post comments(comments will be moderated)', array('#login' => url('user/login', array('query' => $destination)), '#register' => url('user/register', array('query' => $destination)))
);
}
else {
// Only admins can add new users, no public registration.
return t('Login to post comments', array('#login' => url('user/login', array('query' => $destination))));
}
}
}
}
how to change the comment link text " Login or register to post comment" to be shorter ,eg " comment"
Also you can use String overrides module.
In Drupal 6:
Another option is to create a small custom module. This uses hook_link_alter(). This is a small example module to change the title of the "Login to post new comment" link: (Replace every instance of MYMODULE_NAME with the name you choose for the module)
STEP 1: Create a file called MYMODULE_NAME.info and add:
; $Id$
name = "MYMODULE_NAME"
description = "Change the appearance of links that appear on nodes"
core = 6.x
STEP 2: Create file called MYMODULE_NAME.module and add:
<?php
// $Id$;
/**
* Implementation of hook_link_alter
*/
function MYMODULE_NAME_link_alter(&$links, $node){
if (!empty($links['comment_forbidden'])) {
// Set "Login to post new comment" link text
$links['comment_forbidden']['title'] = 'NEW TEXT';
// Add this to allow HTML in the link text
$links['comment_forbidden']['html'] = TRUE;
}
}
STEP 3: Put these files in a folder called MYMODULE_NAME, place the folder in sites/all/modules, and enable the module
If you actually want to stop spammers from creating accounts, you should use something like the CAPTCHA module, since they typically use bots that will ignore instructions in any case.
http://drupal.org/project/captcha
I have developed a blogger-like archive feature (you know, from the feature module).
I want to edit the .module file in order to automatically load the view-template (which is bundled in the feature) into the theme. Is there a way to do it?
On a general level: you should think "features = modules" and leaving theming for... themes! This does not mean that you shouldn't include a template with your feature, but that you should evaluate whether the template you have built suits a general use of your feature or it is specific for your currently used theme. If it is the latter case, you should not package your template file with the feature, but leave it with the theme instead. Just think to how the views module works, to get an idea of what I mean.
[Maybe you are already aware of this and made your considerations to this regards, in which case simply disregard what above. I thought about writing it because your sentence "I want the tpl.php to be actually available for the feature to use it (just as if it were in the active theme folder)" surprised me as general-use templates do not live in the theme folder but in the their module one, and moreover views already provide a "general use" template.]
That said, the way you normally tell drupal to use a given template, is via implementing hook_theme() in your module. In this case - though - given that you are going to override the template defined by views you should implement hook_theme_registry_alter() instead.
Somebody actually already did it. Here's the code snippet from the linked page:
function MYMODULE_theme_registry_alter(&$theme_registry) {
$my_path = drupal_get_path('module', 'MYMODULE');
$hooks = array('node'); // you can do this to any number of template theme hooks
// insert our module
foreach ($hooks as $h) {
_MYMODULE_insert_after_first_element($theme_registry[$h]['theme paths'], $my_path);
}
}
function _MYMODULE_insert_after_first_element(&$a, $element) {
$first_element = array_shift($a);
array_unshift($a, $first_element, $element);
}
Of course you will have to alter the theme registry for your view, rather than for a node (the original example refers to a CCK type).
As on using the template in the views_ui, I am not sure weather the features module already empty the theming cache when you install a feature (in which case you should be good to go). If not, you can trigger it manually by invoking cache_clear_all() from your install file. If emptying the entire cache is too much, you should dig into the views module on how to flush the cache relatively to a single views.
Hope this helps!
Try to add this to your feature .module file
/**
* Implementation of hook_theme_registry_alter().
*/
function MYMODULE_theme_registry_alter(&$theme_registry) {
$theme_registry['theme paths']['views'] = drupal_get_path('module', 'MYMODULE');
}
On the .install file use this
/**
* Implementation of hook_enable().
*/
function MYMODULE_enable() {
drupal_rebuild_theme_registry();
}
Here is my snippet to declare views templates stored in the "template" folder of my "custom_module":
/**
* Implements hook_theme_registry_alter().
*/
function custom_module_theme_registry_alter(&$theme_registry) {
$extension = '.tpl.php';
$module_path = drupal_get_path('module', 'custom_module');
$files = file_scan_directory($module_path . '/templates', '/' . preg_quote($extension) . '$/');
foreach ($files as $file) {
$template = drupal_basename($file->filename, $extension);
$theme = str_replace('-', '_', $template);
list($base_theme, $specific) = explode('__', $theme, 2);
// Don't override base theme.
if (!empty($specific) && isset($theme_registry[$base_theme])) {
$theme_info = array(
'template' => $template,
'path' => drupal_dirname($file->uri),
'variables' => $theme_registry[$base_theme]['variables'],
'base hook' => $base_theme,
// Other available value: theme_engine.
'type' => 'module',
'theme path' => $module_path,
);
$theme_registry[$theme] = $theme_info;
}
}
}
Hope it helps someone.
The person managing a site I'm working on wants to be able to decide what blocks go where. There is already a nice interface for this in Drupal (selecting the region from a drop down) but I'd like to hide certain blocks from this user. These are blocks he should not be able to move around.
Afaik this is not possible via the Permissions. Is there a module that allows fine grained control of what blocks can be managed by whom? I'd rather not write a custom interface ...
Thanks,
Stef
Well, you can create a simple custom module like this (replace my_module with your custom module's name, obviously):
function my_module_perm()
{
return array('view special blocks');
}
function my_module_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'block_admin_display_form') {
if(!user_access('view special blocks')) {
$special_blocks = array( ); // Specially hidden blocks go here
foreach($special_blocks as $block) {
unset($form[$block]);
}
}
}
}
And then:
Add the blocks you want to hide into the $special_blocks array (it's basically the id of the block's div minus block_ )
Create a new account, and possibly a new role for this guy
Permission-wise, the new user's role should have access administration pages and administer blocks on, but shouldn't have view special blocks
Tested on Drupal 6.6, should work on other 6.x versions (and maybe 5.x with a few modifications)
Take those blocks out of regions and embed them into your template manually using module_invoke().
$block = module_invoke('module_name', 'block', 'view', 'block name or ID');
print '<h2>' . $block['subject'] . '</h2>';
print $block['content'];
Maybe give Blockqueue a try? I've never used it, but it appears to cover your use case.