How can I render a specific node as the content for the maintenance page? Given a nid X, how do I have Drupal render it as the content for the maintenance page?

Use the Twig tweak module and create an overwrite template for maintenance-page.html.twig. Then copy & paste stuff from your base theme, but replace {{ page.content }} from the base theme with {{ drupal_entity('node', X) }}
E.g. for stable 9 theme this would look like

  {% if logo %}

  {% endif %}

  {% if site_name or site_slogan %}
    {% if site_name %}

        {{ site_name }}

    {% endif %}

    {% if site_slogan %}

{{ site_slogan }}

    {% endif %}
  {% endif %}

  {% if title %}

{{ title }}

  {% endif %}

  {{ page.highlighted }}

  {# disabled {page.content} here #}
  {{ drupal_entity('node', X) }}

{% if page.sidebar_first %}

    {{ page.sidebar_first }}

{% endif %}

{% if page.sidebar_second %}

    {{ page.sidebar_second }}

{% endif %}

{% if page.footer %}

    {{ page.footer }}

{% endif %}


Which host do I need to fill in the database connection? So I have made a local Drupal site and now I'm moving it to my webhost. In the database connection array:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'localhost',
);

So I filled in all my credentials (driver, database, username,...) but what do I need to fill in after 'host'? Can I just leave it 'localhost' or do I need to fill in the host of my webhosting?

It will depend on your hosting setup and where the DB is located. The host value can be:

A reachable hostname where the PHP code is running (e.g. localhost for your local server)
An IP address (e.g. 127.0.0.1, the ip address normally used for localhost),
A fully qualified domain name (e.g. my-data-base-host.example.com)

Consult your hosting provider on retrieving your DB host connection credentials.


Drupal How to add javascript to ctools modal popup I need to hide some element with some condition using jquery inside ctools modal popup in drupal after popup load. I used drupal_add_js but that not work.

Any suggestion?

You must use: ctools_ajax_command_attr('selector','attr','value'); do perform any kind of actions in popup. For more you can read: http://drupalcontrib.org/api/drupal/contributions!ctools!includes!ajax.inc/7


Is there anything like attached data storage for a view? I'm having hard time using Views with i18n Views. What gets me very irritated is that the translations of global fields (headers, footers, etc.) get lost whenever I make changes to that View. I would feel more comfortable if I could somehow permanently attach to a view some custom data, variables, i18n string arrays, and use them both in Views UI and tpl files.

I would imagine to declare a variable named %my_footer and provide its translations in a module. Then, in a footer I imagine being able to enter something like
This is %my_footer
 or call in a tpl file by saying something like ` and have it rendered in the current translation.

The only thing I would hate to compromise on (as instructed by many users here) is to use PHP code in Views UI text fields.

So, is my scenario possible? I just love to have a single data source...

If you're comfortable in code, you can do that with Panels and ctools contexts.


add a user and role programatically I am using the following code to add a user:

  $roles = user_roles();
  $userinfo = array(
  'name' => 'user2',
  'pass' => '123456',
  'init' => 'user2d',
  'status' => 1,
  'access' => REQUEST_TIME,
  // This is where we are different from the default function.
  'roles'        => array(array_search('student', $roles) => 6),

);
$account = user_save(drupal_anonymous_user(), $userinfo);

I am getting this error message:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 column name is not        unique:
INSERT INTO {users} (uid, name, pass, created, access, status, init) VALUES (?, ?, ?, ?, ?, ?, ?); Array ( [0] => 15 [1] => user2 [2] => $S$DrkIg0KuBFO12eQ9nQ5ViSx4ydfcWS0nS1TMvaTjYyZyfmVniGgh [3] => 1333135061 [4] => 1333135061 [5] => 1 [6] => user2d ) in drupal_write_record()
(line 6975 of

I am wondering if someone can explain what is going wrong with me trying to add a role. ......

drupal_anonymous_user() gives you an object with a uid that is considered empty by PHP. This means, your call to user_save() will try to insert a new user into the database. The insert operation fails, because a user with the name user2 already exists in the database.


Anonymous permissions with Nodeaccess Content type: Webform
Allowed grants: View, Edit
Allowed roles: Anon, authorized, admin

Go to the webform node eg. node/20
Click Grants tab
Tick authenticated and admin users can View, anonymous is unticked
Page is still accessed by anonymous?

node/20:

Global Nodeaccess settings:

At the bottom Webform is ticked to View for anon/authenticated/admin because we want anonymous to see all webforms by default, except one that needs to be logged in. Doesn't really matter because unticking View for anonymous, anonymous can still view the page?!

With every Nodeaccess permission change, Permissions need to be rebuilt every time, for some reason I am not getting the warning message on save, run it at /admin/reports/status/rebuild


How do I programmatically add a field to an existing fieldset that's part of the user entity? I'd like to know how to add a field to an existing fieldset in a user entity

I've seen this example:

Add Fields to Field Group programatically
https://drupal.stackexchange.com/a/71902/1082

$groups = field_group_read_groups(array(
    'name' => 'node',
    'bundle' => 'article',
    'view_mode' => 'full'));
  $your_group = $groups['node']['article']['form']['group_your_group'];
  $your_group->children[] = 'field_your_new_field';
  field_group_group_save($your_group);

But I'm unsure what to supply for 'name' and 'bundle' and also what to supply for the line

$your_group = $groups['node']['article']['form']['group_your_group'];

I think you should try hook_form_alter. try this may it helpful to you.

function mymodule_form_alter(&$form, $form_state, $form_id) {

  // Check your form-ID
  if ($form_id == 'user_profile_form') {
    // Creating custom field
    $form['new_field'] = array(
      '#weight' => 4,
      '#type' => 'textfield',
      '#title' => t('New Field Name'),
    );
  }
  // Attach to the existing group
  // Suppose group machine-name is group_general
  $form['#group_children']['new_field'] = 'group_general';
}


Form elements created with AJAX aren't sending values through form_state I've created a AJAX block form that allows a user to specify the number of fields they would like to have available. like so

    $form['columnNum'] = [
        '#title'   => t('Number of Columns'),
        '#type'    => 'select',
        '#options' => [
            1         => '1',
            2         => '2',
            3         => '3',
        ],
        '#default_value' => $this->configuration['columnNum'],
        '#empty_option'  => t('-select-'),
        '#ajax'          => [
            'callback'      => [$this, 'columnCallback'],
        ],
    ];

    $columns = $this->colFieldGen($this->configuration['columnNum'], $this->configuration['columns']);

    $form['column_wrapper'] = [
        '#type'       => 'container',
        '#attributes' => ['id' => 'column_wrapper'],
        $columns,

    ];
return $form;

the colFieldGen form, generates the number of fields like so.

public function colFieldGen($num, array $config) {
    for ($i = 0; $i < $num; $i += 1) {
        $numTitle    = $i+1;
        $columns[$i] = [
            $i             => [
                '#type'       => 'details',
                '#title'      => t('Column '.$numTitle),
                '#open'       => FALSE,
                'columnTitle' => [
                    '#type'      => 'textfield',
                    '#title'     => t('Column Title'),
                ],
            ],
          ];

And below is the callback.

public function columnCallback(array&$form, FormStateInterface $form_state) {
        $response = new AjaxResponse();
        $columns = $this->colFieldGen($number, $this->configuration['columns']);

        $content = [
            '#type'       => 'container',
            '#attributes' => ['id' => 'column_wrapper'],
            $columns,
        ];

        $response->addCommand(new ReplaceCommand('#column_wrapper', $content));
        return $response;
    }

I'm using the replace command to replace the fields that were present in the container, with a set of new fields. However any of the data in the new fields aren't sent through form_state. Fields that existed already like $form['columnNum'] are sent through $form_state just fine.

Is there a way to see values of ajax created form elements in $form_state? Or is there a better way to do this entirely?

NOTE: This is all being performed in a blockForm if that makes any difference.

UPDATE:

I changed the field generator to be based on a form_state variable like so

if (empty($form_state->getValue('number'))) {
    $form_state->setValue('number', 1);
}

$columns = $this->colFieldGen($form_state->getValue('number'), $this->configuration['columns']);

and then in the AJAX call performed this

public function columnCallback(array&$form, FormStateInterface $form_state) {
    $form_state->setValue('number', 10);
    $form_state->setRebuild(true);
    return $form;
}

But the form never rebuilds with the new amount of specified fields. I receive the progress animation on change, so I know something is firing. I just get no results. To see if the form was attempting a rebuild I added

if (empty($form_state->getValue('number'))) {
    $form_state->setValue('number', 1);
} else {
    die($form_state->getValue('number'));
}

to have the form fail if the form_state already exists but it never dies.

Move all form building activities from the callback to the form build function.

The form elements you add in the callback go directly through javascript to the DOM in your browser. You see them as normal form elements, but the form API doesn't know that they are in your browser and will ignore them.

Edit for the questions in comments:

In the form build function you know that you are rebuilding because $form_state is filled with data. On the first run it is empty.

You have the number of columns in the value of the select element.

You should wait with handling of the configuration data until submit.

In general an ajax form should have the same code in form build as a normal form, because if jquery is not available, ajax will fallback to a normal rebuild.


Translate page.tpl.php strings I have a custom slideshow and the phrases are all in page.tpl.php (please see figure attached)
But they are not dynamic, so they are in PT.

Now I have a multilingual site (I installed all the necessary modules) and everything in my site is working great.

My question is: How can I translate those strings in page.tpl.php to English everytime I switch to EN in my site? Does it require much coding?

Thanks!

Just edit the page.tpl.php file and wrap all text in t() function.

For example:

This is a sample string.

Turns into:

<?php print t('This is a sample string.'); ?>

EDIT: this will make those strings translatable. After that, use the translation interface to find those strings and translate them in other languages.
If your original question was about where you can translate those strings in the admin, let me know and I'll update the answer.


How to distinguish between drush and HTTP request How can I distinguish whether a function is called from drush or by a real HTTP request?

From drush.php:

function_exists('drush_main') may be used by modules to detect whether
they are being called from drush.  See http://drupal.org/node/1181308
and http://drupal.org/node/827478


In which order should one build up a multilingual site? I'm planning to convert (better rebuild) an existing site based on MediaWiki and a phpBB3 Forum to a shiny new Drupal based site. The MediaWiki is multilingual, though most content is in German.
My experience with Drupal is basic. I've done basic things with other CMSs and am familiar with PHP, MySQL and HTML.

A couple of weeks ago I set up a new Drupal 7.10 instance (locally).
My first try was migrating the existing MediaWiki content as articles into Drupal. I failed badly and could not find a way (on the web) realising this.
I ended up building the central and essential MediaWiki templates (which are very individually) as content templates. That worked pretty satisfying and I accepted to manually copy&paste the content in a later step (has somebody a monkey for me?).

Then I tried migrating the existing phpBB into a Drupal-based forum via a module (failed) and finally agreed on bridging those. The modules for this are actively developed and I let some more time pass as to get them more mature.

Beside those two central topics of the desired Drupal site, multilingual content is essential as well. For the wiki-like content even more than for the message board. In case of the wiki content, the users will be creators of new and translators of existing content.

While trying different ways and different modules for all the functionality, I have to admit, that I got hopelessly lost.
I'm not asking for a specific set of modules, I should use. I would have to define all functionality of the desired Drupal site and that's not the core of this question.

My question is rather: In what order should I build up the site's functionality?
That is, after having set and defined the access and user groups, should I first concentrate on the multilingual backend and translation pipeline (e.g. modules for multilingual content and translation)?
Or should I first get the templates for the wiki-based content right and implement the multilingual thing atop of that?
Both is somehow closely interconnected and -- as mentioned above -- I got lost while finding my own way.

I hope, this question is not too broad and vague. If so, please let me know and I try even harder getting it more specific.

I would suggest starting with setting up the multilingual backend. Besides what Drupal core already offers you probably want to use the i18n module. Then you could move on to content migration. If there is no module that can do that for you I'd suggest writing a PHP script rather than manually copy/paste-ing (seeing as the amount of data seems to be fairly large). You could make use of either node_save() or drupal_form_submit() for this task. The first option is a quicker way of adding nodes while the second mimics more closely normal node creation by invoking additional hooks. There's a solid amount of information about using them to create nodes programmatically available on the web that you can make use of. At what point to work on appearance (templates and theming) shouldn't matter too much, but it's probably somewhat easier at later stages when you already have the content to work with.


How to show token value in Webform confirmation In Webform > Form settings > Submission settings > Confirmation message, how can I show a webform token as part of the confirmation message? Something like:

  Hi %value[name], thanks very much for joining our event!

Use Webform tokens module

  Webform Tokens provides tokens for user form submissions for forms
  created with the module Webform 3.

Or upgrade to Webform4 which has this feature inbuilt.


How to Fix/Clean Lambda warnings/errors from Views PHP I used views php to get the values from the field collection of the saved node in order to create a front end select list on views.

It does what I wanted it to do but there are a bunch of warnings and notice and I would like to clean it.

This is just a part of the warning and notice that appeared.

And this:

It's a repetition of errors for my different variables.

This is an example of my code:

<select class="number_of_person">

    <?php
    $wrapper = entity_metadata_wrapper('node', $row->nid);
    if (isset($wrapper->field_criteria)) {
    $prices_number_of_person= array();
    $min_and_max_number_of_person = array();
        foreach ($wrapper->field_criteria as $i){
              $price_loop1[] = $i->field_price->value();
              $min_and_max_loop1[] = $i->field_criteria_name->value();

        }
         $prices_number_of_person= implode(",", $price_loop1);
         $min_and_max_number_of_person = implode(",", $min_and_max_loop1 );

         $split_min_and_max_number_of_person = explode(",", $min_and_max_number_of_person );
         $split_prices_number_of_person = explode(",", $prices_number_of_person);

         $length_number_of_person = count($split_min_and_max_number_of_person);

        for ($number_of_person=0; $number_of_person < $length_number_of_person; $number_of_person++) {

        if($split_prices_number_of_person[$number_of_person] !="" ){
         echo '<option value="'.$split_prices_number_of_person[$number_of_person].'" class="options">'.$split_min_and_max_number_of_person[$number_of_person].'... + ₱ '.$split_prices_number_of_person[$number_of_person].'</option>';
        }

         else{
          echo '<option value="'.$split_prices_number_of_person[$number_of_person].'" class="options">'.$split_min_and_max_number_of_person[$number_of_person].'</option>';

              }
         }

     }
    ?>

    </select>

I was wondering if there is something that I need to add to my code to get rid of the warning and notice?

Thank you in advance!

Before try to explode/implode  check that data exist in them
as example

"$price_loop1"
 if($price_loop1)
     $prices_number_of_person= implode(",", $price_loop1);

and for explode

  if($prices_number_of_person)
      $split_prices_number_of_person = explode(",", $prices_number_of_person);


Theme hook suggestion for nodes within a menu link? I need nodes within a certain place in my menu to use a new node TPL file.

My menu is hierarchical like this.

link1
link2
link3
-linkA
-linkB

I need nodes whose menu link is link3, linkA or linkB to use these new TPL files.

I have 2 content types whose nodes can be in the menu and I need a different TPL file for each content type. These nodes can also be outside of the menu in which case they should use the normal TPL file.

So a node of content type A which has a menu link of link1, link2 or no menu link would use the default node--typeA.tpl.php.

A node of content type A which has a menu link of link3, linkA or linkB would use node--typeA--special.tpl.php

A node of content type B which has a menu link of link1, link2 or no menu link would use the default node--typeB.tpl.php

A node of content type B which has a menu link of link3, linkA or linkB would use node--typeB--special.tpl.php

As I'm extending the node not page TPL I started with this:

function MYTHEME_preprocess_node(&$variables) {
  $variables['theme_hook_suggestions'][] = 'node__SOMETHING';
  kpr($variables);
}

Im assuming I need an if statement around the 2nd line which checks if the node is typeA and also in the correct place in the menu? However I had a look at the $variables on the screen and I couldn't see anything I could use to find out the menu position.

I then looked at preprocess_page to see if it had a variable I could use. There is an array called main_menu which is the name of my menu. But it contains 0 elements.

function MYTHEME_preprocess_page(&$variables) {
  kpr($variables);
}

As this requirement may get even more complex, I would suggest adding a taxonomy selection to the content types in question. You can use this to assign the proper theme suggestions as the value will be saved on the node object. You may also want to check out ThemeKey.


reCaptcha has blocked me out of my website I had enabled reCaptcha yesterday on my site. The keys that I had entered were generated for my real site while I had been working using my temp.

My site displayed this message continuously:

  Input error: Invalid referer

I didn't take it seriously for I thought it will be resolved when I start using the real url for my site.

Today, when I logged out, I realized that I was wrong. I am not able to log inside my administrator account because the captcha is blocking me out. This is the message that I got when I tried to enter the site using my login id password:

  The answer you entered for the CAPTCHA was not correct.

I can not disable the captcha on login screen because I am not able to enter the site. Should I delete the captcha module from my directory right way? Or will that screw up things further because I won't be able to clear the cache of my website?

If you can use SSH, or other shell, it's easy:

Install Drush. On Ubuntu, follow this document. Or simply unpack it and add it's directory to system's PATH variable (OS dependant).
Enter your Drupal's directory
Execute drush dis recaptcha

I strongly advise this approach, it may be a bit hard to set up initially, but drush is a powerful tool that can help you in future.

If you cannot, but you can use SQL client, it's not so bad too:

Login to your Drupal database with your SQL client
Back up your entire database
Execute UPDATE system SET status = 0 WHERE name = "recaptcha";

In both cases, you should be able to login, and uninstall reCaptcha module via UI to get rid of messed configuration data.


How do you run Drupal core-patches and is there a single, general way? When I run contrib-module patches I download the patch file, put it in the modules folder, navigate to there with the Linux-bash and then do git apply patch patch_file_name.

I never ran a core-patch though and I believe it's a bit different as there isn't necessarily a single module to act upon.

So, is there a one single way to run Drupal core patches and how it should be done without damaging anything? Maybe just put it in the site root folder and run it?

I ask this here so people who write such a question in Google could find this info easily.

Drush make is a method to maintain patched releases of contrib and core. It is the only organized, non-custom, method I know of for patch management. The makefile is self-documenting. By "self-documenting", I mean that the makefile contains a list of modules, their versions, and URLs of applied patches.

Create a makefile of an existing Drupal site with:

drush generate-makefile mysite.make

Note, as far as I know drush generate-makefile will not detect applied patches. The example makefile demonstrates how to reference patches in your makefile.


Using Drupal Default jQuery only on node form? I need to use the jQuery 2.0 in my drupal 7 site, so i have unset two drupal jQuery files and added the latest version of jQuery using this code in my template.php file so it will not affect the views or other core parts(uses Seven theme):

function mytheme_js_alter(&$js){
    unset($js['misc/jquery.js']);
    unset($js['misc/jquery.once.js']);
    drupal_add_js('http://code.jquery.com/jquery-2.0.0.min.js');
}

Everything goes fine but just found that it breaks the tagging auto-complete feature, to solve this problem i wish to remove the jQuery 2.0 and add the jquery.js and jquery.once.js file again only when the page is a form that has a ID news_node_form so i made some change with no luck:

function mytheme_js_alter(&$js){
    unset($js['misc/jquery.js']);
    unset($js['misc/jquery.once.js']);
    drupal_add_js('http://code.jquery.com/jquery-2.0.0.min.js');

    function mytheme_form_news_node_form_alter(&$form, &$form_state, $form_id){
        drupal_add_js('http://127.0.0.1/drupal7/misc/jquery.js?v=1.4.4');
        drupal_add_js('http://127.0.0.1/drupal7/misc/jquery.once.js?v=1.2');
        unset('http://code.jquery.com/jquery-2.0.0.min.js');
    }

}

Any idea how to solve this problem?

You cannot use an updated/upgraded version of jQuery 'just like that' with Drupal. Believe me, it might look everything is working fine, but eventually its gonna break.

As Suggested by Motot, you can use https://drupal.org/project/jquery_update module to use an updated version of jQuery. But I don't think the even the dev version of jquery_update module supports 2.0

What you can do is, use jQuery's no-conflict feature. Here is a detailed documentation on using different JS libraries along side jQuery https://drupal.org/node/1058168 (You want to use jQuery 1.x & 2.0)

And yes, there is a module for that as well - https://drupal.org/project/jqmulti


Increase max length of a text field? Is there a simple way to increase the maxlength value of a plain text field that has data in it already?

To directly answer the question, there is no simple way in Drupal 8 to modify the schema for a field once it's been populated with data.

But, there is a more complicated way to manage it.

We've used the work done here by J-P Stacey to update a field in our platform.

ALTER the database tables directly using raw SQL.
Change the site configuration for the field.
Force the current, "desired" schema records in Drupal to match.
Force the "most recently installed" schema records to also match.

Additional information can be found in this article written by Marcus Bernal.


How to add any plugin to ckeditor manually? I'm trying to add a new plugin ckwebspeech in ckeditor module. Here is the plugin which I want to add.

So, that the final editor will look like mentioned in screenshot. Is there any way to add this manually?

The manual process is described on that plugin page itself, as you can see on the instruction page in first image(red circle.)

If you click that link which you have provided in your question, you can see the Download option on that page. If you click it will download and it will open up a new pop-up window.

1. As you can see in the image. Copy that file and paste to that path.

So, I did copy and paste at at module/ckeditor/plugins/ckwebspeech

2. Now second step says, put this code config.extraPlugins = 'ckwebspeech'; So, I went to admin/modules/ckeditor/config. I did choose either Full or advanced, whichever my site is using. Clicked edit, went to Advanced options And paste the second step as shown in the step-2. Saved it ans clear the cache.

3. Now again went to same place at described in step-2. Instead of Advanced option went to Editor appearance and move the webSpeechSetting and webSpeechEnabled button to the custom toolbar as shown in following image.

4. Now if I scroll down further on the same page, I will have all option of the plugins then I enabled that plugin as shown in following image.(see second option which i checked). Saved cleared cache.

5. Now went to any page where I can see my editor, and, it showed up in editor.


Should I use underscore or hyphenated tokens? When displaying tokens that can be used I often see this type of thing:

I have seen that there are a number of d.o issues on this; one in particular is extensive and detailed. But is there a reason to use the dashed one or the hyphened one? There may be a D8 migration reason for all I know?

Tokens are just arbitrary strings, Drupal doesn't mind which characters are used to indicate separation of words (some characters are blacklisted, like ], but for the most part that's true). All that matters is the module that provides them, e.g. Entity in this case, knows how to interpret them when it needs to.

The issue you referenced has two key core contributors debating it, without a resolution, so there simply isn't a standard to apply to this.

Both sets of token provide the same data, so it's a matter of personal preference which one you use.

Since the Entity module provides more field tokens than core modules do, you might end up standardising your site better over time if you choose the ones provided by Entity. But YMMV, in real terms it doesn't matter.


Views#3 custom handler error I'm learning how to implement a custome Views 3 field handler.

Using the following handler code:

class views_handler_filter_sub_nodes extends views_handler_field_custom{

    function options_form(&$form, &$form_state){

        drupal_set_message('My customer handler is responding', 'warning');

        parent::options_form(&$form, &$form_state);
    }
}

I get the following error, repeated twice:

Deprecated function: Call-time pass-by-reference has been deprecated in _registry_check_code() (line 3119 of /var/www/My-Site/includes/bootstrap.inc)

I have removed the & symbols from the arguments. The errors go away but so do all the configuration fields in my View component, as illustrated below:

Can anyone help, please?

Huh? It's been a year and no one has found the error referred to by the message ("Call-time pass-by-reference").

Leave

function options_form(&$form, &$form_state) {

unchanged.

And change this:

parent::options_form(&$form, &$form_state);

to:

parent::options_form($form, $form_state);

and your error should go away.

Briefly (for those who are new to user defined functions, as it relates to this issue)...

Function declaration

A function's arguments are defined in the function's declaration (the line that begins with the function keyword). They are a list of PHP variables the function expects to receive from the caller (see  Function arguments  in the PHP manual for more information). The function declaration determines how many arguments are expected, their datatypes, whether they are required or optional, and whether they are passed by reference or not, among other things.

You have surely noticed the $form and $form_state variables used in lots of form-api function declarations, sometimes with and sometimes without a preceding &. Each & tells the function that that argument will be passed to it by reference. This means the function does not receive a copy of the variable from the caller (as usual), but a pointer to it.

A function may change the contents of references directly from within the function, while a copy is private to the function and must be returned, if the function want its changes to be available to the function that called it (of course, the caller must know what to do with the returned data). Any changes made to reference variables remain after the function ends.

Function execution

When a function is called/executed, the & MUST be omitted, otherwise you get the aforementioned "Call-time pass-by-reference" error. The function declaration determines if it's a reference, not the caller.


How to get my button in a dialog click? I have added the following JS to a node form, it clones the submit button but clicking it inside the dialog (which does show up) doesn't submit the form in the browser, just nothing happens when the button is clicked. I also tried adding the button server side, same results:

(function (window, Drupal, $) {
  Drupal.behaviors.drafter = {
    attach: function attach(context) {
      var button = $('#edit-submit');
      var newbutton = button.clone().prop('id', 'edit-submit-drafter');
      button.click(function () {
        $('#drafter-elements').toggle();
        var confirmationDialog = Drupal.dialog('#drafter-elements', {
          resizable: false,
          closeOnEscape: false,
          create: function () {
            $(this).append(newbutton);
          },
          beforeClose: false,
          close: function (event) {
            $(event.target).remove();
          }
        });
        confirmationDialog.showModal();
        return false;
      })
    }
  }
})(window, Drupal, jQuery);

Where drafter-elements come from:

$form['drafter'] = [
  '#prefix' => '
',
  '#suffix' => '
',
  '#attached' => ['library' => ['drafter/drafter']],
];
$form['drafter']['save_in_place'] = [
  '#title' => 'Confirm',
  '#type' => 'checkbox',
  '#description' => t('By default a new draft will be created.'),
];

With a tiny CSS:

#drafter-elements {
  display: none;
}

(Here's the drafter repository should someone want to try it / fix it.)

for me that submits the node:

(function (window, Drupal, $) {
  Drupal.behaviors.drafter = {
    attach: function attach(context) {
      var button = $('#edit-submit');
      var newbutton = button.clone().prop('id', 'edit-submit-drafter');
      var confirmationDialog = Drupal.dialog('#drafter-elements', {
        resizable: false,
        closeOnEscape: false,
        create: function () {
          $(this).append(newbutton);
        },
        beforeClose: false,
        close: function (event) {
          $(event.target).remove();
        }
      });
      newbutton.click(function (e) {
        button.click();
        confirmationDialog.close();
        return true;
      });
      button.click(function () {
        if (!confirmationDialog.open) {
          confirmationDialog.showModal();
          return false;
        }
      });
    }
  }
})(window, Drupal, jQuery);


What should the dynamic query for the following SQL string be? What should the dynamic query for the following SQL string be?
SELECT p.id, p.name, GROUP_CONCAT(s.name) AS site_list
FROM sites s
INNER JOIN publications p ON(s.id = p.site_id)
GROUP BY p.id;

$query = db_select('sites', 's')
  ->fields('p', array('id', 'name'))
  ->groupBy('p.id');

$query->addExpression('GROUP_CONCAT(s.name)', 'site_list');
$query->join('publications', 'p', 's.id = p.site_id');


What might be stopping this Contextualised Filter work in Block (please)? I am stuck making a contextualised filter in Block View (and I guess if I knew my question, I would also know my answer).

The view comprises

A set of images which I can see in the View before I set up the Contextualised View with their tags
Relationship with Content: Taxonomy terms on node, choose the correct Taxonomy, and check required
Under Contextual Filters, Taxonomy:name
Default View
Raw value from Url
Position is tricky  .. the path alias is albums/[node:title] but this is a multilingual site so en/albums/[node:title] (I have tried positions 1,2, 3)
Check Specific Validation Criteria
Validator:Taxonomy
Check correct taxonomy
Term Name
Tested check/unchecked spaces to hyphen
Additional information
The tag is input exactly as the [node:title]
If the [node:title] is Barking Dogs, then that is the tag. So the [node:title] is changed by Drupal to barking-dogs and so is the tag.  But the name of the tag is not.  The name of the tag remain Barking Dogs.
Results
When I put a tag name into the preview query, I get the correct results
a.  For one word tags
b.  When I type the phrase with space e.g. The Funniest Cat
When I type the shortened phrase, i.e., funniest-cat, I get no results. Checking the transform spaces into hyphens doesn’t help.
When I use the path alias /albums/[node:title], I get the title, such as The Funniest Cat, but no Block.
The Block itself works – If I request a summary when validation fails, that is displayed.  But no contextualised filter.

I am out of ideas. If anyone can spot where I have gone wrong, I’d be grateful.  Or have an idea how to test, as grateful.
Thanks.
Jo

Found the answer - a logical issue rather than a question of using the controls.

The key was to reverse the order of bringing in content.  Set the main content-type as galleries, then use an entity relationship (set that up first) on Relationship to bring in fields from images and sort on them.

With this procedure, Views can use a Contextual filter for the Galleries. I will wirtie it out more fully on my blog.


Drupal implementing an advertising takeover with page background image I need to implement a background image advertising takeover that surrounds the page content in drupal. It's similar to the ones on ign (screenshot attached below).

The only ways I can think of seem really hacky, such as using a view block to display one result of a custom content type containing the image and showing the view in a custom region that spans the background of the page.

Can anyone think of a better way? It needs to be easy to set up in the CMS for an administrator and they need to be able to create different takeovers for different sections of the site.

Thanks

In your theme's preprocess_page() hook you could set a variable that is accessible in your page.tpl.php file.  Basically something like:

function YOURMODULE_preprocess_page(&$vars) {

  $vars['background_image']=make_me_a_background_for_page($_GET['q']);

  // other page preprocessing goes here

}

where make_me_a_background_for_page() is a custom function that returns a path to an image based upon the page being viewed.  You can then use that variable however you want to create the background.

One way would be to put a quick div in the page somewhere like...

<?php if (!empty($background_image)): ?>

<?php print $background_image; ?>

<?php endif; ?>

and have it hidden in css:

#use-this-background-image {
  display: none;
}

and then use jQuery to set the body's background to it:

// Drupal Behaviors Wrapper here :)

  if ($('#use-this-background-image').length) {
    $('body').css('background-image','url("' + $('#use-this-background-image').text() + '")');
  }

// Drupal Behaviors Wrapper here :)

An added bonus of doing it in this somewhat convoluted way is the background image isn't loaded until after your page is, so it pops in after the content, which, to me at least, is nicer looking than watching a big background load and THEN the content.


Insert data into entity programmatically I've installed contact storage module, it's provide storage for Contact messages which are fully-fledged entities in Drupal 8.
What I want to do, is to insert data programmatically from my custom module into the entity of the contact storage

Yep. Just use any of the methods available to create the entity and save it.

use Drupal\contact\Entity\Message;

$message = Message::create([
    // And other fields required...
    'subject' => 'Subject',
    'message' => 'Message...',
    'recipient' => 1,
]);
$message->save();


Search/filter box for Views on separate page I am running the latest versions of Drupal 7 and Views 3.

I have a Views catalog with exposed filters for two different fields. What I would like to accomplish is to have a search box for the catalog on a different page (let's say the front page) with one field only - searching/filtering within either of the two fields. Upon submission, the user is taken to the catalog page with the results showing, and the exposed filters are free to be used again.

The only way I've been able to approximate this is to have a Global Combine fields filter running which is hidden on the catalog page, and utilized by a search filter box that I hard coded via a module. But the fact that the hidden combine field will actually have content in it once the page is loaded compromises the functionality of the visible exposed filters.

Is there a way to go about doing this?

Hope you know, in views there is one option called "EXposed form in Block"

Just enable this option then you can display the exposed filter block anywhere.

Hope this one helps you


Programmatically create a paragraph entity reference field I need to create a config page, that is able to add social media information ( name and icon ), the user must be able to add as many social medias as it wants. To do so, I'we created a paragraph with two fields: name & icon, then I want to add this paragraph as an entity reference field programmaticaly in my config page, the paragraph machine name is social_media.

I tried this, but it didn't work:

public function buildForm(array $form, FormStateInterface $form_state) {

    $form['social_media_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Social Media Configuration'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    ];

    $field = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Type'))
      ->setDescription(t('The Paragraphs type.'))
      ->setSetting('target_type', 'paragraph')
      ->setSetting('handler', 'default')
      ->setSetting('handler_settings',['target_bundles'=>
                      ['social_media'=>'social_media']
          ]);

    $form['social_media'] = $field;

    return parent::buildForm($form, $form_state);
  }

the page is shown but without a form:

The following code did the trick for me when adding the field to custom entity. This provides a reference to the paragraph and the revision. Just to note out that when the paragraph is edited, the reference field will still refer to the old revision. The field type is entity_reference_revisions and my paragraph type

$fields['social_media_id'] = BaseFieldDefinition::create('entity_reference_revisions')
  ->setLabel(t('Skill'))
  ->setDescription(t('The ID of the skill'))
  ->setRevisionable(TRUE)
  ->setSetting('handler', 'default:paragraph')
  ->setSetting('handler_settings', ['target_bundles' => ['social_media' => 'social_media']])
  ->setSetting('handler_settings', ['negate' => 0])
  ->setTranslatable(TRUE)
  ->setDisplayOptions('form', [
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => [
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ],
  ])
  ->setDisplayConfigurable('form', TRUE);


How do I disable Twig and block cache for a specific module? I'm working on a module in Drupal 8 which retrieves time sensitive data from an external REST api. The data is processed and forwarded to a Block. The final data is sent to a Twig template like so:

...

public function build() {
  $build = [];

  $build['ticker_block'] = [
    '#theme' => 'module_theme',
    '#data' => $myService->data(),
  ];

  return $build;
}

This doesn't work on the production environment where cache is enabled and the rendered data shows up as stale. How do I disable cache for my module only, and do I have to do it for both the Twig template and Block plugin?

You can control the cache in the render array with the #cache element.

To disable the cache add:

$build['#cache']['max-age'] = 0;

In this case the block will not be cached for logged in users or anonymous users with a session.

If you want to disable the cache for anonymous users without a session:

  Disable it either by uninstalling the page_cache module completely or
  by triggering the kill switch, see
  How can I prevent a particular page being cached? for example.

The caching of the twig code is not connected to this, the twig code is only cached once, the first time it is used after you cleared the cache.

(edit acc. to comments of Berdir)


How can I get all fields and values of a node at once? I know how to get a particular field (title field) of a node by following code:

$publications = \Drupal::entityManager()->getStorage('node')->load($node_id);
$title = $publications->getTitle();

But I need to get all fields and values in that particular node. I tried print_r($publications). Is there any way to get this?

This is how you can add all values in a custom array. The EntityManager class and the entity.manager service are deprecated; you should use the entity_type.manager service instead.

$publications = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->load($node_id);

foreach ($publications->getFields() as $name => $field) {
  $myFields[$name] = $field->getString();
}

kint($myFields);

You need to improve this code because for some field types that can be different.

For multi-value fields you use $field->getValue()
For entity reference fields, $field->entity->field_name->value


Embedding a custom form in node.tpl.php does not trigger validation I'm trying to render a custom form in node.tpl.php.

The form is rendered properly and submit handler works.
However, the validation handler is not triggered properly upon submitting. If I refresh the page, the error message is only then displayed.

Here's the sample module code:

function sample_custom_form() {
  $form['sample_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Enter something'),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function sample_custom_form_validate(&$form, &$form_state) {
  if ($form_state['values']['sample_field'] == 'error') {
    form_set_error('sample_field', t('This is a validation error'));
  }
}

function sample_custom_form_submit(&$form, &$form_state) {
  drupal_set_message(t('You entered: @value', array('@value' => $form_state['values']['sample_field'])));
}

In hook_preprocess_node():

$form = drupal_get_form('sample_custom_form');
$variables['custom_form'] = drupal_render($form);

In node.tpl.php:

<?php print $custom_form; ?>

Any ideas what am I doing wrong?
Why isn't the validation handler invoked properly?

$form_state['values']['sample_field'] this value is set after submit, so you validate the old result instead of your actual form.

maybe this workflow helps you


Content editor cannot view unpublished taxonomy terms when editing a node We have a custom content type that has a Entity Reference field to a taxonomy vocabulary. The content editor is presented a list of check boxes to select their terms to attach to the node. Some of our terms are published and some aren't. When I am logged in as admin (user 1), I can see ALL of the terms to select from, but when a content editor is logged in, they are only seeing the published terms to select from. We want the editor to still be able to tag content with unpublished terms. I have tried every permission I can think of without just opening it up fully to a content editor. We have content moderation in place so the editors have semi locked down permissions in order to allow a content manager to review and publish the content.
Does anyone know the specific permission that would allow editors to see unpublished taxonomy terms on the node edit page?

You don't need to use permissions, just adjust the field's reference method.
Add a new entity reference display view that returns all taxonomy of the given type with the published = 1 filter removed (so it display all terms regardless of publish status).
Edit your entity reference taxonomy field for the relevant node type. Under the Reference Type, adjust Reference method to Views: Filter by an entity reference view, then select your newly created view.
After saving the field settings, the node form should display all taxonomy regardless of user permissions on viewing unpublished content.


Meta tags on Drupal blog home page How can I overwrite meta tags on the Drupal blog homepage? I'm using a "Blog" module ( which creates a blog homepage with the URL www.mysite.org/blog ) and a "Metateg" module for generating and overwriting title, description and keywords meta tags. The problem is that I can't find a way to overwrite the default generated meta tags for the blog home page since Metatag module doesn't provide this functionality. Is there any other way to do it?

You need to use the metatag_context sub module of Metatag, which means you need the Context module.

I was thrown for a loop on this as well. It'll create a default Context for a few of these oddball situations. Your metatag information is then controlled through Context.

See source for export handling blog: http://cgit.drupalcode.org/metatag/tree/metatag_context/metatag_context.context.inc#n251


How to sort content in Views by menu weight I have a D7 Views view which delivers a number of nodes. I would like them to be sorted based on the weight that their relevant menu items have.

I would like to avoid the fine module DraggableViews or any additional weight field for that matter.

How could this be accomplished?

Relevant pages: https://drupal.org/node/313140

1: Referencing a user contributed module: Views menu sort which at #48 has a D7 version. I have not tested this but others report success.

2: Another method you could use is to use a PHP field in your view like in this article on tappetyclick.com. (I have used this method before)

3: Or you can use the module menu node views which requires menu node.


Views - context filter by nid I have created a view, which basically queries files of type image. That view creates a block, which associated with a certain content type. So the block is displayed whenever one of the nodes of that type is displayed, exactly what I would like to have.

Each of the files displayed has an entity reference field, which contains multiple references to that content type. So that is a one to many relationship, where one image can have multiple nodes of that type associated.

Is it possible within the views ui, to set a contextual filter that it sorts out each file, whose entity reference field (to that content type) contains the current node id?

In pseudo SQL the statement should look like:

SELECT filename, path, node_refs FROM files WHERE node_refs contains <current node id>;

Thanks in Ahead!

Add a relationship as Entity Reference: Referencing entity
Name it with the name of your content type for instance (easier to read in the view settings)
Check the Require this relationship option
Add a contextual filter with Content: Nid

Here comes the trick!

Choose Provide default value in the WHEN THE FILTER VALUE IS NOT IN THE URL fieldset
Type should be Content ID from URL

This will make Drupal fetch the context from the current URL where your block is displayed and loop through the files referenced by the current node.

TA-DAAA :-)


How to can create a user profile with approve changes by admin I want if user changes his/her profile information they not applied till administrator approve them,I am using drupal 7 ,How can I do this ? is there any module exist for this job?

A custom way can be(will need custom coding) do not expose profile fields directly to users to edit, instead each user will have a node(one to one strict mapping) node will have fields that will be mapping to user profile fields. Once a user edits a node you can set a workflow to mark it as unpublished and once admin reviews and publish fields user profile fields will be updated with node fields.

So a possible workflow can go something like

User can edit node(name it user_node) belongs to user only, you can keep user reference field on node to check the edit permissions.
When a node(user_node) is edited check the current user if user is not admin set $node->status = 0, you can use hook_node_presave() for this.
If a node(user_node) is edited by admin keep a checkbox as approve(field visible to admin only, you can use field permissions module to allow admin to see this field).If admin approves the node again in hook_node_presave() change $node->status = 1 and take the uid from the user reference field on the node, update the user profile fields with the current node field values, you can use user_save() function for this.

This is just a rough idea which require coding, I have not checked if there is a module which can set workflow for user profile if there is any it can provide you want you want out of the box.


Add classes to menu item based on url For various reasons, I can not use the Drupal 7 menu system and have to hardcode a special menu. I am trying to add an active class basing on the URL. I was looking at this page and trying the following.

<a href="/search" title="" class="<?php if ( ($path == $_GET['q'] || ($path == '/search') ) ) : print ('active');endif;?>">Search

sports

news

entertainment

You can read URL with out base path using $_GET['q'] ..

<?php if ( $_GET['q'] == "search" ) : print ('active'); endif; ?>

OR

You can use current_path API function which does the same...


How can CSS emulate content display with labels in one column and data in the other? I have set the Manage Display option to make the field labels Inline, given them a fixed width so that all the data is lined up in a column.

.field-label-inline .field-label {
  margin-right: 6px;
  text-align: right;
  width: 110px;
}

The problem is that when the is long, the data it gets positioned below the label rather stay to the right of the label. I want as though it was a table with the right-aligned labels in the first column and the data in the second column.

Can that be accomplished via CSS?

Field content supposed to live inside div.field-items, so you can set "width" or  "max-width" properties to div.field-items. Value of width/max-width should be same as or smaller than parent div.field width minus label width.


Check effect of hook_schema_alter() hook I want to alter the comment subject field title width.

Core comment module sets it to 64 characters, and I want to change it up to 100 characters.

Now I tried to alter the schema using hook_schema_alter() function. Below is my code snippet, which I tried,

/**
 * Implements hook_schema_alter().
 */
function comment_alter_schema_alter(&$schema) {
    if (isset($schema['comment'])) {
        $schema['comment']['fields']['subject'] = array(
        'type' => 'varchar',
        'length' => 100,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The comment title.',
        );
    }
}

I am confused whether do I have to write some stuff in .install file or not?

Now after installing module how can i check whether the width of subject field is increased or not. If I see the comment table then it is as it is to 64 characters. I could find this in your table structure using PHPMyAdmin.

This hook is not used to edit the database as such. It is used to alter the schema when using the drupal_get_schema

  Gets the schema definition of a table, or the whole database schema.

  The returned schema will include any modifications made by any module
  that implements hook_schema_alter().

To do what you want you will have to use the db_change_field and this would go in the .install file.

You can check out the Schema API to get other relavent functions

You have to write db_change_field() in hook_enable() function.

Here is my modified answer:

/**
 * Implements hook_enable().
 */
function comment_alter_enable() {
    db_change_field('comment', 'subject', 'subject', array(
        'type' => 'varchar',
        'length' => 100,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The comment title.',
        )
    );
}


Are there JavaScript events sent by Webform Conditionals? I am using the iCheck module for checkboxes, and the checkbox is initially hidden by the Webform module. Somehow, the Webform module also sets it to disabled while hidden, which is nice.

Once it gets shown, the disabled status is removed from the webform, but the iCheck module doesn't notice. Calling iCheck.update() fixes it, but I need to catch an event to do that.

Are there JavaScript events sent by a webform conditionals?

The Webform module for Drupal 8 is using Drupal's States API, which triggers custom events that are prefixed with 'state:*'.

Events include...

state:disabled
state:required
state:visible
state:checked
state:collapsed


How can I add extra info to my menus? I have some menus that are managed in the standard Menus module (Drupal 6, BTW). I want to add a checkbox when I'm editing a menu item to control the display of a "New" banner via CSS (by adding a class for items that have the checkbox turned on).

I can get my checkbox into the form like so:

function mymodule_form_menu_edit_item_alter(&$form, &$form_state) {
  $form['menu']['newbanner'] = array(
    '#title' => 'New banner',
    '#type' => 'checkboxes',
    '#description' => "Add a 'New' banner to this item?",
    '#options' => array( 'new_banner' => t("This item is new") )
    );
}

But I'm not quite sure how to actually save and use the state of my checkbox. I'm guessing I want to start by creating a mymodule_form_menu_edit_item_submit() function? But how do I get my info in/out of the database and use it to add a class to the generated menu on the front-end?

The code you wrote so far is correct; you just need to add the code for getting the saved setting, and the code to save it.

function mymodule_form_menu_edit_item_alter(&$form, &$form_state) {
  // Get the mlid ID of the menu item.
  $mlid = $form['menu']['mlid']['#value'];

  $form['menu']['newbanner'] = array(
    '#title' => 'New banner',
    '#type' => 'checkboxes',
    '#description' => "Add a 'New' banner to this item?",
    '#default_value' => variable_get("mymodule_newbanner_$mlid", 0),
    '#options' => array('new_banner' => t("This item is new")),
  );

  $form['#submit'][] = 'mymodule_menu_item_submit';
}

function mymodule_menu_item_submit($form, &$form_state) {
  $item = &$form_state['values']['menu'];
  // Get the last ID inserted in the table.
  if (empty($item['mlid'])) {
    $item['mlid'] = db_last_insert_id('menu_links', 'mlid');
  }

  variable_set('mymodule_newbanner_' . $item['mlid'], $item['newbanner']);
}

The mlid could be zero, when the menu item is first created; in that case, the form submission handler gets it from the table, as it is executed after the form submission handler added by menu.module, which saves the menu item in the table using menu_link_save().


Multiple select not working in drupal8 I have a form element as follows :

$form['fieldset']['select-user'] = array(
            '#type' => 'select',
            '#title' => t('Select a user'),
            '#options' => select_user_dropdown_options(),
            '#description' => t('Select a user'),
            '#size' => 10,
            '#attributes' => array(
                'style' => 'width:600px',
                'multiple' => 'true'
            )
        );

And in the form submit handler i am processing it as follows :

    /**
     * #submit callback for node_adoption_transfer_form().
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        $groupId = $form_state->getValue('select-user-group');
        $groupName = $form_state->getValue('group_name');
        $userId = $form_state->getValue('select-user');
        $groupName = empty($groupName) ? '' : $groupName;
        #print_r($userId);exit;
        foreach ($userId as $key => $value) {
            $query = "select * from {usergroup_user_map} where user_id=$value AND group_id ='$groupId'";
            if (count(db_query($query)->fetchObject()) > 0) {
                continue;
            } else
                db_query("insert into {usergroup_user_map} (user_id,group_name,group_id) values ($value,'$groupName','$groupId')");
        }
     }

But when am printing the $userId its only printing the last value , How to resolve this ?

UPDATE

  my issue solved .I was using '#multiple' => 'true' instead of
  '#multiple' => TRUE , my bad ;) . That saved my day ..

I had same issue , but i solved like this

$form['fieldset']['select-user'] = array(
   '#type' => 'select',
   '#title' => t('Select a user'),
   '#options' => select_user_dropdown_options(),
   '#description' => t('Select a user'),
   '#size' => 10,
   '#multiple' => TRUE,
   '#attributes' => array(
      'id' => 'edit-select-user',
      'style' => 'width:600px',
   )
);

Code:

Form:

Output in submit:


Pressflow 6 forms creating session cookies We have a Pressflow 6 website behind a Varnish cache but our cache hit-rate is awfully low. I've recently found that stripping the "Cookie" header from requests completely increases the hit-rate to 97-98%.

The vast majority of our users are anonymous, so Pressflow shouldn't be setting a session cookie, however we do have a number of forms on the site and it seems that when someone uses a form a session cookie is set in their browser. The forms aren't fancy, the page they submit to just says "thanks for your comment" so there's no need for a session as POST requests aren't cached anyway. The cookie's lifetime is about a month and a half too.

I was considering stripping the cookies when there's no "DRUPAL_UID" cookie, however I'm loath to remove them all in case there's a legitimate reason for them being set.

So, two questions:

Is there a legitimate reason for these cookies being set?
If not is my best option to get Varnish to strip them out or is
    there a way to prevent them from being set or to remove them within Pressflow?

// Default backend definition.  Set this to point to your content
// server.
//
backend default {
  .host = "127.0.0.1";
.port = "81";
.connect_timeout = 600s;
.first_byte_timeout = 600s;
.between_bytes_timeout = 600s;
// enable to use status script for health of backend
//  .probe = { .url = "/status.php"; .interval = 5s; .timeout = 1s; .window = 5;.threshold = 3; }
}

//
// BOOSTED VARNISH - by Trellon, LLC
//
// - Based on a configuration by Lullabot and VCL examples for Varnish Wiki.
//
// Logic is:
//
// * Assume: A cookie is set (we add __varnish=1 to client request to make this always true)
// * If boosted URL -> unset cookie
// * If backend not healthy -> unset cookie
// * If graphic or CSS file -> unset cookie
//
// Backend response:
//
// * If no (SESSION) cookie was send in, don't allow a cookie to go out, because
//   this would overwrite the current SESSION.

// Respond to incoming requests.
sub vcl_recv {

////// START BOOST Logic (Prerequisite)
  // We always send a cookie, so that empty requests are
  // handled by below boost logic, too.
  set req.http.Cookie = ";__varnish=1;" req.http.Cookie;
////// END BOOST Logic (Prerequisite)

// Enable to disable varnish
//      return (pipe);

////// START DEFAULT RULES
 // -------- CloudFlare ----------
  remove req.http.X-Forwarded-For;
  if (req.http.CF-Connecting-IP) {
    set req.http.X-Forwarded-For = req.http.CF-Connecting-IP;
  } else {
    set req.http.X-Forwarded-For = client.ip;
  }

  // Remove a ";" prefix, if present.
  set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
  set req.http.Cookie = regsub(req.http.Cookie, "^__\s*", "");
  set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|cfduid)=[^;]*","");
  // -------- CloudFlare ----------

 if (req.request != "GET" &&
    req.request != "HEAD" &&
    req.request != "PUT" &&
    req.request != "POST" &&
    req.request != "TRACE" &&
    req.request != "OPTIONS" &&
    req.request != "DELETE") {
      // Non-RFC2616 or CONNECT which is weird.
      return (pipe);
  }
  if (req.request != "GET" && req.request != "HEAD") {
    // We only deal with GET and HEAD by default
    return (pass);
  }

////// END DEFAULT RULES

  // Allow the backend to serve up stale content if it is responding slowly.
  set req.grace = 1h;

  // Do not cache these paths.
  if (req.url ~ "^/status\.php$" ||
      req.url ~ "^/sitemap\.xml$" ||
      req.url ~ "^/update\.php$" ||
      req.url ~ "^/jstats\.php$" ||
      req.url ~ "^/boost_stats\.php$" ||
      req.url ~ "^/cron\.php$" ||
      req.url ~ "^/ooyala/ping$" ||
      req.url ~ "^/admin/" ||
      req.url ~ "^/info/.*$" ||
      req.url ~ "^/flag/.*$" ||
      req.url ~ "^.*/ajax/.*$" ||
      req.url ~ "^.*/ahah/.*$") {
       return (pass);
  }

  // Pipe these paths directly to Apache for streaming.
  if (req.url ~ "^/admin/") {
    return (pipe);
  }

  // Do not allow outside access to cron.php or install.php.
  if (req.url ~ "^/(install)\.php$" && !client.ip ~ internal) {
    // Have Varnish throw the error directly.
    error 404 "Page not found.";
    // Use a custom error page that you've defined in Drupal at the path "404".
    // set req.url = "/404";
  }

  // Handle compression correctly. Different browsers send different
  // "Accept-Encoding" headers, even though they mostly all support the same
  // compression mechanisms. By consolidating these compression headers into
  // a consistent format, we can reduce the size of the cache and get more hits.=
  // @see: http:// varnish.projects.linpro.no/wiki/FAQ/Compression
  if (req.http.Accept-Encoding) {
    if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v)$") {
      // No point in compressing these
      remove req.http.Accept-Encoding;
    }
    else if (req.http.Accept-Encoding ~ "gzip") {
      // If the browser supports it, we'll use gzip.
      set req.http.Accept-Encoding = "gzip";
    }
    else {
      // Unknown or deflate algorithm. Remove it and send unencoded.
      unset req.http.Accept-Encoding;
    }
  }

////// START .htaccess rewrite rules

// Strip out Google Analytics campaign variables. They are only needed
// by the javascript running on the page
// utm_source, utm_medium, utm_campaign, gclid
  if(req.url ~ "(\?|&)(gclid|utm_[a-z]+)=") {
    set req.url = regsuball(req.url, "(gclid|utm_[a-z]+)=[^\&]+&?", "");
    set req.url = regsub(req.url, "(\?|&)$", "");
  }

////// END .htaccess rewrite rules

////// START BOOST Logic

  // This is no pressflow, so we always have a SESSION

  // but boost will always set the DRUPAL_UID cookie
  // when the user is logged in.
  //
  // So it is safe to remove all cookies for the boosted paths.
  if (!(req.http.Cookie ~ "DRUPAL_UID=")) {
     // User is anonymous

     // Boost rules from .htaccess
     if (!(req.url ~ "(^/(admin|cache|misc|modules|sites|system|openid|themes|node/add))|(/(comment/reply|edit|user|user/(login|password|register))$)")) {

////////// BOOST CONFIG: Change this to your needs
       // Boost rules from boost configuration
       if (!(req.url ~ "/(excluded-url-to-be-configured)")) {
         unset req.http.Cookie;
       }
////////// END BOOST CONFIG: Change this to your needs
    }
  }

////// END BOOST LOGIC

////// Cookie removal logic

  // Always cache the following file types for all users.
  if (req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|html|htm|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v|pdf)(\?[a-z0-9]+)?$") {
    unset req.http.Cookie;
  }

  // Use anonymous, cached pages if all backends are down.
  if (!req.backend.healthy) {
    unset req.http.Cookie;
  }

}

// Routine used to determine the cache key if storing/retrieving a cached page.
sub vcl_hash {
  // Include cookie in cache hash.
  // This check is unnecessary because we already pass on all cookies.
  // if (req.http.Cookie) {
  //   set req.hash += req.http.Cookie;
  // }
}

// Code determining what to do when serving items from the Apache servers.
sub vcl_fetch {

////// START BOOST Logic

  // This is no pressflow, so we always have a SESSION
  // but we only set SESSION if we actually send cookies
  //
  // So logic is: If we did not send a cookie in,
  // we do not allow a cookie out.

  if (!req.http.Cookie) {
    unset beresp.http.set-cookie;
  }

////// END BOOST LOGIC

  // Don't allow static files to set cookies.
  if (req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|html|htm|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v|pdf)(\?[a-z0-9]+)?$") {
    // beresp == Back-end response from the web server.
    unset beresp.http.set-cookie;
  }

  // Allow items to be stale if needed.
  set beresp.grace = 1h;

  // Serve the good page from the cache and re-check in one minute

  if (beresp.status == 503 || beresp.status == 501 || beresp.status == 500) {
    set beresp.grace = 60s;
    restart;
  }

  // Anything that is cacheable, but has expiration date too low
  // which prevents caching gets cached by varnish to take the
  // load off apache.

  if (beresp.cacheable && beresp.ttl < 1h) {

////////// MINIMUM CACHE LIFETIME: Change this to your needs
    // Set how long Varnish will keep it
    set beresp.ttl = 1h;
////////// END MINIMUM CACHE LIFETIME: Change this to your needs

    // marker for vcl_deliver to reset Age:
    set beresp.http.magicmarker = "1";
  }

}

sub vcl_deliver {
////// START DEBUG
  if (obj.hits > 0) {
    set resp.http.X-Varnish-Cache = "HIT Varnish (" obj.hits ")";
  }
  else {
    set resp.http.X-Varnish-Cache = "MISS";
  }
////// END DEBUG

  // The magic marker is used to reset the age to 0
  // as else the object is older than its ttl.

  if (resp.http.magicmarker) {
    // Remove the magic marker
    unset resp.http.magicmarker;

    // By definition we have a fresh object
    set resp.http.Age = "0";
  }
}

// In the event of an error, show friendlier messages.
sub vcl_error {
  // Redirect to some other URL in the case of a homepage failure.
  //if (req.url ~ "^/?$") {
  //  set obj.status = 302;
  //  set obj.http.Location = "http://www.megaleecher.net";
  //}

  // Otherwise redirect to the homepage, which will likely be in the cache.
  set obj.http.Content-Type = "text/html; charset=utf-8";
  synthetic {"

  <title>"} obj.status " " obj.response {"</title>

Page Could Not Be Loaded

The page you requested is temporarily unavailable.

We're very sorry, but the page could not be loaded properly. This should be fixed very soon, and we apologize for any inconvenience.

We're redirecting you to the Tech Blogs Homepage in 5 seconds.

(Error: "} obj.status " " obj.response {")

"};
  return (deliver);
}

The above worked for me, if you are not using Cloudflare make sure to remove that section.


Views rest export does not update I have two websites.
On website 1 I have a calendar showing upcoming events. Next to a regular views page I also created a views rest export page with 6, of the most near in the future, upcoming events.
On website 2 I created a rest import function with JavaScript. Getting the 6 events and showing them in a block.
Now my problem is that, when a day is passed and an event has taken place, the event is not removed from the block in website 2. I'm not caching anything on website 2 and it is just importing the rest export every time the page loads. And I turned the cache of the view on website 1 off.
It looks like the problem is with website 1 (because emptying the cache on website 1 fixes the problem on website 2 for some reason it is not updating the rest export when an event has passed.
The updating of the rest export on website 1 should take place because the filter of the view is set to only show the upcoming events.
I find it hard to explain what the problem really is hopefully my explanation makes sense (at least a little bit).
So what I'm wondering if this is a normal behavior? Did I miss a setting?

These things would be easy to solve if you could set a cache expiration time for anonymous requests in UI, but you can't unfortunately. See Page cache not rebuilding after page cache maximum age is reached
In this case you could add an additional query parameter containing the current date when website 2 is requesting content from website 1 with javascript. This would create a new cache entry on every date change in the page cache of website 1, even if the query parameter is never used. You need to disable caching of the View itself so that it doesn't get cached in other places.


How to make a link in calendar module to current date? Here is another calendar related question: I want to create a link-item that links to a view that filters events to the current date. Easy, you say?

Right now i have a mini-calendar block that show the current month and a view (type page) for events that has a contextual filter: Date: Date (node). It provides the default value Current Date if the filter value is not in the URL.

This works fine. The view shows the events for the current date when the /events page with the view is visited for the first time (no filter value in URL).

So, if the mini-block with the month view is used, it shows the events of that day accordingly. But if someone cycles through the months and wants to go back to show events of today he has to click back to the current month and date to show them.

Now i want a link-item that links to the current date view as a kind of shortcut, visible on all event-views, but i have no idea how to do that.

Right now i have my view duplicated, with an own path (/eventstoday) and a block with the link to that view, shown on event-view pages.

But there must be a way to achieve this with only one view...

Any help would be appreciated... and thanks for reading!

EDIT:

Additional Information about settings used: I use Ajax in the views and also the calendar configuration option: "Track current date in session" for all users.

  Store session information about the user's current date as they move
  back and forth through the calendar. Without this setting users will
  revert to the current day each time they choose a new calendar period
  (year, month, week, or day). With this option set they will move to a
  day that conforms to the time period they were viewing before they
  switched. Requires session tracking which is not ordinarily enabled
  for anonymous users.

I use Drupal 7.14 and the latest development-snapshots of calendar, date, ctools and views.

<a href="event/<?php print format_date(time(), 'custom', 'd f y'); ?>">Event of today

Do something like this in the calendar theme. Change the path and the format API and put it in one of the tpl.php file of the calendar.

Or just put a link on the tpl.php, pointing to the default view without date on the url

Event of today

Where do you want to put it?


How to use hook_menu_link_alter() on taxonomy term view? When viewing a taxonomy term, I want to change the 'Edit' link (in the admin tabs) to say 'Edit this term' instead.

In taxonomy.module, the menu item is defined like this:

function taxonomy_menu() {
    $items['taxonomy/term/%taxonomy_term/edit'] = array(
        'title' => 'Edit',
        'page callback' => 'drupal_get_form',
        // Pass a NULL argument to ensure that additional path components are not
        // passed to taxonomy_form_term() as the vocabulary machine name argument.
        'page arguments' => array('taxonomy_form_term', 2, NULL),
        'access callback' => 'taxonomy_term_edit_access',
        'access arguments' => array(2),
        'type' => MENU_LOCAL_TASK,
        'weight' => 10,
        'file' => 'taxonomy.admin.inc',
      );
}

So in my module, I try to do this:

function mymodule_menu_link_alter(&$item, $menu) {
  if ($item['link_path'] == 'taxonomy/term/%taxonomy_term/edit') {
    $item['link_title'] = 'Edit this term';
  };
}

After clearing cache and rebuilding menus, the menu item still says 'Edit'.

Is this because the menu item type is MENU_LOCAL_TASK? Or perhaps I am missing something else?

hook_menu_link_alter() is invoked from menu_link_save(), which is the function called when a menu link is saved. The code you wrote for that hook would be invoked when, for example, you add a menu link from admin/structure/menu/manage/main-menu/add, and use taxonomy/term/%taxonomy_term/edit as value for Path.

As Clive said, hook_menu_alter() is the hook you should use to change the menu item defined in hook_menu() from a module.


Does the sitemap.xml file does from the xmlsitemap module actually get generated? I see that there is a 1.xml file generated in the sites/default/files/xmlsitemap folder, but I do not see a file in the Drupal root. However, when I call http://www.example.com/sitemap.xml I do get the info. Is this the normal behaviour?

Yes, that's normal behaviour.

xmlsitemap_menu() includes a route for /sitemap.xml specifically.


Views proximity search by postal code show all when empty I'm using proximity search in views 3.

The proximity search is by Postal Code.

When first loading the view page, it's showing all result.
In my case this is not good because the postal code is required for filtering.

My question is.

Is there a way to not showing all the result when postal code search field is empty.

Here is a screen shot of my views Criteria.

In More
Thanks a lot

In the settings for the exposed search field, you should be able to change the behaviour:
On Empty input, Show None.  Show All is set by default


Features versus Configuration Management I am building a Drupal 8 site and I have done some research whenever I should use Configuration Management or Features to export configuration and include it in my profile.
In order to export and import configuration with Configuration Management from one site to another, sites have to have the same UUID. It means that they have to be a clone of each other.
There are two ways to achieve this:

Clone the DB from one site to the other in order to have the same UUID
Programmatically modify the UUID to match the one in configuration

The site I am going to build will have its own profile installation and my intention is to keep configuration or features within the profile.
I have already created my profile installation but now I have to include configuration in a way it does not depend on UUID so I can:

Spin up a fresh development environment using profile installation
Develop new functionalities
Export new functionalities in the profile
Deploy it to prod and apply new functionalities without re-installing the site

How can I export configuration and add it to my profile?
Should I use Configuration Management and manually remove the UUID or should I use Features and add it to my profile?

Using the Features module, I am not able to set the destination for my features. I would like to put all my features under profiles/my_profile/feature. When I create it I am not able to set a destination so it gets saved under modules/custom. I manually moved it from modules/custom to profile/my_profile/features. If I update it, it will not update the features I moved but instead it will create a new feature with the same name under modules/custom. How can I setup a custom destination?

I would advise using Features. This would allow not only exporting functionality and compartmentalizing it a lot easier, but you could also have the ability to bring in features later from an external source, and/or, use certain features here on a different site that didnt start with your installation profile.

Currently there is an issue to support custom path generation for Features:  https://www.drupal.org/node/2693123

When that is addressed, you can generate the features to the path of your choice. For now, you can generate the result, grab it out of modules/custom and place the generated feature module into your profile.


Linking to jQuery in block breaks Gallery formatter At the top of my block, is this line:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

This is the reason why the Gallery formatter does not display correctly.

The entire block contains the following:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script type="text/javascript" src="http://localhost/nes/sites/all/themes/nesvesti/js/facebook/fb-traffic-pop.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){
    $().facebookTrafficPop({
        timeout: 10,
        delay: 0,
        title: "Support Us...",
        message: 'Like the page...',
        url: "http://google.com",
        closeable: false,
        opacity: 90
    });

});

</script>

My question is, is there any way to resolve this conflict?

There's a few issues there. Drupal ships with jQuery so no need to include it twice. If you need a later version, use the jquery_update module. Also, JavaScript in D7 should be wrapped in a jQuery namespace as per the documentation here https://drupal.org/node/756722


Address book problem when user edit the billing address i just installed commerce address book module but i noticed that when authenticated users try to edit their billing address they have some options in the bottom that seems very strange and not necessary.

The fist one is : The user is able to change the owner of the account
and the second is : The user can change the status from active to disabled.

I think that these options should not be there.

Do you know how can i disable?

I found this patch which worked for me: http://drupal.org/node/1774932


How do I get a view of all flaggable nodes? I have a custom flag defined only on certain content types and I want to make a convenient list of all nodes that the flag is being displayed on, that is, nodes of all the content types that the flag is defined on.

If these content types are never going to change, the quick and dirty would be to just create a View filtering on those content types.

If this is not the case, then you are going to have to get down into some coding as I am not aware of any built in Views/Flags integration on this level.  Sure, you can list all flagged or not flagged content, but I don't see a way to list flaggable content.

So, to get the node types, you should be able to do something like this:

$flag=flag_get_flag('NAME_OF_THE_FLAG');

and now

$types=$flag->types;

should be an array of node types this flag can be applied to.  So now you need to tell Views about this.

So, using the quick and dirty View created above, you could then alter it up with something along these lines:

function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='NAME_OF_THE_VIEW') {

    $flag=flag_get_flag('NAME_OF_THE_FLAG');

    $filters = $view->display_handler->get_option('filters');
    // you may want to dpm() or drupal_set_message() or watchdog() or otherwise look at $filter to see what you have to deal with on your system
    $filters['type']['value'] = $flag->types;

    $overrides = array();
    $overrides['filters'] = $filters;

    foreach ($overrides as $option => $definition) {
      $view->display_handler->override_option($option, $definition);
    }

  }

}

which on my box here, changes the types filtered to those in the flag.

Your $flag and $filters may/will most probably vary, so check to see what you have to work with as these are the broad strokes.

Lots of information about flags here: Flag 3.x PHP API

Information about Views hooks here:  Views Hooks


How to use hook_menu to add an item to the secondary links? Adding an item to the primary links is easy:

function hook_menu()
{
    $items = array();
    $items['bla'] = array(
        'title' => 'bla',
        'page callback' => 'mymod_blah',
        'expanded' => TRUE,
    );
    return $items;
}

This adds it to the primary links. How do I add it to the secondary links?

You can use menu_name to specify the menu of the items you are adding:

See the hook_menu docs for more info.

For example, to add the item to the main menu:

function hook_menu()
{
    $items = array();
    $items['bla'] = array(
        'title' => 'bla',
        'page callback' => 'mymod_blah',
        'expanded' => TRUE,
        'menu_name' => 'main-menu',
    );
    return $items;
}


Block Settings not applying to Zen sub theme I've created a Zen sub theme using the Starter Kit enabled it, and set it as the default (I've changed very little from the Starter Kit). If I go to Structure > Blocks there is only a tab for the Zen theme (which is enabled, but not set to default). I can set blocks into different regions and save, but the changes are not reflected on the page. If I switch to the base Zen theme, the changes are there, but switching back to my sub theme shows just the default layout.

I'm new to Drupal, so should the sub theme be inheriting the base Zen theme's settings, or should there be a separate tab for the sub theme? And what do I need to do get the tab to show up? I've gone through numerous examples and tutorials without finding an answer.

Thanks.

I solved the problem, but don't know exactly what the issue was.

While troubleshooting, I noticed some Warning

  site:drupal.org Invalid argument supplied for foreach() in
  element_children()

As well as the tabs not changing names regardless of which themes were enabled. Disabled and uninstalled all of my custom modules, but nothing changed. Disabled and deleted all the custom themes I had installed, and the errors disappeared and the Block Settings menu started behaving properly again. I copied all the themes back in, and it's still working properly, so I am not sure what the problem was.

I will be reinstalling several of the modules and checking to see if the problem reoccurs, but for now all is well.


How to add dynamic field labels? I have a "medical records" content type which has a "medical process" field embedded (type=paragraphs bundle, number of values unlimited). In the paragraph bundle its has visit time, diagnosis, treatments, images, etc., so the paragraph can record every visit.

Everything works well, however, if we have a lot of paragraphs, in the view page, it looks ugly, so I would like to add some labels to each visit record enter image description here(paragraph), such as "the first visit", "the second visit","the % visit)...as I know the field group can only show a static label, token not available. Do anybody know how to realize this?

You can use hook_node_view to change the view before rendering.

/**
 *
 * @param type $node
 * @param type $view_mode
 * @param type $langcode
 * Implements hook_node_view().
 * To change paragraph title in node view.
 */
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
  if ($node->type == 'CONTENT-TYPE-ID' && $view_mode == 'full') {
    foreach ($node->content['field_medical_records'] as $key => $paragraph_values) {
      if (is_numeric($key)) {
        $item_key = key($paragraph_values['entity']['paragraphs_item']);
        $node->content['field_medical_records'][$key]['entity']['paragraphs_item'][$item_key]['field_visit_time']['#title'] = numToOrdinalWord($item_key) . ' Visit';
      }
    }
  }
}

/**
 *
 * @param type $num
 * @return string
 * Implement to get Ordinal word from number.
 */
function numToOrdinalWord($num) {
  $first_word = array('eth', 'First', 'Second', 'Third', 'Fouth', 'Fifth', 'Sixth', 'Seventh', 'Eighth', 'Ninth', 'Tenth', 'Elevents', 'Twelfth', 'Thirteenth', 'Fourteenth', 'Fifteenth', 'Sixteenth', 'Seventeenth', 'Eighteenth', 'Nineteenth', 'Twentieth');
  $second_word = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty');
  if ($num <= 20) {
    return $first_word[$num];
  }
  $first_num = substr($num, -1, 1);
  $second_num = substr($num, -2, 1);
  return $string = str_replace('y-eth', 'ieth', $second_word[$second_num] . '-' . $first_word[$first_num]);
}

You can change field names as per your requirement.


Editing content redirects to apache test page? Everything in the site works except for when saving it redirects to an apache test page.  Any ajax request returns an error and the apache test page as debug text?  Any idea?  php 5.3 all requirements met.

Clarification
For example:
When editing content and clicking save I am taken to an apache test page.
The url display in the browser is site.com?q=node/1/edit&destination=admin/content
If I refresh the page and send the postdata again I get the apache start page.
If I load that page (like put the cursor in the URL bar and hit enter) it goes to the content edit screen but nothing is saved.

All forms that submit post data it seems do not work.  I dont have this problem anywhere else on the server.

This was an issue with mod_security.  Disabling it fixes the problem...but is not advised.


Is multisite a good option? I am a single developer making a good few sites in drupal.  At the moment I have one site working, I will be using the same modules for the next few but different theming.  Is multisite a good option even though wont be sharing any content?  I just want to be able to manage the sites on the one laptop, the one installation if possible & save time downloading modules again and again.  All of the sites will have different domains, none of them subsites.  I have been trying to get this working for weeks but am in an awful fuzzle now.  Any thoughts?  I tried to post on drupal.org forums but couldnt even get that working.  Any help welcome..

Regards
Naoimi

I don't think you want multisite. If you're concerned about environment spinup time, create a drush make file with the modules and settings you want. You can even generate one online.

You could also use a development environment like Pantheon or Kalabox or Acquia Dev Desktop, or another distribution to get started.


How to insert an RTMP url from an adobe streaming server (rtmp://example.com/myvideo.flv) in drupal 7? I need to create a video gallery and would like some advice on how to view flash videos on drupal 7.

The url I have to insert are rtmp (rtmp://example.com/myvideo.flv).

Any ideas on what modules to install and the steps to follow?

I read on the previous questions about flowplayer but it's only supported on Drupal 6.

Many thanks for your help.

You can use JWPLAYER , and here is an example for how you setup the streaming

1- in the page header you include the jwplayer js library
2- follow the embedding guide "http://www.longtailvideo.com/support/jw-player/28839/embedding-the-player"
3- use the RTMP changes as it's documented here http://www.longtailvideo.com/support/jw-player/28854/using-rtmp-streaming/

So your simple code will look like this;

 jwplayer("myVideo").setup({
     file: "rtmp://example.com/application/mp4:myVideo.mp4",
     image: "/assets/myVideo.jpg",
     height: 360,
     width: 640
    });


Tracking outbound Google Adsense clicks I would like to be able to track how many clicks are done on Google adsense ads from each node of my site.
The purpose of doing so is to be able to do revenue sharing with the authors of each article that will be published.

This module may seem to be useful: http://drupal.org/project/adsense

Except that it says "Click Tracking: tries to track clicks on the displayed ads, usually failing to do so."

Are there any alternatives?

Thanks in advance for your answers.

The problem is links are generated by Google. I assume Google tools does not suffice, and you can't generate report of enough quality using Google Analytics - if you could, you wouldn't ask here.

You cannot alter links. If what you display is not what Google provided, you are not getting any money. So the only sure way - generate link like http://example.org/count_ad_click/123dwe324), record click and redirect user - is closed for you.

You could cover ads with transparent link to your counting address, to avoid altering the real one. That counts as click hijacking and can hurt your reputation, badly. Browsers can start to display "possible malware" alerts, SEO position will drown and so on. Oh, and of course no money.

You still can use jQuery to append onclick to those links, and either push events to Analytics or to your own counting mechanism. Both are prone to manipulation, as they happen on a client side and user can fake those clicks all he wants, so you can get any number of false positives. On the other hand, if your reader will have javascript turned off, it will not count him at all, and some anty-hijacking plugins can prevent click count, too. Last but not least, that's the way AdSense module works now, anyway.


How do I programmatically save longitute and latitude? I am using the Geofield Map module which depends on the geofield and I want to save lng and lat pragmatically in the geofield via my controller. I have tried the methods below and they didn't work:

$WayPointEntity->field_geo_field->setValue("POINT(" .$waypoint['lng']." " .$waypoint['lat'].")");

I also tried:

$WayPointEntity->field_geo_field = array(
                  'input_format' => GEOFIELD_INPUT_LAT_LON,
                  'geom' => array('lat' => $waypoint['lat'], 'lon' => $waypoint['lng']),
              );

  $WayPointEntity->save();

Try this :

$point = [
  'lat' => $lat,
  'lon' => $lon,
];
$value = \Drupal::service('geofield.wkt_generator')->WktBuildPoint($point);
$WayPointEntity->field_geo_field->setValue($value);


Show form message only on initial load, but not after submit I'm often using Drupal::messenger() to show status/warning messages before I submit the form. But those messages are usually counter-intuitive once the form has been submitted. How can I add a message to a form that is only rendered before the form has been submitted.
My typical code looks like this:
function buildForm() {
  /**
   * ...build form...
   */
  $showWarning = $this->doSomeChecks();

  /**
   * tried to use isSubmitted() to prevent the message after submitting, but does not work
   */
  if ($showWarning  && !$form_state->isSubmitted()) {
    $this->messenger()->addWarning('Some info you should know before submitting this form.');
  }
}

function submitForm(array &$form, FormStateInterface $form_state) {
  /**
   * ...do stuff...
   */
  $this->messenger()->addMessage('Successfully done something');

  /**
   * tried to use deleteByType() to remove message from buildForm after submitting, but does not work
   */
  $this->messenger()->deleteByType($this->messenger()::TYPE_WARNING);
}

I know I could use $form_state->setRedirect($customPage) in submitForm(), but I don't want the overhead of creating a new page just to hide a simple warning message.
Is there no simple way to show a message only once on the initial form load, but not after submit?

Try
if (empty($form_state->getUserInput())) {
  $this->messenger()->addWarning('Some info you should know before submitting this form.');
}

See the discussions here: Avoid repetitive API calling in form rebuild while submitting


How to write EntityQuery so that it checks user's access to nodes? How do I write the following Drupal 8 EntityQuery so that it only returns nodes that the current user has access to?

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article');

The above query will return all nodes, even unpublished ones. Depending on how you use the results (like a list of nodes), users could see titles or other information from unpublished nodes.

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->condition('status', 1);

When I add the "status" condition, I now get a list of only published nodes. But I would like people with administer nodes permission to see all the nodes.

Basically, is there a way to simulate the "admin or published" filter, like on Views?

Entity queries by default consider the node grants system, you actually have to opt out of that to get everything when using node grants.

The problem is that drupal core doesn't actually implement that API for the status, that only becomes relevant when using modules that do.

So unfortunately, the only way to simulate "admin or published" is to do it yourself. Check the permission, if the user doesn't have it, add the status = 1 condition. Note that views uses "administer nodes" but technically, that's actuallly wrong, "bypass node access" would make more sense, that would be consistent with what is being checked when trying to access node/ID of an unpublished node. But in your own code, you can use whatever makes sense for you, including a custom permission.

Alternatively, you could use a module like https://www.drupal.org/project/view_unpublished, which does populate grant records and your entity query will just work. In fact, I just closed a bug report where someone reported the behavior you want as a bug when using that module: https://www.drupal.org/project/view_unpublished/issues/2871272.


Validate a custom type node before submitting I'm to validate the creation of a new content node, of a custom content type. It seems I cannot find the right hook.

I tried using hook_node_presave, however, the only way to stop node from creating is to throw an exception. This is rather user unfriendly.

 function custom_module_node_presave($node) {

    if($node->getType()=='custom_content_type'){
            if(some_business_rules_apply()){
                    drupal_set_message('You cannot add a new node.','error');
                    # cancel saving
                    throw new \Exception(t('You cannot add a new node.'));
            }else{
                    # do something more
            }
    }
}

I tried to use hook_node_validate but it seems like it is not called. Do I miss something? Maybe, I use the wrong name for the hook function? Is there some kind of example for hook_node_validate?

function custom_type_node_validate(\Drupal\Core\Entity\EntityInterface $node, $form, &$form_state){
    \Drupal::logger('My logger')->info('Node validate');
}

In Drupal 8 the hook hook_node_validate() has been removed. Here are some suggestions.

Reference: hook_node_validate() and hook_node_submit() have been removed.

Field constraints

If you're trying to validate an individual field,  use a constraint.

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function custom_general_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  // Alter node.page.field_service.
  if ($entity_type->id() === 'node' && $bundle === 'page') {
      $fields['field_service']->addConstraint('CustomAssignableService', []);
  }

Entity constraints

For general constraints on the entire entity or constraints which are not specific to a single field.

/**
 * Implements hook_entity_type_alter().
 */
function custom_general_entity_type_alter(array &$entity_types) {
  if (isset($entity_types['node'])) {
    $entity_types['node']->addConstraint('CustomAuthorizedTerritory');
  }
}

Form validation

The "constraints" will always validate the field / entity no matter the form / method with which you use save the entity.

Additionally, you can provide form validation using a hook_node_form_alter() to improve the UX with nice error messages.

Note: These are "form-level" validations and are only applied when the node is created / updated from a said form. Users might be able to bypass these restrictions while saving the node using web services or other forms (if any).

// In the mymodule.module file.

/**
 * Implements hook_form_FORM_ID_form_alter().
 */
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $form['#validate'][] = 'mymodule_node_form_validate';
}

function mymodule_node_form_validate($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  if ($node->getType() == 'custom_content_type') {
    if ($form_state->getValue('some_property') !== '123') {
      $form_state->setErrorByName('some_property', t('Property must be 123.'));
    }
  }
}