How to change placeholder title of search box? I have placed 2 search box in 'node/92' page at two different region one is at header region and another is at content region ,I have to change the placeholder text of both search box as abc and xyz respectively
my code is:

function bartik_form_search_block_form_alter(&$form, &$form_state, $form_id) {      //print arg(1);
      if (arg(1) == 92)
    {

    $form['search_block_form']['#attributes']['placeholder'] = t('abc ');
}

}

but this code not working well after using it both the search box placeholder text having the same title  "abc"

By using hook_form_alter and/or any of its descendants, you are altering the placeholder everywhere and anywhere that the form occurs.

To isolate specific instances of the form, based on which region they are in, you can use hook_preprocess_page.

For example, in your template.php:

function yourthemename_preprocess_page(&$variables) {
  if (arg(1) == '92') {
     // Set the default value for the form in the header region.
    $variables['page']['header']['search_form']['search_block_form']['#attributes']['placeholder'] = t('abc');

     // Set the default value for the form in the content region.
    $variables['page']['content']['search_form']['search_block_form']['#attributes']['placeholder'] = t('def');
  }
}


List of images with checkbox (user registration) This is what I would like to do:

When a user registers on the website they have to give in if some options like for example if they are politically engaged, professionally engaged, an expert, ... .

I also want a field that contains 3 images. And based on the chosen options of the user I would like to select 1,2 or 3 of them. So the user can contain image 1 & 2 or ... .

So I was thinking of 3 images with 3 checkboxes and cross the checkboxes next to the images (programmatically). But is this a good way to do this? And if yes, how can I implement this?

You can do that by the following.

Go to Configuration » People » Account settings

Add a Field type : List (text) and WIDGET: Check boxes/radio buttons

In Allowed values list  textarea add key|<img src ='/your/path/to/image' />

Enter one <img> per line and set Number of values as Unlimited (to appear as checkboxes)

That's it. I tested it and working fine.

Add key whatever you want.You may have to make minor CSS changes in order to align checkbox and image.

Hope this helps.


Private File System and User Access Is there a way to protect Drupal files from being accessible by the file path (putting http://www.domain.com/files/image.jpg) in the browser URL from users poking around?

I see two ways of doing that:

Change the "files-mode" to private via admin/settings/file-system (as googletorp stated) AND changing the filepath to somewhere outside of your webserved files.
Change the "files-mode" to private and set some rewrite rules inside your .htaccess (or elsewhere in your webserver config). this gives you more control which files you want served private and which public. Something like:

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/sites/default/files/(private/.*)$
RewriteRule ^.*$ /system/files/%1 [L]

Now every request directly to the "private" files will be rewritten to the systempath which is controled by drupal. So no access without drupal is possible.


Redirect to home page without using deprecated methods I am attempting to add some code to a hook_entity_view_alter() function to redirect the user to the homepage under a rare condition with RedirectResponse.

I understand the method to accomplish this is along these lines (taken from here):

$response = new Symfony\Component\HttpFoundation\RedirectResponse($url);
$response->send(); // don't send the response yourself inside controller and form.
return;

My issue is that I am not sure how to format $url. Most articles on the topic, such as this one, suggest using \Drupal::url(), but this is deprecated in favour of Drupal\Core\Url. I would like to avoid using deprecated methods as much as possible, but am stuck at trying to figure out what the Drupal\Core\Url equivalent is to \Drupal::url('<front>'). I am not sure which methods to be using, and nothing I've tried with Url::fromUri() has worked.

Try using Url::fromInternalUri then instead of fromUri():

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Url.php/function/Url%3A%3AfromInternalUri/8.2.x

It specifically notes the use of front and none. But you can't pass the URL object or path tokens to RedirectResponse, as this is a Drupal construct. That class expects the following arguments:

http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/RedirectResponse.html

string  $url        The URL to redirect to
integer $status     The response status code
array   $headers    An array of response headers

$url needs to be a string, so on your URL object, call ->toString() to get the URL.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AtoString/8.2.x


Filter by taxonomy parent using Json api In drupal 8.5 I have a taxonomy term list like this:

Term A (12 items)
  Term 1 (3 items)
  Term 2 (8 items)
  Term 3 (1 items)
Term B (3 items)
  Term 4 (1 items)
  Term 5 (2 items)

I want to use the json api to fetch all data within term B. So I expect a result set of 3 items.
But when I do:

https://www.some-api.com/jsonapi/node/test?
  _format=api_json&
  filter[taxFilter][condition][path]=field_regio&
  filter[taxFilter][condition][operator]=IN&
  filter[taxFilter][condition][value][]=2 (=> id of term B)

I get a response with "data": [],
This is probably because the term id of these nodes are set to the children (term 4 and 5).

But isn't drupal supposed to return all nodes in the children of term B?

Otherwise how can I get all nodes in Term A or B?

The term-ID 2 belongs to "Term B", not to "Term 4" or "Term 5". To check if term belongs to Term B you may include the term parent and check if it has id 2:

https://www.some-api.com/jsonapi/node/test?
_format=api_json&
include=field_regio.parent
filter[taxFilter][condition][path]=field_regio.parent&
filter[taxFilter][condition][operator]=IN&
filter[taxFilter][condition][value][]=2 (=> id of term B)

This should work at least for the simple example provided it the question.


No 'read-more' to specific content type (eg page) I've been making a content type page for my Drupal 7 website.
I'd like to see an option to disable the 'read more' and the 'link' to the /node/x in the content type customization.
I just want it to be displayed on the home 'as is'.

Is that possible?

You can do this by removing the "teaser" mode and tweaking node--your_content_type.tpl file.

To remove the teaser mode: Go to "Structure > Content types > your content type";
click on "Manage display"  and "Custom display settings"; uncheck the "Teaser" checkbox.
This will display the content in the front page as is.

Now to remove the "read more" link, unset it in your node--your_content_type.tpl.

unset($content['links']['node']['#links']['node-readmore']);

This way you will not have "read more" link in your home and the whole content will be displayed for your content type.


Theming views that use node row style I have a view that uses node rows. I looked at views-view-row-node.tpl.php and it only contains 4 lines. I tried to override the theme by using my node.tpl.php code in a new file but got this warning:

  Invalid argument supplied for foreach() in /home/public_html/sites/all/themes/templates/overrides/views-view-row-node--taxonomy-term-attachment.tpl.php on line 36.

How can I use a modified version of node.tpl.php to theme a certain display of my view?

You probably missunderstood the two different templates here

The node template(node.tpl.php): This is for rendering a specific node
views template This is for wrapping the node + comments

So all you have to do is to use the node.tpl.php to theme a single file.


How does the mapping of the Feeds module work? Does the mapping of the tables from source to destination should be completed, if I have 6 fields in the source table? Should I list all 6 fields, or can I only put 1 field to map if I only want that field to be imported?

You can import as few or as many source fields as you want.  You do not have to include all of them!  The source table or cvs row or whatever does not have to match your destination entity exactly.  It's OK to just take the parts you need.  I frequently use the feeds module with csv files, and import just a portion of the columns that are actually present in the file.

Naturally, just make sure none of those missing fields are marked as required on the destination entity...


How to modify Drupal configuration programmatically? How can I modify the Drupal settings found on /admin/config/people/accounts (and other configuration pages) using a custom module?

For example, how do I rename the Anonymous user and change 'Who can register accounts' setting from 'administrator' to 'visitor' programmatically with a custom module?

Most of these configuration settings tend to be controlled by a variable, so Drupal uses variable_get() and variable_set() to retrieve and modify these values.

To find out the variable name and value you can have a look at the source page.  For example:

<label for="edit-user-register">Who can register accounts? </label>
<div id="edit-user-register" class="form-radios">
  <input type="radio" id="edit-user-register-0" name="user_register" value="0" class="form-radio">
  <label class="option" for="edit-user-register-0">Administrators only </label>

  <input type="radio" id="edit-user-register-1" name="user_register" value="1" class="form-radio">
  <label class="option" for="edit-user-register-1">Visitors </label>

  <input type="radio" id="edit-user-register-2" name="user_register" value="2" checked="checked" class="form-radio">
  <label class="option" for="edit-user-register-2">Visitors, but administrator approval is required </label>
</div>

Here you can see that in order to change the "Who can register accounts?" option, you need to change the value of the user_register variable. You can set it to 1 for visitors, so putting this code in your module will do the trick:

variable_set('user_register', 1);

Of course, this is if you're too lazy to open the source code :) .  The other way is to find out which callback generates this form, and inspect user.module:

function user_menu() {
  //snip...
  $items['admin/config/people/accounts'] = array(
    'title' => 'Account settings',
    'description' => 'Configure default behavior of users, including registration requirements, e-mails, fields, and user pictures.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_admin_settings'),
    'access arguments' => array('administer users'),
    'file' => 'user.admin.inc',
    'weight' => -10,
  );

Then find the callback function user_admin_settings() in user.admin.inc:

$form['registration_cancellation']['user_register'] = array(
  '#type' => 'radios',
  '#title' => t('Who can register accounts?'),
  '#default_value' => variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL),
  '#options' => array(
    USER_REGISTER_ADMINISTRATORS_ONLY => t('Administrators only'),
    USER_REGISTER_VISITORS => t('Visitors'),
    USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL => t('Visitors, but administrator approval is required'),
  ),
);

So there you have your variable and in fact there's some constant to set up the values: USER_REGISTER_VISITORS.


link tag is removed by ckeditor I am using Ckeditor in drupal 7.26. I placed HTML Content with link tag in the source of Ckeditor. It removes link tag. I want to send my css file through that html content. How can I add it into the editor.

As Clive said there is almost certainly no situation that CKeditor  can validly edit/create an html head element. Since link must be a child of a head element this means that CKEditor cannot create a valid link element.

That being said there is a way to add a stylesheet the the CKEditor. You will have to allow JavaScript in whatever filter you are using (so use with caution) and then insert a script like this:

<script>
  (function($) {
    $('head').apend("<link rel='stylesheet' href='my/added/stylesheet.css'>");
  }(jQuery))
</script>

Or if you don't want to use jQuery:

<script>
  var element = document.createElement("link");
  element.setAttribute("rel", "stylesheet");
  element.setAttribute("href", "/my/added/stylesheet.css");
  document.getElementsByTagName("head")[0].appendChild(element);
</script>


Permissions wiping themselves I have a weird problem and was hoping maybe someone on this community experienced it before or would know a better way to debug the issue.

I help manage a large group of multi-sites in Drupal 7.52. There are currently 9 websites and thousands of nodes, so its not a tiny system. we have 13 roles (including the basic - 6 are custom).

Two of these roles are checked to see "View Interactive Information Bar". Description of this permission is "Allow users to view the IIB. This may allow users to perform administrative tasks.".

There are a bunch more but I will use the above as the example to the issue. We will go say 2-3 weeks with no issues and then all of a sudden this permission will become un-checked ONLY for our custom roles. This applies to a bunch of other permissions as well, what is odd is its not ALL the permissions. It is only a few and they keep repeating, the above permission is one.

I will go in and check it back on, it will be fine for a day and then boom, unchecked again. I will repeat this for maybe 2-3 days and then it will be fine for weeks.

I've checked the logs, error logs etc... and nothing is coming up. I've tried checking CRON to see if it happens when CRON runs but nothing. It almost seems random.

Has anyone ever come across this before? Or know of a way to possibly debug this?

Thanks!

To debug, add a user update hook and check if they role is being unchecked, then log the $edit to your watchdog log then you should be able to see who/what is causing this change. This is a very rough example and you'd have to customize it to fit your roles etc.

function YOURMODULE_user_update(&$edit, $account, $category) {
   if (user_has_role($YOUR_ROLE_RID, $account) {
     debug($account, 'account', true);
     debug($edit, 'edit request', true);
     // maybe add an email notification letting you know the event fired
   }
}

You can then test it by manually disabling that role and see if the debug messages appear in your log. Then if it works, just wait and see what happens when the mysterious permissions troll strikes again.


How do I compare fields in a database query? Given the query fragment:

$query = $connection->select('mytable', 't');
$query->addField('t', 'myfield1', 'myfield1');
$query->addField('t', 'myfield2', 'myfield2');

I need to add a condition like this:

$query->condition('t.myfield1', 't.myfield2', '=');

But it doesn't seem to work. For comparison, I can use:

$query->condition('t.myfield1', 'banana', '=');

... and that works. But it seems comparing two fields to see if they match does not work? I can write this out in straight SQL code and properly query the database in a console, but can't duplicate in Drupal's database API.

What am I doing wrong?

You must use where(), like this:

$query = \Drupal::database()->select('mytable', 't')
  ->addField('t', 'myfield1', 'myfield1')
  ->addField('t', 'myfield2', 'myfield2')
  ->where('t.myfield1 = t.myfield2');


How do I render the User Login block? I'm trying with this:

$block = module_invoke('user', 'block_view', 'login');

It returns an empty array.

The user_block_view() function has this line in it for the login delta:

if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {

If you're logged in, the function will return an empty array, which is probably what's happening in your case.

If that's not the reason (and even if it is) you can get around it by calling the form function directly:

$form = drupal_get_form('user_login_block');

There doesn't appear to be any extra access checks done in the form function so it should be rendered regardless of whether you're logged in or not.


How to override default theme to custom module path theme Is it possible to create template file for custom module created page that override default page theme only when the path is visited?

The code i tried so far is displaying my custom module result inside default page theme content area. I want to display result in my self created template file content area. Is it possible?

function mymodule_menu(){
    $items = array();
    $items['mymodule'] = array(
        'title' => 'Mymodule title',
        'description' => 'Mymodule description',
        'page callback' => 'mymodule_page',
        'page arguments' => array(),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
    );
    return $items;
}

function mymodule_theme() {
    return array(
        'mymodule_theme_page' => array(
            'arguments' => array('mymodule' => NULL),
            'template' => 'page-mymodule',
            'path' => drupal_get_path('module', 'mymodule').'/template',
        )
    );
}

function mymodule_page(){
    $mymodule = array('key'=>'Hello World');

    $output = theme('mymodule_theme_page', $mymodule);
    return $output;
}

The "most drupal" approach would be to place a copy of your template in your theme's directory named page-mymodule.tpl.php (eg, page-PATH.tpl.php) and be done with it. However, there are some cases where you may want to do this theming in a module, in which case you could do something along these lines in mymodule.module:

  // tell drupal that you want to use page-mymodule.tpl.php if you
  // are looking at www.yourhost.com/mymodule

  function mymodule_preprocess_page(&$vars) {

    if ($_GET['q']=='mymodule') {

      $vars['template_file']='page-mymodule';

      $vars['new_variable']=array('foo','bar','baz'); // $new_variable is now available in the template

    }

  }

  // tell drupal to look in .../mymodule/tpl/page
  // for page templates before looking anywhere else

  function mymodule_theme_registry_alter(&$theme_registry) {

    $theme_hook = 'page';
    $modulepath = drupal_get_path('module', 'mymodule') . '/tpl/page';
    array_unshift($theme_registry[$theme_hook]['theme paths'], $modulepath);

  }

Now, if you have page-mymodule.tpl.php in the directory .../mymodule/tpl/page and you rebuild your theme registry, easy if you have the Admin Menu module installed, otherwise, just clear all your caches, you should be on your way to using a page template in your module for that path.

(And, of course, in your page callback, you can return whatever content you want displayed in the content area of this template without using any of the theme functions you have in your original question.)

ADDITION:  you can use the preprocess_page() hook to add any number of variables that are to be available to the template.  So, in the above, you now have $new_variable available to use in there.


Manage display of geofield with wkt input widget I am stuck on something that seemed very simple and need your help.
I have an input form where there is a geofield input field of type WKT. So the user gives the WKT of a point. When the node is viewed I would like the WKT that the user previously gave to be displayed on a map. On the manage display tab all the other options seem to work (WKT, KML, description etc), except from the map option like leaflet, openlayers and geofield maps. There is empty space where the map was supposed to be.
Can anyone help me on this?

Some suggestions:

make sure that you edit the right format when you filled in the wkt.
check for any errors in the installation of the map.

I had the same problems in the beginning with mapping too. I had an error in the installation of my leaflet map. In the end I solved it with a new installation and I geocoded the geofield from my address field.


Getting error for drush site-install :Unable to find a matching SQL Class I have created a drupal project using composer:

composer create-project drupal-composer/drupal-project:8.x-dev ./ --stability dev -vv

Then I downloaded drush using this command:

composer global require drush/drush

Now I try to install the drupal site using this drush command:

drush si standard --db-url=mysql://***:***@localhost/recommande_db --site-name=***** --account-name=*** --account-pass=*** --account-mail=*****

I'm getting this error:

exception 'Drush\Sql\SqlException' with message 'Unable to find a matching SQL Class. Drush cannot find your[error]

database connection details.' in

/Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/commands/sql/sql.drush.inc:588

Stack trace:

#0 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/commands/sql/sql.drush.inc(573):

drush_sql_get_class(Array)

#1

/Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/commands/core/site_install.drush.inc(117):

drush_sql_get_class()

#2 [internal function]: drush_core_pre_site_install('standard')

#3 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/command.inc(366):

call_user_func_array('drush_core_pre_...', Array)

#4 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/command.inc(217):

_drush_invoke_hooks(Array, Array)

#5 [internal function]: drush_command('standard')

#6 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/command.inc(185):

call_user_func_array('drush_command', Array)

#7 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67):

drush_dispatch(Array)

#8 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/preflight.inc(66):

Drush\Boot\BaseBoot->bootstrap_and_dispatch()

#9 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/drush.php(12): drush_main()

#10 {main}

I tried all the suggestions found in several forum but no solution.
Can you help please!

For your information here the result of the "drush status" command:

PHP executable         :  /usr/bin/php

 PHP configuration      :

 PHP OS                 :  Darwin

 Drush script           :  /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendo

                           r/drush/drush/drush.php

 Drush version          :  8.1.2

 Drush temp directory   :  /tmp

 Drush configuration    :

 Drush alias files      :

Make sure that you execute drush from the web folder.


Views Filter with Checkbox and Searchfield I am searching for a solution to generate a custom filter consiting out of two fields. I want to have one Dropdown which holds the fields of my view, and then a second field "textfield" which will hold the search variable.
Here's an example. I do have a view with ID, name, email. My two filters would be a dropdown containing ID, name and email. And when I type something into the textfield, the field selected in the dropdown will be the filtered one. Does anyone know a module that does that? If not, I will write one.
I've checked Global combined filters so far, but they don't do what I want.

EDIT: just in case my question wasn't clear enough, this is what I want to achieve. And still got no idea how to.

What I've found so far is the Module Composite Views Filter, which does quite the thing. You can display a filter on selection of dropdown. But not programatically. You have to fill your dropdown yourself.Not quite what I was looking for, but better than nothing.


How do I add JS libraries in DrupalGap I am hoping to add Slick Library within my DrupalGap but when I try to use it, I am unable to.

The library is added normally within index.html but when one my node page (which has the HTML in it) tries to use it, it doesn't work.

Any idea how to do this correctly.

Including the Slick carousel .js file in the index.html file is correct.

You can use the brand the new hook_entity_view_alter to attach a pageshow handler to the node's page:

http://api.drupalgap.org/7/global.html#hook_entity_view_alter
http://docs.drupalgap.org/7/Pages/Page_Events

In the pageshow handler is when you'd initialize the carousel. The pageshow event fires after page is shown to the user. There are a few other hooks you could use to have a chance to place the pageshow event on a node's page within the app:

http://api.drupalgap.org/7/global.html#hook_entity_post_render_content
http://api.drupalgap.org/7/global.html#hook_entity_post_render_field

The hook_entity_view_alter is the most powerful and is brand new, so you need the latest bin/drupalgap.min.js file and the latest jdrupal.min.js file to run it. But that is the hook I'd recommend using


Get the value of a field of the taxonomy term referenced with an Entity Reference field I have a taxonomy vocabulary "Partners", with boolean field field_1. When I create a user, I attach to it a term from the vocabulary "Partners" with an Entity Reference field. Is there a way to get the value of the field_1 field of that term and to bind it to the user?

(In the first case I need this value to limit the access to a page created by Page Manager to the users whose partners has the field_1 field filled with the value 1. I suppose I need the field value also for other cases later.)

The relation of the user and the partner could be made in another way, too, if it will be easier, more intuitive or more practical.

The user is already associated with the boolean field via the taxonomy term.

For example, load your user's account:

global $user;
$account = user_load($user->uid);

Now load your taxonomy term:

$partner = taxonomy_term_load($account->taxonomy_field_name[LANGUAGE_NONE][0]['tid']);

And then get the boolean value of field_1:

$boolean_value = $partner->field_1[LANGUAGE_NONE][0]['value'];


Display HTML code in a Drupal field as plain text I am using Drupal as a blog for posts about programming. Naturally, I have to post code samples.

When I post the code samples, Drupal renders them as actual HTML. How can I stop this from happening?

Example,

Thank You

^ This gets displayed as the words "Thank You" with the listed formatting in the inline style.

^ This doesn't get displayed at all.

Steps I have taken

I have created a new input format and turned off all the filters.
I wrap the code in both  and
 tags.

I know Drupal has a filter called " Display any HTML as plain text". If I use this, then it works. But then all my formatting for the test of the post (e.g. paragraphs, links) get displayed as text making the post unreadable.

Looks like you're looking for Code Filter.

  This module provides a simple text format (input filter) that handles <?php ?> and  tags so that users can post code without having to worry about manually escaping < and > characters with &lt; and &gt;.

It is the module used on Drupal.org for escaping markup.


How to make a child entity automaticially reference back to parent entity when created using inline entity form? Here is the example:

'Parent' Content Type = Author

field1: Name
field2: Age
field3: Picture
field4: Entity Reference to Books (inline entity form widget)

'Child' Content Type = Books

field1: Title
field2: Description
field3: Entity Reference to Author using prepopulate (need help)

Author has entity reference to Books using Inline Entity Form. So when creating an "Author", we can add "Books" they have written inline.

When a user visits an individual "Book" page, I want a field that links back to the "Author" who wrote it. How can I create this link automatically when creating a "Book" inline?

I assume I have to create a Book field3 that is an Entity Reference to Author that uses prepopulate. But I have not been able to configure this correctly to get it working as wanted. Any ideas?

This has been acheived using Rules:

Export of Rule:

{
        "rules_ifs_backlink_populator" : {
        "LABEL" : "IFS backlink populator",
        "PLUGIN" : "reaction rule",
        "ACTIVE" : false,
        "REQUIRES" : [ "rules" ],
        "ON" : [ "node_insert", "node_update" ],
        "IF" : [
          { "node_is_of_type" : {
              "node" : [ "node" ],
              "type" : { "value" : {
                  "auction" : "auction",
                  "estate_sale" : "estate_sale",
                  "garage_sale" : "garage_sale"
                }
              }
            }
          }
        ],
        "DO" : [
          { "LOOP" : {
              "USING" : { "list" : [ "node:field-ifs-add" ] },
              "ITEM" : { "list_item" : "Current list item" },
              "DO" : [
                { "component_rules_create_entity_reference_back_link_" : { "child_param" : [ "list-item" ], "parent_param" : [ "node" ] } }
              ]
            }
          }
        ]
      }
    }

Export of Component:

{ "rules_create_entity_reference_back_link_" : {
    "LABEL" : "create entity reference back link ",
    "PLUGIN" : "rule",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "child_param" : { "label" : "Child Parameter", "type" : "node" },
      "parent_param" : { "label" : "Parent Parameter", "type" : "node" }
    },
    "IF" : [
      { "AND" : [
          { "node_is_of_type" : { "node" : [ "child-param" ], "type" : { "value" : { "ifs" : "ifs" } } } },
          { "entity_has_field" : { "entity" : [ "child-param" ], "field" : "field_auction_ref" } },
          { "data_is_empty" : { "data" : [ "child-param:field-auction-ref" ] } }
        ]
      }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "child-param:field-auction-ref" ],
          "value" : [ "parent-param" ]
        }
      }
    ]
  }
}


Cron error: LogicException : Render context is empty In a custom module (sel), I have this code:

function sel_cron()
{
  $accountSwitcher = Drupal::service('account_switcher');
  $account = \Drupal\user\Entity\User::load(1);
  $accountSwitcher->switchTo($account);

  $query = \Drupal::entityQuery('service_category');
  $dLastExtractionDate = strftime("%Y-%m-%d", strtotime("- 1 week", strtotime(\Drupal::state()->get('sel.NextEmailForNewServices'))));
  $view = views_embed_view('sel_services', 'embed_2', $dLastExtractionDate);
  $view = \Drupal::service('renderer')->render($view);   <--------------------- problem here

  $accountSwitcher->switchBack();
}

The expected result of the view is a table but when the result is empty (because of the value of the contextual filter), an unfiltered text ("Nothing to display today. Too bad!") should be displayed instead.
But in this case, I get this error logged:

  LogicException: Render context is empty, because render() was called
  outside of a renderRoot() or renderPlain() call. Use
  renderPlain()/renderRoot() or #lazy_builder/#pre_render instead. in
  Drupal\Core\Render\Renderer->doRender() (line 243 of
  /Users/efalzon/Sites/JdP8/web/core/lib/Drupal/Core/Render/Renderer.php).

How to fix that?

$view = \Drupal::service('renderer')->renderPlain($view);

instead of

$view = \Drupal::service('renderer')->render($view);

was the solution!
Thanks to @Clive


Omega 4 Sub-Theme problem with file_get_contents(make.libraries) failed to open stream when creating an omega 4 sub-theme using drush 6 on windows 7 and xampp and drupal 7, see attached pic,'file_get_contents(libraries.make) : failed to open stream : no such file or directory make.utilities.inc:471  Can anyone help?

It's a known bug of Omega theme, so you should follow Drupal issue queue for details: Invalid or empty make file: libraries.make.

As workaround, you may to navigate to subtheme's folder (e.g. fifth_avenue subtheme dir) and run:

drush make libraries.make --no-core --contrib-destination=.


How to import an iCal Feed I'd like to import an iCal feed. Every calendar entry on a given URL should be transformed into a node.

I read that this should be possible with with the feeds, date and calendar module. But I did not find any description about the topic.

I would be very happy if some one could shed some light on this topic.

This online video got me a good bit of the way along:

http://mustardseedmedia.com/podcast/episode34

  On this podcast, Bob shows how to import any iCal feed of events into your Drupal site and displaying them in a Views-driven calendar on your site. (This means importing your Google or Yahoo! calendars or any other calendar system that puts out a feed in iCal format) This is tasty stuff! Want to have the Drupal calendar delete nodes once they're deleted from the feed? Check out this patch and give it a try. Episode Links Feed API, iCal Parser, Feed API Mapper

I am stuck on populating the Organic Group field of the newly created node.


How to adapt the name of a custom Drush command? I saw the interesting answer to the question about "How can I get a list of content types with drush?", which starts like so:

  You can create a drush command named content-type-list.

But I wonder what it should look like if the command should be named something else, eg mijn-contenttypes-lijst (instead of content-type-list), and use drush drush mcl (instead of drush ctl)?

Some reasons why I may want to use another name:

Because it conflicts with something else in Drupal for which I already used content-type-list and/or ctl.
The command is hard to remember (eg because it's not in my native language), so I want to adapt it to another name.

What exactly would I have to change in the code included in that answer, which currently looks like so:

<?php
/**
 * @file
 * Drush commands related to Content Types.
 */

/**
* Implements hook_drush_command().
*/
function drush_content_types_drush_command() {
  $items['content-type-list'] = array(
    'description' => dt("Show a list of available content types."),
    'aliases' => array('ctl'),
  );
  return $items;
}

/**
 * Callback for the content-type-list command.
 */
function drush_drush_content_types_content_type_list() {
  $content_types = array_keys(node_type_get_types());
  sort($content_types);

  drush_print(dt("Machine name"));
  drush_print(implode("\r\n", $content_types));
}

PS: I understand I can create aliases for it also (as shown in the linked answer), but that's not what my question is about. E.g. if I want a command that does something different.

You would have to change a couple of things:

/**
 * Implements hook_drush_command().
 */
function drush_content_types_drush_command() {
  $items['mijn-contenttypes-lijst'] = array(
    'description' => dt("Show a list of available content types."),
    'aliases' => array('mcl'),
  );
  return $items;
}

The array key under $items and the "aliases" value under that need changed. The array key is used to identify the callback to invoke when using the drush command or alias. The callback, for whatever reason, doesn't start with the command file prefix but rather starts with "drush" and then the command file prefix and then the array key listed above replacing the dashes with underscores. So the second (callback) function would look like...

/**
 * Callback for the content-type-list command.
 */
function drush_drush_content_types_mijn_contenttypes_lijst() {
  $content_types = array_keys(node_type_get_types());
  sort($content_types);

  drush_print(dt("Machine name"));
  drush_print(implode("\r\n", $content_types));
}

Making those changes should give you what you want. More information about creating your own drush commands can be found here: Command Authoring


How to get All options of a 'select' field? How can I get all options for a cck field?

For example, There is a field with 3 options in allowed values, like option1, option2, option3.Is there any function which receive the field name and returns option1 to option3?

You can also use list_allowed_values().

$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);


What are the CSS classes for block instances? Preface

Now in Drupal 8 we can finally create block instances: i.e, placing a block more than once -> in more than one region.

Does any instance has a unique css class?

Why I ask this?

In some cases you want to hide 1 block instance, but not the other.

For example, say you have the block "contact_form" in 2 regions: "Highlighted" && "Sidebar". You can hide the first instance for desktop devices, thus making it appear only for mobile devices this way:

media screen and (min-width: 768px) {

#block-contact-form .instance_1 {display: none}

}

.instance_1 is a fictive name and I used it only to explain how such a class is so needed.
Its .instance_1 and not .instance_2 as In Drupal machine-generated objects are usually Zero-based indexed.

Doing so can be good for better UI-UX and better accessibility for mobile-device users.

After I created a second instance for a block, I saw that Drupal 8 doesn't create a class to mark it, but rather creates a similar, yet almost identical CSS id (#) name for it which is not zero-based index in this case, rather one-based-indexed.

For example, if the first instance' id is #block-contact-form, the second will be #block-contact-form-2.

If we want to hide only the first instance, we can now do:

media screen and (min-width: 768px) {

#block-contact-form {display: none}

}

If we wanted to hide the second one we would change #block-contact-form to #block-contact-form-2.


Groups and Private File Visibiility I have created a content type Agenda - the body is paragraphs - there are two types: (1) Text and public files and (2) Private Files.  The fields work properly - Anonymous cannot see Private Files.  Authenticated Users can see Private files.

My issue occurs when I create group content for Agenda.  Non-members can see Private Files.  I cannot figure out where to go to turn this off.  The paragraph Private Files is set for view for authenticated user.  I cannot find in group how to change paragraph.

Any help is appreciated.

You may need to implement hook_file_download().


Load title and header HTML by URL I'm using drupal 7 and I want to load the view title and header HTML of this view by Its URL. Is IT possible?

There's not a direct function that I'm aware of. But you can query the views_display DB table, indirectly to retrieve your view as the path data is serialized information:

function get_view_from_path($path) {
  $page_views = db_select('views_display','vd');
  $page_views->join('views_view', 'vv', 'vv.vid = vd.vid');
  $page_views = $page_views->fields('vd')
    ->fields('vv')
    ->condition('display_plugin', 'page')
    ->execute();

  foreach ($page_views as $view) {
    $options = unserialize($view->display_options);
    if ($options['path'] == $path) {
      return views_get_view($view->name);
    }
  }
  return FALSE;
}

if ($my_view = get_view_from_path('my-view-path')) {
  // @TODO: Look @ $my_view->display["page"]->display_title
  // $my_view->display["page"]->display_options['header']
  // for title & header data.
}


Executing a method of a custom entity after all instances have been built I'm putting together a private message module. Conversations threads are a custom entity within the module. A thread can potentially appear twice on a page - once in the 'inbox' (a block), and once as the main content of the page. I'm wrapping the rendered threads with a div that I'm attaching in an override of EntityViewBUilder::view(). If the user has not viewed the thread, I'm adding a class of 'unread-thread' to the div wrapper.

Where I'm running into a problem, is finding a place to mark the thread as 'read'. If I do it at the end of EntityViewBuilder::view(), then the class is only applied to the first instance of the thread on the page, since it's already been marked read by the time it comes to the next instance of the thread on the page. I want the class to be part of the wrapper on all instances of the thread on the page.

So I need to find somewhere to mark a thread as read, but only after all instances on the page have passed through EntityViewBuilder::view(). I'm thinking a post-render hook may be good, but I'm not finding one. Does anyone have any suggestions?

You can use an event for this, a RESPONSE event with a low priority or a TERMINATE event. See for example UserRequestSubscriber::onKernelTerminate:

/**
   * Updates the current user's last access time.
   *
   * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
   *   The event to process.
   */
  public function onKernelTerminate(PostResponseEvent $event) {
    if ($this->account->isAuthenticated() && REQUEST_TIME - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {
      // Do that no more than once per 180 seconds.
      /** @var \Drupal\user\UserStorageInterface $storage */
      $storage = $this->entityManager->getStorage('user');
      $storage->updateLastAccessTimestamp($this->account, REQUEST_TIME);
    }
  }


Display a field of one content type based on another selected value Screen Preview

I am using DRUPAL 7. I have created  custom content types credit card detail. When adding a new card I want to select the country first and based on that loads related banks in the second drop down. I need help to resolve this issue.Thanks.

Note: country list is loading from countries module, where banks from a db table.

You will have to use AJAX.

Using hook_form_alter you can add ID to the element which needs to be changed.

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

 //First add id to the field to be changed

  $form ['field_bank'][LANGUAGE_NONE][0]['value']['#prefix'] = '
';
  $form ['field_bank'][LANGUAGE_NONE][0]['value']['#suffix'] = '
';

//Then you can add AJAX to the countries field like this:

$form ['field_country'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
  'callback' => 'MYMODULE_ajax_callback',
  'wrapper' => array('replace_textfield_div')
          );
 }

Now in your ajax callback function:

  function MYMODULE_ajax_callback(){
    $country = $form_state['values']['field_country'];

      if($country == 'US'){

             $options = array('Bank1'=>'Bank One', 'Bank2'=>'Bank Two');
           // and so on . You can Load Banks from DB_TABLE and place them here according to your need
             $form['field_bank']['#options'] = $options;

       }
   //AND OTHERS according to your requirement

  return  $form['field_bank'];

   }

Please remember to rename the fields according to your forms and requirements.


How to import Joomla user created date to Drupal? This new site is migrated from Joomla to Drupal. Most users were created 44 years ago and they should not be. I found out the created date format is different between Joomla and Drupal. So, how can I migrate or convert Joomla created date(something like this "2008-08-05 20:20:42.000000") to Drupal(something like "1335285830")?

Additional information

PS: I output Joomla Created Date as CSV.

Drupal uses timestamp for a date.
You could convert it to timestamp using strtotime()

$timestamp = strtotime('2008-08-05 20:20:42.000000');

Now in $timestamp you will have same output as in Drupal db.


Global Submission validation based on a select item Is there a way to get Drupal 7 / Webforms to block a submission for a duplicate answer in a previous submission.  I am sending an application questionnaire to multiple app owners, the form is setup with a listbox containing the App name, then the rest of the form is generic for each app.  I would like for the App owners to not be able to accidentally submit for the same app twice.

Many people have suggested the "Webform Validation" module, but as far as I can tell, it only does validation on the form itself.  It cannot do validation for the form being submitted against previously submitted forms.

TIA

If I understood your question correctly, Webform supports this out of the box.

Edit the "app name" field and under "Validation" select the "Unique" checkbox:

  Check that all entered values for this field are unique. The same value is not allowed to be used twice.

This will make sure that each webform entry has a unique value for this field, meaning that duplicates will not be allowed.

UPDATE

Here is a sample code that will allow you to validate the webform submissions.

Create a new folder called custom in sites/all/modules, and then another folder called sample in custom.

Place the following in sample.info file:

name = Sample
description = Sample custom module that provides custom webform validation rules.
package = Custom
core = 7.x
version = 7.x-1.0

Place the following in sample.module file:

/**
 * Implements hook_form_alter().
 */
function sample_form_alter(&$form, &$form_state, $form_id) {
  // Make sure that we are selecting the webform forms.
  if (substr($form_id, 0, 20) == 'webform_client_form_') {
    $form['#validate'][] = 'sample_webform_validate';
  }
}

/**
 * Sample validation callback.
 */
function sample_webform_validate($form, &$form_state) {
  // Replace this with the name of your field, cid (webform component ID) and
  // nid.
  $field_name = 'select_something';
  $cid = 1;
  $nid = 4;
  // Check if this is a duplicate.
  $is_duplicate = db_select('webform_submitted_data', 'd')
    ->fields('d')
    ->condition('nid', $nid)
    ->condition('cid', $cid)
    ->condition('data', $form_state['values']['submitted'][$field_name])
    ->execute()
    ->fetchObject();
  if ($is_duplicate) {
    form_set_error($field_name, t('Duplicate value, please select something else.'));
  }
}


Converting seconds to date with Facet API I've inherited a project that deals with Drupal Facet API. I've got everything working fine, except for the display of the date for events.

The filter by date and time >> start date displays the date in seconds, however I would like this to be the date and time, e.g. Saturday 14th September 10:15 am

Here is the code from the event_system.module:

     if (isset($variables['view']) && $variables['view']->name == 'events') {
    $i = $variables['view']->row_index;
    $timestamp = strtotime($variables['view']->result[$i]->field_data_field_date_and_time_field_date_and_time_value);
    $variables['post_date'] = format_date($timestamp, 'medium');
  }

I've tried this:

$variables['post_date'] = format_date($timestamp, 'custom', 'g:i a, d F, Y',0);

and this:

$variables['post_date'] = format_date('l jS F Y', strtotime($timestamp));

I've tried adding different parameters to format_date but with no success. If someone could point me in the right direction that would be great.

So it sounds like the issue is you need to convert a UNIX timestamp to a human-readable datetime?  PHP comes with the date() function which can handle this.

The first argument is the 'format' which you can find here: http://php.net/manual/en/function.date.php.

The second argument is the UNIX timestamp--just simply pass in the timestamp variable (the # of seconds) as the second argument.


How to provide facility to download & upload files to specific type of user in drupal 6 What i did:-

So , i am create one content type like "login_page", so in that i want to display title , description and file download & display. This content type display on when user logged in instead of user page . And i have 2 types of user i.e Customer user & guest user.

What i want:-
So now i want to display or download text file such as pdf or doc files facility to customer user & display facility to guest user . This files are uploaded by the admin.

So for that any module is available or any solution nearly same to such situation. Please help me i am stuck on that.

Create two roles namely "customer" and "guest" (if you had not created yet). Now you can use field_permissions to give each role the  permission you want. Add permission to customer role to download it and guest to view it.


how can I make a welcome popup window upon visiting the website Some clients I have may want a popup when a user visits the site if they have special events going on, and display maybe a flyer in a popup.

How can I force a popup upon a user visiting the site? Is there a module that can accomplish this? If not, what kind of edits am I looking at doing?

You are looking for Splashify module, it also have the option to popup on any page.

  Display a splash page anywhere on your site by redirecting the user,
  showing a lightbox, or displaying a popup. This module is designed to
  be search engine friendly, mobile device friendly and offers multiple
  configuration options.

or

You can try TinyBox (Simple Splash). see the demo

  The main purpose of this module is to provide Splash Screen/Window as
  simple as possible.

or

take a look at Splash Offer module

  Allows the management of one or more "splash offers", which are modal
  popups with an accept or reject form. If a user accepts the offer then
  a new page will open with a provided accept url. If they reject the
  offer, the modal will close.


Custom block: How to know you're in an admin context? I've developed a custom block which relies on a taxonomy term ID being present in the URL, otherwise it throws a 404.

I've placed this block in a panel page (ctools pages), but now when I try to edit the panel page, I get a 404 response, but only on the "Content" tab of the panel page variant.

What's the proper method for knowing you're on an admin page, or in the context of a panel edit, so that I can skip throwing a 404?

Looks like I just need to call path_is_admin

if (!path_is_admin(current_path())) {
  drupal_not_found();
  drupal_exit(); // This is needed if we call drupal_not_found() from hook_block_view()
}


How many web pages can the Panels module handle?  What's the performance impact? I'm creating new site in Drupal 7, and I must use about 400 panel pages with Views.  I'm wondering how many panel pages I can use in my site without affecting performance? Can Drupal/Panels handle 400 panel pages?

There is no reason to believe that "Panels is slow". This is a misconception created by the fact that Page manager and Panels modules are complicated, and not easily understood.

Panels is actually sometimes faster than core is on it's own.
And that's without utilizing caching, something Panels can do much better than core, because it allows you to do it from on a page by page basis, down to on a block by block basis.

At NodeOne, we build all our sites using Page manager, Panels, and Panels Everywhere. I have yet to see a performance problem caused by the use of Panels itself. That said, you should consider using Caching, as a website utilizing Panels well is most likely a complex one. (I'm no longer with that business, but this remained true for as long as I was)


Updating Drupal core in a Acquia Dev Desktop? Running the latest Acquia Dev Desktop (with subscription) with Drupal 7.22 core.

I´d like to update the Drupal core to the most recent version, but after reading the documentation on Acquia that is available to unsubscribed users, I wonder if that is at all possible. Any ideas on how one would go about this?

The Acquia documentation for Dev Desktop lists very clearly the steps that need to be taken to upgrade your Drupal install: https://docs.acquia.com/dev-desktop/upgrade.

Also, if you are a subscriber, you can open a ticket with them and they will assist you.


How to install patched Paypal module in Drupal Commerce? I am not an expert of Drupal, but I am trying to configure a site with Drupal Commerce, and in particular, the PayPal module.

I need the following two patches:
https://www.drupal.org/node/2415489
https://www.drupal.org/node/2415501
that, if I understood correctly they are not merged into the paypal module yet.

So, what I did is to manually download the PayPal module, manually apply the patches (unfortunately they conflict each other, so I applied one with the patch command and the other by manually diff the files) and I tar.gz everything.

The resultant module is here: https://dl.dropboxusercontent.com/u/7968745/commerce_paypal-7.x.2.3.tar.gz

Now, if I try to install this module I get the following error:

Unable to create directory 'temporary://update-extraction-bde81194/.'

But if I try to install any other module, it works.

BTW: I don't know if this is relevant or not. Before installing my custom-made module, I disabled and uninstalled the PayPal module, but if now I look for the modules in my Drupal installation I still find the PayPal module (but disabled)

You have to make sure that the temporary directory is configured at admin/config/media/file-system is writable.

In my case /tmp is writable, as per the settings in the screenshot below.


Update Two select box when change another select box I have drupal form with three select box i want to change select box 2nd and 3rd after change value of 1st select box.

ex:
i have Three select box

1) Cruise line

2) Destination

3) Ship Id

When user select any value of Cruise line then i want to update value of 2) Destination and 3) Ship id

2nd and 3rd select box value are dependent on 1st select box

your answer really appreciated

Thanks in advance

Try one of the following module

Simple hierarchical select

  Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Hierarchical Select

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

Or you can also achieve that by writing a custom module :)


How to display fields horizontally in a node? A node lists all its field vertically one after the other by default. Does anyone know of a way to display at least some of the fields horizontally?

Like so:

FIELD 1               FIELD 2              FIELD 3

The default behavior of Drupal's field display is to wrap the content in DIVs, which are displayed as block-level elements by default, hence, one per line.

There are a number of different ways to solve for your display needs.

As Sidharth mentioned, displaying fields can be done via custom CSS. Typically you'd want to create a custom node.tpl.php for your theme and apply your CSS rules to those elements in your template.

Another solution, if you're not looking for custom templates for different node types, is the Field Group Inline module.


Add condition group in Views filter handler I have a Views filter handler, which does

$this->query->add_where(
  $this->options['group'],
  $this->real_field,
  vms_get_current_mlid(),
  $this->operator = ($this->operator == '=') ? 'IN' : 'NOT IN'
);

Which initially looks fine, but fails with "NOT IN", when the field value is NULL, as NOT IN (100) does not return TRUE for a NULL value, which is what I would like.

When the operator is 'NOT IN', I need to add a "OR IS NULL" operator as well, but still keep it within the same group.

If the filters are

  Node is "page" AND NID_REFERENCE NOT IN (100, 101, 102)

I would like that to become

  Node is "page" AND (NID_REFERENCE NOT IN (100, 101, 102) OR NID_REFERENCE IS NOT NULL)

How do I do that?

The answer turns out to be that  add_where() also accepts a DatabaseCondition argument, meaning I could do

$this->query->add_where(
  $group,
  db_or()
    ->condition($table, $vms_target, 'NOT IN')
    ->condition($table, $vms_target, 'IS NULL')
)


How to create an EMPTY anchor-only link with l()? I'm trying to use l() to get something like , for ajax-calling purposes.  https://stackoverflow.com/questions/1698453/drupal-creating-anchor-only-link-with-l is very close to the right thing -- use an option in l() like 'fragment' => 'foo' to produce a link like  -- but I'm trying to get a clean '#'.  Is there any way to do this, or should I just put something in as part of the fragment and not worry about it?

PHP typecasting pop quiz time! (Full disclosure: I didn't win in our office).

As pointed out already, this is the code in l() that we're concerned with:

if (isset($options['fragment']) && $options['fragment'] !== '') {
  $options['fragment'] = '#' . $options['fragment'];
}

So here's the question: What value casts to an empty string but passes the following?

(isset($var) && $var !== '')

The answer is: FALSE!

So, we could try this:

l(t('My link'), NULL, array('fragment' => FALSE));

Which gives us:

My link

Thankfully we can strip that leading slash by passing along external => TRUE:

l(t('My link'), NULL, array('external' => TRUE, 'fragment' => FALSE));

Which gives us:

My link

Boom. The things we do to avoid concatenating html strings manually, eh?

Postscript:

I'm not sure I'd actually recommend printing a link like this from php under normal circumstances. Without your javascript, all that link is going to do it jump your user to the top of the page (which, to my slight surprise, is specced behaviour). It should probably point somewhere that works without javascript.

If the link really only makes sense with javascript around (like the controls for a js-only slideshow or something), I think it's better to add the link to the page with javascript. Alternatively, if you really want to put it in your source, make sure it's display:none'd by default. Drupal has the .js class on the html for then showing it when javascript is around.


how to show all alphabates in glossary block in drupal 7? I have a glossary view in drupal 7 with attachment. These attachment missing some alphabates. showing like a|c|d|h|m etc. But I need a|b|c|d|e|f etc like this.

Did you check this module?

https://www.drupal.org/project/views_glossary

It provides exact same functionality.


How to send one time login url with Rules? I have a rule to create a user and an action to send login url to user's email. I didn't find any action to send login url, so added an Send HTML Email action and added the [user-created:one-time-login-url] token in mail body. but it appears as it is([user-created:one-time-login-url]), and is not translated to login url.

Then I used this php function to print the same url:

<?php
print user_pass_reset_url($user_created);
?>

It prints a url but also prints the following notices:

Notice: Undefined property: stdClass::$uid in user_pass_reset_url() (in line 2299 /var/www/web/modules/user/user.module).
Notice: Undefined property: stdClass::$pass in user_pass_reset_url() (in line 2299 /var/www/web/modules/user/user.module).
Notice: Undefined property: stdClass::$login in user_pass_reset_url() (in line 2299 /var/www/web/modules/user/user.module).

$user_created is the php variable referring to the user created in the previous action. But it seems it's not a user object(because of notices).

What's the proper way to send one time login url?

Try out Login one time module

  The use case for this is where your users can't figure out how to use
  a username and password - so they request an email link to what they
  need.


D7 - download files works for admin, not for other users There is a content type for accepting job applications, including resumes and cover letters as files uploaded. The files are set to private.

The form/page is set to unpublished by default - largely to 'fix' some other wonkiness.

Users with admin privileges have no trouble downloading the resume and cover letter files.

The more limited users in HR cannot - Drupal returns a message

  You are not authorized to access this page.

I've been tweaking permissions trying to find the magic bullet. The HR user can 'Edit' the individual's application form, but even though the associated resume or cover letter file is shown as a link, once again, the HR role is not authorized.

Any ideas what permission I need to toggle? What's blocking the ability for the HR role to download the file?

As you setup the content type default as unpublished, this will prevent any one to see the individual content but the author of the content(if he or she has permission to "View own unpublished content") and User with the privilege of "Bypass content access control"
which probably you don't want to give it to any one but admin, so basically there is a better approach to this :

I recommend to

1) setup content type default as published

2) Setup Content Access module http://drupal.org/project/content_access

3) Setup content type access permission by Content Access module.

3-1) Use Content access module to prevent any user but HR to have access to the specified content type. This will prevent any one to have access to following content type but HR, so you don't need to worry about content being published.

3-2) give permission to the specified rules (maybe anonymous or authenticated) to be able to create the specified content type.

Note: Don't do this in production environment, first test it to make sure everything is as you want it since "content access" module will rewrite your current website permissions.

If it still seems confusing let me know I will add photos to explain it.


Language Manager getCurrentLanguage returns default language instead I am creating a multilingual D8 site, which 3 languages enabled.

In trying to display the currently active language, the snippet

$lang = \Drupal::languageManager()->getCurrentLanguage()->getName();

always returns the default language ( English ) even though the UI has switched to one of the alternative languages. The above line is called from the mytheme.theme file in hook_preprocess_page.

In the language switcher block, the correct language is getting the session-active is-active classes.

When referencing the documentation for D8.5 in the above method, in the code shown it very much shows like this is what the function does:

public function getCurrentLanguage($type = LanguageInterface::TYPE_INTERFACE)
{
  return $this
    ->getDefaultLanguage();
}

Am I missing something obvious here? Is there another way to get the current active language?

The method you've quoted is the default code for single language sites. For multilingual sites the default LanguageManager is replaced with ConfigurableLanguageManager and the method is overridden wtih this content:

ConfigurableLanguageManager::getCurrentLanguage:

public function getCurrentLanguage($type = LanguageInterface::TYPE_INTERFACE) {
  if (!isset($this->negotiatedLanguages[$type])) {

    // Ensure we have a valid value for this language type.
    $this->negotiatedLanguages[$type] = $this
      ->getDefaultLanguage();
    if ($this->negotiator && $this
      ->isMultilingual()) {
      if (!$this->initializing) {
        $this->initializing = TRUE;
        $negotiation = $this->negotiator
          ->initializeType($type);
        $this->negotiatedLanguages[$type] = reset($negotiation);
        $this->negotiatedMethods[$type] = key($negotiation);
        $this->initializing = FALSE;
      }
      elseif ($type == LanguageInterface::TYPE_INTERFACE) {
        return new Language([
          'id' => LanguageInterface::LANGCODE_SYSTEM,
        ]);
      }
    }
  }
  return $this->negotiatedLanguages[$type];
}

Then the result depends on the language negotiators you have configured in language detection, see comment from @Clive.


I want to display one content type inside of another I have a page called "Our Team" that will display all the members of our team. I have a content type called "Team Member" and have created many team members under this content type. How can I list all "Team Members" on one page?

What I would do is the combination of the comments above.

To your team 'Team member' content type add entity reference field with reference to 'Our Team' content type
Create a view that lists all of your team members (regardless the team for now).
In 'Contextual filters' under 'Advanced' settings of your view that you created in 2. add the field the you created in 1.
In the settings of that filter select 'Provide default value' and choose 'Content ID from URL'
Save your view.
Add view field to your 'Our Team' content type, in the settings of that field select 'Always display default value' and below select the view that you created in 2.

As long as I understood you correctly this should do the trick.


Is there a drupal 7 module for webform password and password confirmation fields? Is there any module that I can use for password and password verification field on webform.

I googled the sites and apparently the webform_password module is for drupal 6 only.

Thanking you in advance

Well, actually there's an issue posted for Drupal 7 webform_password module.

Checkout the issue here

You can download webform_password module for Drupal 7 from here


New user registration fields I have a site with about 30 members, but I just added a new mandatory field on the registration. I want the old members to be forced to fill this in as well. What would be the best way to do this?

Choose one:

Use the rules module to test whether the user has authenticated and the field value of the current user is empty. Redirect to user/[uid]/edit if this is the case.
Do the same test in a module during your implementation of hook_init(). Call

drupal_goto('user/[uid]/edit')

to redirect to the user edit page.
Do the same test in a module during your implementation of hook_init(). Call

menu_set_active_item('user/[uid]/edit');

to show the user edit page.

Replace [uid] by the user id of the currently logged in user.

In cases 1 and 2, you also have to make sure that you do not redirect from 'user/[uid]/edit' back to 'user/[uid]/edit'. This would create an infinite  loop of redirections, because the POST data gets lost when redirecting.

Documentation:

drupal_goto()
menu_set_active_item()


Programmatically create a taxonomy and attach a field to it I created a vocabulary using the following code.
$vocab = entity_create('taxonomy_vocabulary', array(
  'name' => 'vocab_name',
  'vid' => 'vocab_id',
  'description' => 'description'
));
$vocab->save();

I need to attach a custom field to it. I created the field with BaseFieldDefinition::create('string'), bu I couldn't figure out how to attach the created field to $vocab.
How can I achieve it?

Create them in the ui, export them to yaml using the single config export ui, put the yaml files in your_module/config/install - done


Module for Importing and exporting Vcards Is there drupal module to support importing vcard details to the site and publish the details of the content?

Thank you

You can check the vCard module. It can be useful for you.

Here is a quote about it (from the module's project page):

  ... adds a vCard download link to every users profile. This link makes it easy to add users on your Drupal site to your local address book. Since we love microformats, there is also a theme function (theme_vcard) for displaying user data in the hCard format.


Relationships block other content type from showing I have this views_slideshow and its supposed to show two content types, but shows only one. One is simple content type with image field (the one that is not getting showed) and other is commerce product type with relationships and contextual filters. So could this be something blocking this other non commerce content type from showing up? If I remove relationships for product, then it shows the Slideshow content type, but hides Products content type.

Solved by adding :title filters and setting both to not empty. Also set second filter (default, not referenced) for a separate group under OR setting.


Why arn't changes I am making in CSS appearing? This is weird. I've just started at a company that uses Drupal (I havent used it before) and I've been tasked with making some simple CSS changes to a site.

I find the site's theme folder and corresponding CSS and make a simple change just to test things out. Nothing happens. I clear the cache via admin and get a 500 error. Fine. So I use drush to clear CSS and JS. It says it works but still no change. I clear my browser cache too just to be sure.

I use Chrome's inspector to trace back the paths of the CSS files I'm working on - they're correct. I even check the themes .info file to see if all the .css files are linked - they are.

So...what am I missing here? What on Earth is going on?

(Edit: CSS aggregators are off)

I'd turn off CSS aggregation temporarily to see if that makes any difference. The settings are in admin/config/development/performance

That way you can see which CSS files are being used directly. This sounds like it might be a configuration problem with the server itself and not something with Drupal.

Also, check the response headers for the CSS. That will give you more info about whether it's serving cached versions and if there's something like a reverse proxy serving old versions of the files.


How to display a create node form together with a referenced node of a different type I'm using a content type for Clients and another content type for Tasks. Each client has many tasks and each task belongs to one client. Both types are connected by a reference field defined for the Task content type that points to a Client node.

I know how to display a Client's information together with a list of all Tasks for that client. I'm using a view in a block that is parameterized with the Client node ID. That was easy.

However, in order to create a new Task for a Client, I need to display the Client's information together with the create new task form.

Is there any way I can do that in Drupal 7?

If you need to put that info in a block near the form, you can create your custom hook like

function mymodule_menu(){
  $items = array();
  $items['mynode/add/%/%'] = array(
      'title' => t('Create content'),
  'description' => 'Calls to a drupal_get_form',
  'access callback' => 'user_access',
  'page callback' => 'my_function',
  'page arguments' => array(2,3),
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
 );

 return $items;
}

So now you have a page called /mynode/$type/$id_user

In that page you can render the form of that content type using drupal_get_form() and returning it rendered. Now in the blocks config you can add your block view to the pages called /mynode/mytype/* , getting the user id argument from the url will let you render that view with the user data.


Mobile_detect php redirecting to subdomain - Stuck in a redirect loop! I am using the following code in a module for redirection to a subdomain whenever a mobile is detected;

<?php

  function mobydetect_init() {
  include("PATH/TO/Mobile_Detect.php");

  $detect = new Mobile_Detect();
  if ($detect->isMobile()) {
    header('Location: http://m.mysite.com');
    drupal_exit();
  }
}

However when I go to my site using a mobile I get this error message;

"This web page has a redirect loop."

I have disabled to subdomain from redirecting to the main domain in Aegir. So where's the loop coming from?

Presumably your hook_init runs on both domains.

You need to check you're not already on the redirected page prior to redirection.

e.g

/**
 * Implements hook_init
 */
function mobydetect_init() {
  if($_SERVER['HTTP_HOST'] != 'm.mysite.com'){
    include("PATH/TO/Mobile_Detect.php");
    $detect = new Mobile_Detect();
    if ($detect->isMobile()) {
      drupal_goto('http://m.mysite.com', array('absolute' => TRUE, 'external' => TRUE));
    }
  }
}

Note, hook_init doesn't run on cached pages so you may find mobile users aren't redirected on cached pages. You could try using hook_boot instead or else offload to the webserver conf.


Views Count with multiple fields I have 2 fields that each can have multiple values. I want to count the number of values for a given content type (Actions). Using aggregation everything works fine when the display/view has one field but when I add subsequent fields the results do not come close to adding up.

Record 1 => Field a has 2 values selected, field b has 4
Record 2 => Field a has 4 values selected, field b has 6

Result should be ... Field a = 6 and Field b = 10

Since you are using Views, can't you use the delta value of the field? It should give you the amount of fields-a & fields-b per node. If you have 2 value's in field a. field a:delta = 2. From there you should be able to aggregate over several nodes.

It won't give you the value's of the selected fields though.


Call javascript right after the form elements are rendered I have a content-type "Document". I have a multiple select dropdown box in my form.

$form['priorities']['selectoffid'] = array(
    '#type' => 'select',
    '#title' => 'Select Signatories',
    '#id' => 'select-chosen',
    '#attributes' => array('multiple' => 'multiple', 'style' => 'width:100%'),
);

Each option of the dropdown corresponds to a textfield. Selected option's corresponding text field are shown and unselected option's corresponding text field are hidden.

Now everytime I hit the Save button  and some other required form elements are not filled, it reloads and display the form errors. After reloading some text fields that are supposed to be visible is now hidden.

The value of the multiple select dropdown still consist of 3 values, according to the $form_state variable , but some of it's corresponding text fields are not visible anymore. How will I make it visible again? I tried using after_build form.

$form['#after_build'][] = 'document_monitoring_form_after_build';

function document_monitoring_form_after_build($form, &$form_state){

    drupal_add_js(drupal_get_path('module','document_monitoring') . '/myscript.js');

    return $form;
}

In my myscript.js :

alert('Javascript is called');
document.getElmentById('priority-6').style.display = 'block';
document.getElmentById('priority-22').style.display = 'block';
document.getElmentById('priority-5').style.display = 'block';
alert('Javascript is called');

The javascript is called before the multiple select dropdown is rendered. How will I make the javascript be called right after the form elements is rendered?

You need to wait for the DOM to be ready (i.e. when then browser has finished comprehending the HTML).

Drupal's javascript API provides a natural place for your code, in the form of a behavior, e.g.

(function($) {
  Drupal.behaviors.mymoduleFoo = {
    attach: function(context, settings) {
      $('#priority-6').show();
      // ...
    }
  };
})(jQuery);

The attach method is invoked when the DOM is ready, and also at other points in the page execution when something might have changed (e.g. when an AJAX call is made), to give you the opportunity to respond to any new/change elements that might affect your code's functionality.


Use a view's result as a javascript setting I am trying to integrate the Supersized javascript library (http://buildinternet.com/project/supersized/) into my site.

It requires an array of image urls when initialized.

I would like to use a view to populate this array so that my content editors can easily update the site with new background images.

Does anyone know how to do this with Drupal 7?

I have seen the http://drupal.org/project/supersized module, but as far as I know it doesn't work with views.

It looks like Supersized wants a slides array with the information about each image.  You could build the slides array dynamically from the view.

Two fields in the view:
(1) The image,
(2) The image thumbnail

The slides array wants these properties: image, title, thumb and url.

You could derive the image src, the title and the url from the image field (make sure it links to something).
You could derive the thumbnail src from the image thumbnail field.

And here is some code that with modification should work just fine (taken from Supersized demo page):

jQuery(function($){

  var slidesFromView = [];

  $(".view-supersized .views-row").each(function(){
    var rowImage = $(this).find(".views-field-image img").attr('src');
    var rowTitle = $(this).find(".views-field-image img").attr('title');
    var rowThumb = $(this).find(".views-field-image-thumb img").attr('src');
    var rowUrl = $(this).find(".views-field-image a").attr('href');
    slidesFromView.push({image: rowImage, title: rowTitle, thumb: rowThumb, url: rowUrl});
  });

  $(".view-supersized").hide();

  $.supersized({

    // Functionality
    slideshow               :   1,          // Slideshow on/off
    autoplay                :   1,          // Slideshow starts playing automatically
    start_slide             :   1,          // Start slide (0 is random)
    stop_loop               :   0,          // Pauses slideshow on last slide
    random                  :   0,          // Randomize slide order (Ignores start slide)
    slide_interval          :   3000,       // Length between transitions
    transition              :   6,          // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
    transition_speed        :   1000,       // Speed of transition
    new_window              :   1,          // Image links open in new window/tab
    pause_hover             :   0,          // Pause slideshow on hover
    keyboard_nav            :   1,          // Keyboard navigation on/off
    performance             :   1,          // 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
    image_protect           :   1,          // Disables image dragging and right click with Javascript

    // Size & Position
    min_width               :   0,          // Min width allowed (in pixels)
    min_height              :   0,          // Min height allowed (in pixels)
    vertical_center         :   1,          // Vertically center background
    horizontal_center       :   1,          // Horizontally center background
    fit_always              :   0,          // Image will never exceed browser width or height (Ignores min. dimensions)
    fit_portrait            :   1,          // Portrait images will not exceed browser height
    fit_landscape           :   0,          // Landscape images will not exceed browser width

    // Components
    slide_links             :   'blank',    // Individual links for each slide (Options: false, 'num', 'name', 'blank')
    thumb_links             :   1,          // Individual thumb links for each slide
    thumbnail_navigation    :   0,          // Thumbnail navigation
    slides                  :   slidesFromView,

    // Theme Options
    progress_bar            :   1,          // Timer for each slide
    mouse_scrub             :   0

  });
});


Drush not connecting to site's settings.php When I run drush --debug status in the docroot of my Drupal site, I get the following message:

[user@computer]$ drush --debug status
Phar detected. Proceeding to drush_main().
Loading drushrc "/home/user/.drush/drushrc.php" into "home.drush"[bootstrap]
scope. [0.02 sec, 3.54 MB]
Cache HIT cid: 8.1.14-commandfiles-removed    [debug]
[0.03 sec, 3.59 MB]
Bootstrap to phase 0. [0.28 sec, 9.55 MB]                            [bootstrap]
Trying to bootstrap as far as we can. [0.28 sec, 9.56 MB]                [debug]
Found command: core-status (commandfile=core) [0.28 sec, 9.56 MB]    [bootstrap]
Loading outputformat engine. [0.28 sec, 9.56 MB]                        [notice]
Calling hook drush_core_status [0.29 sec, 9.85 MB]                       [debug]
Returned from hook drush_core_status [0.38 sec, 9.86 MB]
         [debug]
 PHP configuration      :  /etc/php.ini /home/user/.drush/drush.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.14
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /home/user/.drush/aliases.drushrc.php
Command dispatch complete [x.xx sec, x.xx MB]                           [notice]

As you may see in that output, "PHP Configuration" has two entries where as "Drush configuration" has none. And that one of the entries for "PHP Configuration" looks like the entry that should be in "Drush configuration".

I did run it within the docroot of Drupal. And I have even tried in sites/default. Plus, I have even tried my aliases and none of them are working. This all worked before though with another Drupal site. It just stopped working after I transferred the Drupal files from one server to another. I thought my permissions were correct but they don't look correct. Plus I have even tried adding --uri and --root to Drush and that didn't work either. For the transfer I used rsync options avzp.

drush -d pm-info give's the following:

[user@computer]$ drush -d pm-info
Phar detected. Proceeding to drush_main().
Loading drushrc "/home/user/.drush/drushrc.php" into "home.drush"[bootstrap]
scope. [0.02 sec, 3.54 MB]
Cache HIT cid: 8.1.14-commandfiles-removed    [debug] [0.03 sec, 3.59 MB]
Bootstrap to phase 0. [0.27 sec, 9.55 MB]                                              [bootstrap]
Bootstrap to phase 6. [0.28 sec, 9.56 MB]                              [bootstrap]
Command pm-info needs a higher bootstrap level to run - you will need[error]
to invoke drush from a more functional Drupal environment to run this
command. [0.28 sec, 9.56 MB]
The drush command 'pm-info' could not be executed. [0.28 sec, 9.56   [error]
MB]

Changing the ownership of the some of the files in the sites directory seems to have fixed the issue.


How can I bypass required fields when saving a node as unpublished? I am saving node as unpublished without adding data in required fields. How can I achieve that in Drupal 8 ? Basically I need something like Save as Draft option for nodes in content types.

There's the Require on Publish module. You'll have a checkbox for all fields beneath the default "Required" checkbox that says "Require on publish". So you need to have the default "Required" checkbox unchecked and just check "Require on publish". Quite clever actually.

This module allows fields to be required only when the piece of
content is being published or is already published. This can be used
when you have fields such as tags or SEO information on your piece of
content that editors really don't need to fill in until the content is
going live.
Usage
When managing a field for a content type, click the new 'Required on
Publish' checkbox instead of the 'Required field' checkbox.


Sending Auto-filled Email from Content Type Profiles I have 'resource' content types. There are hundreds. I want each profile to contain an individualized link to a 'feedback form', or some mechanism to report an error with the profile, by email...to our staff. These items are coming from the DB, obviously. So something like the following:

Resource Name
Type
Description
[LINK to submit problem about this profile]
more details here

When the user clicks the link (in my imagination) they would either be able to send an email to someone on our staff with details auto-filled about the resource they are complaining about, OR, it takes them to a feedback form of some type with details auto-filled about the resource they are complaining about. Either way it auto-fills form fields and allows the sending of email.

Anyone know of a good module or technique for handling this?

I use Webform for this kind of thing, as long as the values being passed to the form aren't too extensive.

On the Resource page template, create links to the webform, with field values in the the URL.

Webform 4 can then use tokens to place those values from the URL into fields.

You can then use Webform Rules to send an email.

The same thing can be accomplished with Entity Form, Entity Reference, Prepopulate, and Rules.


Grant permission to current user at runtime in specific environment Many Drupal contrib modules have inverse "feature flag" implementations vis-a-vis a killswitch variable added to settings.local.php to disable a feature:

// Killswitch setting.
$settings['disable_captcha'] = TRUE;

// Config override.
$config['google_analytics.settings']['account'] = '';

However, the Drupal 8 version of CAPTCHA does not yet have the disable_captcha killswitch that existed in Drupal 7 (see related issue #2836076).

The module does have another kind of killswitch via a Drupal permission skip CAPTCHA.  This got me wondering:

Is it possible to dynamically add a permission to the current site visitor—both anonymous or authenticated users—at runtime for a specific environment without affecting the standard roles & permissions store so that configuration management/sync is not adversely affected by the environment-specific permission?

Ideally this logic would be located in settings.local.php to avoid the following risks and technical debt

the chance that unintended environments would be affected, and
to have to copy/paste/commit solutions to this problem in every client project only to have to later remove that code once the proper killswitch solution in issue #2836076 lands.

Yes you can but why not just remove the field ? here is a few ideas on to how to do it..

in settings.local.php

 //add
$settings['stop_captcha_from_being_stupid'] = TRUE;
// or
$settings['enviroment_name'] = 'dev';

in some hook_form_alter

use Drupal\Core\Site\Settings; // above ^^^
$stop_capcha = Settings::get('stop_captcha_from_being_stupid') ;
if ($stop_capcha === TRUE) {
  unset($form['captcha']);
}

// or enviroment with custom header ;)
$current_request = $request = \Drupal::request();
if (!empty($current_request->headers->get('shutup-captcha'))) {
  if ($current_request->headers->get('shutup-captcha') == 'somesalt') {
    $environment_name = Settings::get('enviroment_name') ;
    $environments_to_allow_bypass_captcha = [
      'dev',
      'int',
      'test',
    ];
    if (in_array($environment_name, $environments_to_allow_bypass_captcha)) {
      unset($form['captcha']);
    }
  }
}


Path configuration in media gallery module I am using Media gallery module to create gallery and pathauto module to generate URL.

For a gallery page I use this pattern for URL

photo-gallery/[node:title]

When user will click on any photo. I am showing that image on different page.

But I am not getting way to set path for page where the single image will be displayed.

Automatic it generates URL like this

/media-gallery/detail/356/460

Is there any way around this?
Any help will be appreciated.

The solution that Letharion posted will work fine, but making integration with path auto is a better solution like (s)he writes.

Doing this in not that hard, but it can be a bit tricky to do the first time.

To do it you need a few steps.

First you need to implement hook_pathauto in order to get the setting for how the alias should look like. Here you can give info about which type of token can be used for path replacements etc.
Second you need to create a function which can be used to generate an alias. It should look something like this.

function foo_pathauto_update_alias($file, $op, array $options = array()) {
  module_load_include('inc', 'pathauto');
  $path = media-gallery/detail/' . $file->bid . '/' . $file->fid
  pathauto_create_alias('aug_product', $op, $path, array('file' => $file));
}

Path auto is based on entities. So you need to be able to generate the path from a single entity. In this case the file that's created. By using the above function structure you can use a single function and utilize it for bulk updates as well as regular updates while keeping path auto functionality intact.
Lastly you need to call your update function when file is created or updated. This will handle path alias creation. Doing it this way, you can also get path auto to update path alias if the data is changed and the alias should be different, if you want to do so. There is settings for this in the path auto module.
For bonus you can choose to create a bulk update function, that will enable you to the alias for any file created. It takes a bit of work, but should work nicely.

Note doing it this way, it will be a good idea to use the file entity module, as it allows you to handle files like entities, which fits path auto a lot.


Set  page in theme settings? I've created a settings page for my theme, and I'd like to be able to set the frontpage from there, but I don't know how I can change the frontpage in code?

This is the setting:

$node_type = "page";
$result = db_query(
    'SELECT n.nid, n.title FROM {node} n WHERE n.type = :type',
    array(':type' => $node_type)
);
$options = array();
foreach ($result as $record) {
    $options[$record->nid] = $record->title;
}

$form['static_nodes']['front_page_id'] = array(
    '#type'        => 'select',
    '#title'       => t('Frontpage'),
    '#options'     => $options,
    '#description' => t('Set the page used as the frontpage.'),
    '#default_value' => theme_get_setting('front_page_id'),
);

Solution:

function billetsalget_form_system_theme_settings_alter(&$form, &$form_state)
{
    /**
     * The group fieldset
     */
    $form['static_nodes'] = array(
        '#type'          => 'fieldset',
        '#title'         => t('Static Pages'),
        '#weight'        => -2,
    );

    /**
     * Get pages from db as options
     */
    $node_type = "page";
    $result = db_query(
        'SELECT n.nid, n.title FROM {node} n WHERE n.type = :type',
        array(':type' => $node_type)
    );
    $options = array();
    foreach ($result as $record) {
        $options[$record->nid] = $record->title;
    }

    /**
     * Select dropdown for Frontpage
     */
    $form['static_nodes']['front_page_id'] = array(
        '#type'        => 'select',
        '#title'       => t('Frontpage'),
        '#options'     => $options,
        '#description' => t('Set the page used as the frontpage.'),
        '#default_value' => theme_get_setting('front_page_id'),
    );

    /**
     * Run function when form is submittet
     */
    $form['#submit'][] = 'billetsalget_form_system_theme_settings_submit';
}

function billetsalget_form_system_theme_settings_submit(&$form, &$form_state)
{
    /**
     * Set frontpage to 'node/' + node_id selected in the form
     */
    variable_set('site_frontpage', 'node/' . $form_state['values']['front_page_id']);
}


Creating content type using views I created a content type using views called Bars & Restaurants

I want that content type to show under my Bars & Restaurants menu link at the top of my page.

I have changed the path to http://localhost/drupal/barsandrestaurants

and the menu to: menu tab - navigation and it still only shows up on my home page.

Is there a way to display the content type only on my bars and restaurants page?

I want authenticated users to be able to go into the page and add bars and restaurants themselves.

I am very new to drupal so any help will be great!

I want the content that Im adding to be under the Bars & Restaurants page there

Assuming what you want to do is :

Make a content type which authenticated user can add by themselves called barandrestaurant.
Make a view displaying all the barandrestaurant content-type.

First creat a new content type called barandrestaurant :

You should unchecked the "promote to front page" in the content type page :

Allow user to add your content type in admin/people/permission --> find your content type node name (barandrestaurant) and allow authenticated user to create new content.

Second make a view page filtering your content type barandrestaurant

Go to admin/structure/views/add a new view and fill the form to filter on your content type like that :
Specifiy that what you want is a view page and that you want to add a menu link in navigation menu :
Add in the header or in the footer (as you want) a "global text area" with a html link to create new barandrestaurant content type page :

Add a new bar or restaurant

This should look like this :

Now you should have a content type called barandrestaurant which can be created by your authenticated users visiting the link http://www.yoursite.com/bar-and-restaurant. The link should be in your navigation menu too.


Is it possible to have three levels of subdomains in Drupal 7? I know how to create a sub domains for Drupal website (I create a sub domain and add its folder in /sites folder). Out websites are multilingual so for every language I create a subdomain and in the end the sites are going to be like this :

fr.example.com
en.example.com
ar.example.com

and so on. we have also a few sites that are subset of our main website and we want to display them like this

fr.subset1.example.com

en.subset1.example.com

ar.subset1.example.com

fr.subset2.example.com

en.subset2.example.com

is it possible to implement such thing in Drupal 7?

The answer is "yes". A Drupal multisite can use whatever structure it likes, including the one you propose.

To do this for subdomain http://fr.subset1.example.com/ just create the following subdrectory sites/fr.subset1.example.com/. Make sure it contains the file default.setttings.php and a copy this to settings.php. Then create subdirectories files  (and optionally, modules and themes), and make sure they're all writable by the web-server user.

Then:

Set up DNS for this subdomain (fr.subset1.example.com) to point to the same IP as the default domain.
Create a serveralias (details below) (or vhost entry) for that directory that has the same web root as the default domain.
Point your browser to the base URL of your website (http://fr.subset1.example.com/) to complete the web based part of the installation of a Drupal site.

To create a multi-site instance, you also need to make sure the DNS for that instance points to the same web root as the default domain. If you've set up a sub-domain, the simplest way to do this is to add it as a ServerAlias. This means putting something like this in the Apache vhost configuration:

<VirtualHost *>
  ServerName example.com
  ServerAlias fr.example.com
  ServerAlias fr.subset1.example.com
  …
  DocumentRoot /var/www/example.com/htdocs/
  …
</VirtualHost *>

Alternatively, you may create a separate vhost for the multi-site. This requires a separate entry, but allow you to tailor the web server settings for this particular multi-site instance.

Repeat this procedure for any other subdomains you want.


Redirect to page in form submit and use the form data in new page How to redirect in drupal 7 in form submission, I need to use the submitted data in next redirected page but below video_subtitle_view function is not printing anything

How do i do it

/**
 * Implements hook_menu()
 *
 */
function video_subtitles_menu() {
  $items = array();
  $items['player/video_subtitle/view'] = array(
     'page callback' => 'video_subtitle_view',
     'access callback' => 'user_access',
     'access arguments' => array('administer video_subtitles status'),
  );
  return $items;
}

    function video_subtitle_view($form, &$form_state){
    //    print 'video_subtitle_view';
        print_r($form);
        print_r($form_state);
    }

function video_upload_subtitles_form_submit($form, &$form_state) {

     $form_state['redirect'] = 'player/video_subtitle/view';
//     $form_state['redirect'] = array(
//            'player/video_subtitle/view',
//             array(
//                    'query' => array(
//                    'form' => $form,
//                    'form_state' => &$form_state,
//                   ),
//              ),
//      );

}

function video_subtitle_view($form, &$form_state){
//    print 'video_subtitle_view';
    print_r($form);
    print_r($form_state);
}

do i need to pass the form data as parameter??

You can use server session to keep your form state something like below

function video_upload_subtitles_form_submit($form, &$form_state) {
    $_SESSION['my_form_data'] = $form_state;
    $form_state['redirect'] = 'player/video_subtitle/view';

}

// Then

function video_subtitle_view(){
    print_r($_SESSION['my_from_data']);
}


Set site name in installation profile I'm writing a custom installation profile, and most things work, except that I can't get it to change the site name.

function myprofile_install() {
  include_once DRUPAL_ROOT . '/profiles/standard/standard.install';
    standard_install();

    // ...

    variable_set('site_name', st('My Site Name'));

    // ...
}

the variable_set has no effect. So I tried adding

$GLOBALS['config']['site_name'] = "My Site Name";

at the end of the function to see if it got a different result, but it did not. Other parts of my profile work, so I know it's running. Other profiles seem to be able to use variable_set in their hook_install, so I don't think it's forbidden. Is there something else that I need to do to get the variables to "take"?

This question seems to indicate that I am doing it correctly, as do this one and this one. I've re-checed the RTFM and sample profiles to see if there's a step I'm missing, but if there is, I can't find it. The title of this question looked promising, but it turned out to be an unrelated issue.

If I add an echo statement inside of myprofile_install it indicates that the value has been set properly (and that the myprofile_install function is being read all the way through), but when I log into the site, it has the default 'site-install' name.

I am building the site via a drush command, not via the gui:

drush -y si myprofile --db-url=mysql://###:###@localhost:8080/mysite username=### pass=### dbname=###

In response to @clive's comment (thanks!), I neglected to mention that I also have

function myprofile_form_install_configure_form_alter(&$form, $form_state) {
    if (!function_exists("system_form_install_configure_form_alter")) {
        function system_form_install_configure_form_alter(&$form, $form_state) {
            $form['site_information']['site_name']['#default_value'] = 'mysite';
        }
    }
 }

in the .profile file. I assumed this code wasn't being called at all, since I wasn't using the gui form. But if the form were invisibly clobbering the values I set in the .install file, it seems like it would be setting it to mysite rather than to site-install?

The work-around that I'm currently using (because I really need to move on and accomplish other things) is to add a

drush -y vset site_name "My Site"

call to the bash script that I'm using to create the mysql database and run the installation. Not an elegant solution, (and it bypasses localization, but that's not an issue yet, since the site is currently in only one language), but it gets the job done for now so that I can get other things working.

Leaving this here in case it helps someone, but not "accepting" it, since it's a work-around, not an answer.