What are the render arrays in Drupal

 "Render Arrays" or "Renderable Arrays" are the building blocks of a Drupal page, starting with Drupal 7. A render array is an associative array which conforms to the standards and data structures used in Drupal's theme rendering system.

The core structure of Drupal's Render API is the render array, which is a hierarchical associative array containing data to be rendered and properties describing how the data should be rendered. 

As a  developer you'll use render arrays to describe the content your module controls in order to output it on a page as HTML, or as part of a response in another format like JSON.

Rendering in the Drupal world means turning structured "render" arrays into HTML.

A render array is a classic Drupal structured array that provides data (probably nested) along with hints as to how it should be rendered (properties, like #type). A page array might look like this:


$page = array(

  '#show_messages' => TRUE,

  '#theme' => 'page',

  '#type' => 'page',

  'content' => array(

    'system_main' => array(...),

    'another_block' => array(...),

    '#sorted' => TRUE,

  ),

  'sidebar_first' => array(

    ...

  ),

  'footer' => array(

    ...

  ),

  ...

);

Render array properties

#type -

The element type. If this array is an element, this will cause the default element properties to be loaded, so in many ways this is shorthand for a set of predefined properties which will have been arranged through a RenderElement plugin.

#cache -

Mark the array as cacheable and determine its expiration time, etc. Once the given render array has been rendered, it will not be rendered again until the cache expires or is invalidated. Uses the Cache API. This property accepts the following subproperties:

'keys'

'contexts'

'tags'

'max-age'

'bin'

#markup-

Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, <script> and <style> are not allowed.)

#plain_text -

Specifies that the array provides text that needs to be escaped. This value takes precedence over #markup if present.

#prefix/#suffix -

A string to be prefixed or suffixed to the element being rendered

#pre_render -

An array of functions which may alter the actual render array before it is rendered. They can rearrange, remove parts, set #printed = TRUE to prevent further rendering, etc.

#post_render -

An array of functions which may operate on the rendered HTML after rendering. A #post_render function receives both the rendered HTML and the render array from which it was rendered, and can use those to change the rendered HTML (it could add to it, etc.). This is in many ways the same as #theme_wrappers except that the theming subsystem is not used.

#theme -

A single theme function/template which will take full responsibility for rendering this array element, including its children. It has predetermined knowledge of the structure of the element.

#theme_wrappers - 

An array of theme hooks which will get the chance to add to the rendering after children have been rendered and placed into #children. This is typically used to add HTML wrappers around rendered children, and is commonly used when the children are being rendered recursively using their own theming information. It is rare to use it with #theme.

#sorted -

TRUE if the elements of this render array have been sorted by weight. You can set this to FALSE to force Drupal to re-sort the elements in the array. This is useful when adding a new element to a render array in a preprocess hook.


PHP | gethostname() Function

 The gethostname() function returns the host name for the local machine.

The gethostname() function is an inbuilt function in PHP which returns the host or domain name for the local machine. This function is applicable after PHP 5.3.0 before that there was another function called php_uname function.

Syntax - 

 gethostname()

Example - 

 <?php

   echo gethostname();
?>


Parameters: This function doesn’t accept any parameters.

Return Value: This function returns the host or domain name on success and FALSE on failure.

for more details visit -  https://www.php.net/manual/en/function.gethostname.php

Difference between array_merge() and array_combine() in PHP

array_combine(keys, values)

suppose we have two array, one array contain Name and another array contain age- and we want to create single array with name and age-

so in this case we use array combine - 

a - $fname=array("Ali","Aslam","Raj");
b - $age=array("35","37","43");

Defination - 

array_combine() is used to creates a new array by using the key of one array as keys and using the value of other array as values. One thing to keep in mind while using array_combine() that number of values in both arrays must be same.

$c=array_combine($fname,$age);
print_r($c);

<?php
$fname=array("Ali","Aslam","Raj");
$age=array("35","37","43");

$res=array_combine($fname,$age);
print_r($re);
?>

Result - 

Array ( [Ali] => 35 [Aslam] => 37 [Raj] => 43 )


array_merge(array1, array2, array3, ...)

The array_merge() function merges one or more arrays into one array.

If two or more array elements have the same key, the last one overrides the others.

<?php
$a=array("a"=>"red","b"=>"green");
$b=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>

Result - 

Array ( [a] => red [b] => yellow [c] => blue )



How to Set header in Drupal 8

 Drupal 8 has introduced symfony request reponse object. So anything related to request/response header or body level changes should be using these new system instead of procedural functions like drupal_add_http_header, drupal_send_headers, drupal_page_header.


Drupal 7

function drupal_serve_page_from_cache(stdClass $cache) {

...

...

  // Send the remaining headers.

  foreach ($cache->data['headers'] as $name => $value) {

    drupal_add_http_header($name, $value);

  }


}


Drupal 8

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\HttpFoundation\Response;

function drupal_serve_page_from_cache(stdClass $cache, Response $response, Request $request) {

...

...

  // Send the remaining headers.

    $response->headers->set($name, $value);

 }


}


Drupal 7

drupal_add_http_header();

Drupal 8 

/** @var \Symfony\Component\HttpFoundation\Response $response */

$response->headers->set();


Drupal 7 

drupal_send_headers();


Drupal 8

/** @var \Symfony\Component\HttpFoundation\Response $response */

$response->sendHeaders();


Drupal 7

drupal_page_header();

Drupal 8

/** @var \Symfony\Component\HttpFoundation\Response $response */

$response->sendHeaders();


D7,

<?php drupal_add_http_header('Content-Type', 'text/csv'); ?>


equivalent, in Drupal 8:


<?php 

use Symfony\Component\HttpFoundation\Response;

$response = new Response();

$response->headers->set('Content-Type', 'text/csv');

 ?>


If you want to modify the headers of a response, you need to use an EventSubscriber. Symphony doesn't have a hook system, but instead uses an event/emitter system. Since it's Symphony driving the request/response cycle, you basically needs to integrate with Symphony to do this.

You could take a look at \Drupal\Core\EventSubscriber\FinishResponseSubscriber to see how this is done, the gist of it is this:

/**

 * Add custom headers.

 */

class HeaderResponseSubscriber implements EventSubscriberInterface {

  public function onRespond(FilterResponseEvent $event) {

    $response = $event->getResponse();

    $response->headers->set('Some-Header', 'some value'); 

  }


  public static function getSubscribedEvents() {

    $events[KernelEvents::RESPONSE][] = array('onRespond');

    return $events;

  }

}

Note in the above code all use statements have been excluded, also you need to register your class as a event_subscriber service, this is done in your module's module_name.services.yml file like this:

services:

  name_of_service:

    class: Drupal\Full\Namespaced\Path\To\Class

    tags:

      - { name: event_subscriber }

You can add arguments (other services) that your class will depend on in the services file like normally.

MySQL AVG() Function

 MySQL AVG function is used to find out the average of a field in various records.

To understand AVG function, consider an employee_tbl table, which is having following records −

mysql> SELECT * FROM employee_tbl;

+------+------+------------+--------------------+

|  id  | name | work_date  | daily_typing_pages |

+------+------+------------+--------------------+

|   1  | John | 2007-01-24 |        250         |

|   2  | Ram  | 2007-05-27 |        220         |

|   3  | Jack | 2007-05-06 |        170         |

|   3  | Jack | 2007-04-06 |        100         |

|   4  | Jill | 2007-04-06 |        220         |

|   5  | Zara | 2007-06-06 |        300         |

|   5  | Zara | 2007-02-06 |        350         |

+------+------+------------+--------------------+

7 rows in set (0.00 sec)


Now, suppose based on the above table you want to calculate average of all the dialy_typing_pages, then you can do so by using the following command −

mysql> SELECT AVG(daily_typing_pages)

   -> FROM employee_tbl;

+-------------------------+

| AVG(daily_typing_pages) |

+-------------------------+

|         230.0000        |

+-------------------------+

1 row in set (0.03 sec)


You can take average of various records set using GROUP BY clause. Following example will take average all the records related to a single person and you will have average typed pages by every person.


mysql> SELECT name, AVG(daily_typing_pages)

   -> FROM employee_tbl GROUP BY name;

+------+-------------------------+

| name | AVG(daily_typing_pages) |

+------+-------------------------+

| Jack |        135.0000         |

| Jill |        220.0000         |

| John |        250.0000         |

| Ram  |        220.0000         |

| Zara |        325.0000         |

+------+-------------------------+

5 rows in set (0.20 sec)

PHP script to keep track of the number of times a page is visited by users using cookie

 <?php

    setcookie('count', isset($_COOKIE['count']) ? $_COOKIE['count']++ : 1);

    $visitCount = $_COOKIE['count'];

?>

<html> 

    <head> 

        <title>Count Page Access</title> 

    </head> 

    <body> 

        <?if ($visitCount == 1): ?>

            Welcome! This is the first time you have viewed this page. 

        <?else:?> 

            You have viewed this page <?= $_COOKIE['count'] ?> times. 

        <?endif;?>

    </body> 

</html>

PHP Method Overloading

Overloading in PHP

Overloading in PHP provides means to dynamically create properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types. 

PHP Method Overloading 

It is a type of overloading for creating dynamic methods that are not declared within the class scope. PHP method overloading also triggers magic methods dedicated to the appropriate purpose. Unlike property overloading, PHP method overloading allows function call on both object and static context.

 The related magic functions are.

__call(string $name, array $arguments) –  is triggered when invoking inaccessible methods in an object context.

__callStatic(string $name, array $arguments) – is triggered when invoking inaccessible methods in a static context.

The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method.


<?php
class Wali
{
    public function 
__call($name$arguments)
    {
        
// Note: value of $name is case sensitive.
        
echo "Calling object method '$name' "
             
implode(', '$arguments). "\n";
    }

    public static function 
__callStatic($name$arguments)
    {
        
// Note: value of $name is case sensitive.
        
echo "Calling static method '$name' "
             
implode(', '$arguments). "\n";
    }
}

$obj = new Wali;
$obj->runTest('in object context');

Wali::runTest('in static context');
?>


Output:

Calling object method 'runTest' in object context

Calling static method 'runTest' in static context


Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...