Drupal, where i can find footer file? - php

I need to put some code into the site on drupal and i need this code to work on every page of my site. How can i do this? I wanted to find the file of footer and put some code inside, but i can't find it.

There are 3 ways to add PHP code in to the footer.
1> Turn on the PHP filter & enter the code into a block that is positioned in the footer left region.
2> Put the code in the appropriate template file in the sub-theme.
3> Make a module that outputs the code to a block; activate and place the block.
Suppose that you want to add following line to footer area :
©<?php print date('Y');?> Your Company Name - Address of your company.
So best way to do it is make small module like this:
copyright_block.info
name = Copyright Block
description = Shows the (incrementing) current year and company information.
package = Other
core = 7.x
files[] = copyright_block.module
copyright_block.module
<?php
/**
* #file
* This module shows the copyright year and company information.
*/
/**
* Implements hook_help().
*/
function copyright_block_help($path, $arg) {
if ($path == 'admin/help#copyright_block') {
return t('Manually edit to change company information');
}
}
/**
* Implements hook_block_info().
*/
function copyright_block_block_info() {
$blocks = array();
$blocks['show_copyright'] = array(
'info' => t('Company Information'),
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function copyright_block_block_view($block_name = '') {
if ($block_name == 'show_copyright') {
$content = "<p>©" . date('Y') ." Your Company Name - Address of your company</p>";
$block = array(
'subject' => t('Company Information'),
'content' => $content,
);
return $block;
}
}
NOTE: Do not put PHP end tag ?> at the end.

Related

Drupal 8 custom module not showing up in block layout

I have a custom block module for Drupal 8. It is working on my localhost version of drupal (version 8.7.8). When I upload it to the web server (Version 8.7.11), I can enable the module, but it doesn't show up when I try to place the block on the block layout page. I don't have much control of the web server - files are uploaded via a git repository, but other modules I've added work without issues.
My module is just 2 files:
modules/custom/ischool_section_title_level_two/ischool_section_title_level_two.info.yml
name: iSchool Section Title Level Two
description: Provides a block that shows the Level Two title, or Level One if there is no Level Two.
core: 8.x
package: Custom
dependencies:
- block
type: module
modules/custom/ischool_section_title_level_two/src/plugin/block/iSchoolSectionTitlelevel_two.php
<?php
namespace Drupal\ischool_section_title_level_two\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a block that shows the Level Two section title, or Level One title if there is no level Two
*
* #Block(
* id = "ischool_section_title_level_two",
* admin_label = #Translation("iSchool Section Title Level Two"),
* category = #Translation("Custom"),
* context_definitions = {
* "node" = #ContextDefinition("entity:node", label = #Translation("Node"))
* }
* )
*/
//code adapted from http://hussainweb.me/an-easier-way-to-get-the-current-node-in-a-block-plugin-in-drupal-8/
//and https://design.briarmoon.ca/tutorials/drupal-8/getting-the-parent-node-of-a-drupal-8-node
class iSchoolSectionTitlelevel_two extends BlockBase {
public function build() {
$node = $this->getContextValue('node');
if (empty($node)) {
return [
'#markup' => "",
];
}
$L1_Title = $node->getTitle();
$L2_Title = $node->getTitle();
$currentNode = $node;
while (true) {
$parent_node = $this->getParentNode($currentNode);
if (empty($parent_node)){
break;
}
$L2_Title = $L1_Title;
$L1_Title = $parent_node->getTitle();
$currentNode = $parent_node;
}
return [
'#markup' => $L2_Title,
];
}
private function getParentNode($node){
if (empty($node)) return null;
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', ['node' => $node->id()]);
// Because loadLinksByRoute() returns an array keyed by a complex id
// it is simplest to just get the first result by using array_pop().
/** #var \Drupal\Core\Menu\MenuLinkInterface $link */
$link = array_pop($links);
if (empty($link)) return null;
/** #var \Drupal\Core\Menu\MenuLinkInterface $parent */
if ($link->getParent() && $parent = $menu_link_manager->createInstance($link->getParent())) {
if (!method_exists($parent, "getUrlObject")) return null;
$urlObj = $parent->getUrlObject();
if (is_null($urlObj)) return null;
if (!method_exists($urlObj, "getRouteParameters")) return null;
$route = $urlObj->getRouteParameters();
if (empty($route)) return null;
if (!isset($route['node'])) return null;
$parent_node = \Drupal::entityManager()->getStorage('node')->load($route['node']);
return $parent_node;
}
else return null;
}
// cache this block for a definite time.
public function getCacheMaxAge() {
return 43200;
}
}
This was an issue with the capitalization of the folders.
The 2nd file should have been in the /src/Plugin/Block/ folder but instead was in the /src/plugin/block/ folder (missing the initial caps).
On the local windows machine, this didn't make any difference. On the LAMP stack machine it resulted in the block not showing.

Drupal: custom block doesn't appear

I am new at Drupal 7 and I'm creating a Block by code, following this tutorial.
So I create a new module folder at drupal/sites/all/modules and created two files:
block_square_menu.info: it has the info of the module:
name = Block Square Menu
description = Module that create a Block for Square menu, menu shown only in home page
core = 7.x
package = custom
block_square_menu.module: it contains the PHP code:
<?php
/**
* Implements hook_block_info().
*/
function block_square_block_info() {
$blocks = array();
$blocks['block_square'] = array(
'info' => t('Block Square'),
'cache' => DRUPAL_CACHE_PER_ROLE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function block_square_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'block_square':
$block['subject'] = t('block Title');
$block['content'] = t('Hello World!');
break;
}
return $block;
}
After save the files, I go to Admin/Modules, I activate the new module and save the configuration. Now I go to Structure/Blocks and it should list my new Block, but it doesn't do.
I have followed all the tutorial steps and I cleaned Drupal cache, but I'm still having the problem.
First solve your mistake: change the function name where you implemented hook_block_view(), you need to change it as function blocks_square_block_view()
/**
* Implements hook_block_view().
*/
function blocks_square_block_view($delta = '') {
$block = array();
......
After also if not solve then remove 'cache' attribute from hook_block_info() it is optional.
Then follow 2 steps if you missed.
1) Clear all cache (/admin/config/development/performance).
2) Enable your custom module (/admin/modules).
After trying again, your block should appear in (/admin/structure/block).
Solved, the problem was the name of the functions. So the names started with "block_square" which it have the word "block" and it causes some trouble so I changed the all the names with menu_square.
So the functions are now:
menu_square_block_info()
menu_square_block_view($delta = '')
And the files are:
menu_square.info
menu_square.module
The code of the files are:
info:
name = Menu Square
description = Module that create a Block for Square menu, menu shown only in home page
core = 7.x
package = custom
module:
<?php
/**
* Implements hook_block_info().
*/
function menu_square_block_info() {
$blocks['menu_square'] = array(
'info' => t('Block Square'),
//'cache' => DRUPAL_CACHE_PER_ROLE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function menu_square_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'menu_square':
$block['subject'] = t('block Title');
$block['content'] = t('Hello World!');
break;
}
return $block;
}

How can I set $build['#cache']['max-age'] in the following code?

In my drupal 8 custom module I use block to show the next and previous links of current article page. However, links do not change when switching nodes due to the caching. How can I limit the caching for this block?
I can't wrap my head around this.
public function build() {
/**
* {#inheritdoc}
*/
$node = \Drupal::request()->attributes->get('node');
$created_time = $node->getCreatedTime();
$nextprevlinks ="";
$nextprevlinks .= $this->generateNext($created_time);
$nextprevlinks .= $this->generatePrevious($created_time);
return array('#markup' => $nextprevlinks);
}
Just in case someone else brain farts like I just did.
This is how my return now looks:
return array('#markup' => $nextprevlinks,
'#cache' => array("max-age" => 0),
);

Kohana 3.3.3 multi language site

I'm new to Kohana, using version 3.3.3.1, I'm trying to build a simple dynamic site with the content/pages stored in mySQL DB. The site should have multiple languages. I tried searching everywhere for a good solution/module but I couldn't find anything that works with latest version of Kohana. I tried also this: https://github.com/shockiii/kohana-multilang but it's not working on the latest kohana.
I want to put the language in URL like this (and possibly hide the parameter for the default language):
http://www.domain.com/topics/page-name-here.html -- this would be default EN
http://www.domain.com/de/test/some-page-name-here.html
http://www.domain.com/fr/category/other-page-name-here.html
In my bootstrap.php I have the following route (before adding the language logic):
Route::set('page', '(<category>)(/<pagename>.html)', array(
'category' => '.*',
'pagename' => '.*'))
->defaults(array(
'controller' => 'Page',
'action' => 'index',
));
I want to have all this multi-language logic inside a module if possible. But I read about overriding the Request, URL, Route, and other classes to be able to do that.
What is the best way I can do this? What should I do/change and where to start?
I know this is more a general question, but any help or guidance is greatly appreciated.
Thanks very much!
1) add <lang> into routes in bootstrap.php:
Route::set('default', '((<lang>)(/)(<controller>)(/<action>(/<id>)))', array('lang' => "({$langs_abr})",'id'=>'.+'))
->defaults(array(
'lang' => $default_lang,
'controller' => 'Welcome',
'action' => 'index',
));
- define $default_lang somehow - I use siteconfig.php file placed inside application/config -see below.
2) Extend/redefine factory method in Request Controller:
<?php defined('SYSPATH') or die('No direct script access.');
class Request extends Kohana_Request {
/**
* Main request singleton instance. If no URI is provided, the URI will
* be automatically detected using PATH_INFO, REQUEST_URI, or PHP_SELF.
*
* #param string URI of the request
* #return Request
*/
public static function factory( $uri = TRUE,$client_params = array(), $allow_external = TRUE, $injected_routes = array())
{
$instance = parent::factory($uri);
$index_page = Kohana::$index_file;
$siteconfig = Model_Siteconfig::load();
$lang_uri_abbr = $siteconfig['lang_uri_abbr'];
$default_lang = $siteconfig['language_abbr'];
$lang_ignore = $siteconfig['lang_ignore'];
$ignore_urls = $siteconfig['ignore_urls'];
/* get the lang_abbr from uri segments */
$segments = explode('/',$instance->detect_uri());
$uri_detection = array_intersect($segments, $ignore_urls);
if(empty($uri_detection))
{
$lang_abbr = isset($segments[1]) ? $segments[1]:'';
/* get current language */
$cur_lang = $instance->param('lang',$default_lang);
/* check for invalid abbreviation */
if( ! isset($lang_uri_abbr[$lang_abbr]))
{
/* check for abbreviation to be ignored */
if ($cur_lang != $lang_ignore) {
/* check and set the default uri identifier */
$index_page .= empty($index_page) ? $default_lang : "/$default_lang";
/* redirect after inserting language id */
header('Location: '.URL::base().$index_page . $instance->detect_uri());
die();
}
}
}
return $instance;
}
}
I use "siteconfig" array with language definitions:
array(
'language_abbr' => 'cs',
'lang_uri_abbr' => array("cs" => "česky", "en" => "english"),
'lang_ignore' => 'it',
)
3) Extend/redefine "redirect" method in Controller class for automatic language adding:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller extends Kohana_Controller {
/**
* Issues a HTTP redirect.
*
* Proxies to the [HTTP::redirect] method.
*
* #param string $uri URI to redirect to
* #param int $code HTTP Status code to use for the redirect
* #throws HTTP_Exception
*/
public static function redirect($uri = '', $code = 302)
{
$lng = Request::current()->param('lang');
return HTTP::redirect( (string) '/'.$lng.$uri, $code);
}
}
If You would use HTML class (for templates for example), you should probably redefine some other methods like "anchor" for creating anchors with automatic language adding:
<?php defined('SYSPATH') OR die('No direct script access.');
class HTML extends Kohana_HTML {
/**
* Create HTML link anchors. Note that the title is not escaped, to allow
* HTML elements within links (images, etc).
*
* echo HTML::anchor('/user/profile', 'My Profile');
*
* #param string $uri URL or URI string
* #param string $title link text
* #param array $attributes HTML anchor attributes
* #param mixed $protocol protocol to pass to URL::base()
* #param boolean $index include the index page
* #return string
* #uses URL::base
* #uses URL::site
* #uses HTML::attributes
*/
public static function anchor($uri, $title = NULL, array $attributes = NULL, $protocol = NULL, $index = FALSE)
{
//default language
$lng = Request::current()->param('lang');
if ($title === NULL)
{
// Use the URI as the title
$title = $uri;
}
if ($uri === '')
{
// Only use the base URL
$uri = URL::base($protocol, $index).$lng;
}
else
{
if (strpos($uri, '://') !== FALSE)
{
if (HTML::$windowed_urls === TRUE AND empty($attributes['target']))
{
// Make the link open in a new window
$attributes['target'] = '_blank';
}
}
elseif ($uri[0] !== '#')
{
// Make the URI absolute for non-id anchors
$uri = URL::site($lng.$uri, $protocol, $index);
}
}
// Add the sanitized link to the attributes
$attributes['href'] = $uri;
return '<a'.HTML::attributes($attributes).'>'.$title.'</a>';
}
}
I found a great module that is working with Kohana 3.3.3: https://github.com/creatoro/flexilang

Drupal custom module is not working

Here is my custom.info
name = Custom
description = Custom module
core = 7.x
package = Own
and custom.module
<?php
/**
* #file
* An example custom module for selecting, updating and deleting query
*/
/**
* Implementation of hook_block_info()
*/
echo 'Today: \n';
echo date('m/d/Y');
function custom_block_info() {
$block['custom'] = array('info' => t('Custom block'))
return $block;
}
/**
* Implements hook_block_view.
*/
function custom_block_view($delta = '') {
global $user;
$block['content'] = t('Hello #user from IP #host',array(
'#user' => format_username($user),
'#host' => $user->hostname`enter code here`
));
$result = db_select('node','a')
->fields('a', array('title'))
->execute();
foreach($result as $node) {
$items[] = array(
'data' => t($node->title)
);
}
$block['content'] .= theme('item_list', array(
'items' => $items
));
return $block;
}
But this custom module is not displaying data in the sidebar where had i put the block. i have place the echo statement above the code it's not even displaying that echo statement in block can any one tell me how to resolve this????
P.S. I have installed drupal i ve changed nothing in database!
Check if your module is active in the modules list (admin/modules) if so try to put your echo statements in a hook_init like this:
function custom_init(){
echo 'Today: \n';
echo date('m/d/Y');
}
then clear all drupal cache Configuration > Performance > Clear alla caches (admin/config/development/performance)

Categories