wget or curl executables not found. Curl activated but not working As I know so far Drush has some limitation on Windows. I need however, to get it working, and I have activated the curl module in php.ini. All you need is to uncomment the line:

extension=php_curl.dll

Now, I run phpinfo.php and it seems curl is activated, but I still get the console error:

  wget or curl executables not found.

I have restarted the Apache server several times but still no way out.

Is anyone able to help me up?

The problem was with the php.exe path in drush.bat

The solution is to properly edit it. In my case ( I use xampp ) here is the path:

@echo off
REM See http://drupal.org/node/506448 for more information.
@c:\xampp\php\php.exe "%~dp0drush.php" %*

Turn "allow_url_fopen" off in your php.ini file


Creating linkable images using Flexslider and Slideshow View I am looking to create the ability to have my slider images link to link specified in my field_link. I have tried to put the node [field_link], but it is reading as plain text. I have tried a few suggestions, but I must not be doing them right.

Below you will find the current configuration I am using.

This is how I have set up my Slideshow View:

This is how I have set up my Image Field:

This is how I have set up my Link Field:

I have always had to modify the view template for the specific display to wrap everything in a link properly. The issue is compounded even more when using Picture for responsive image variations.

The custom template changes aren't extensive, but I've not found a re-usable or GUI based method to do this with sliders.

How do you get fields: ? I only have content and feeds etc. not fields.

I have a field collection with three fields:
1: field_slideshow_link
2: field_slideshow_image
3: field_slideshow_title

I want to link the image to the link provided in 1.

so I want to rewrite the output, "Output this field as a link" setting should be [field_slideshow_link]
How do I do that in a collection?


Issues with regions using the Spaces Dashboard module I have been facing many issues trying to use the Spaces Dashboard module (part of the Spaces module).

I have setup a site with pressflow, OG, Context, Spaces, and Features; I got everything working well together.

I have been trying to implement the Spaces Dashboard feature, so group managers can manage their own group front page with an easy to use drag'n drop UI.

Through context, I have been able to create a default dashboard with some enabled blocks.
I have configured all spaces_dashboard settings and saved them in my default group space so every new group is shipped with those settings.
I have done some workaround in my template to get the context working with my Zen subtheme (based on #26 at http://drupal.org/node/633778).
I can now drag and drop blocks from my dashboard edition block to my theme regions.
I followed this tuto for setting up the UI (not really fully working with zen subtheme) : http://www.leveltendesign.com/answer/adding-customize-dashboard-magic-your-drupal-theme
I can currently drop blocks in ANY of the theme's regions even the disabled ones. I'm not sure of where does the problem comes from. The region settings are setup in the module config page at both site level and spaces level.
I cannot drop blocks in empty regions. ("Empty" meaning any region on the page that does not contains any block yet.)
If I move a block out of a region and there is no block anymore in the region I cannot move it back in the region. I'm not sure if this is a CSS, JS or module issue.
I found that by adding div for empty regions I can get some empty regions to work, but this is just a html trick and not a solution.

Content top

Finally, the 'save' button from the dashboard block doesn't save any modification to the dashboard in the current space nor in the global settings.

In case anyone still cares about this ...

You cannot drop blocks into empty regions, because they are empty. You can tell the dashboard settings to show all regions always, and then use CSS to hide the regions you dont want to be droppable ever via display none in CSS i think. Thats what I did.

The save button issue you would have to debug with Firebug and maybe a php profiler. You need to be sure the zen theme has allllll the html and css needed by the Gingko theme as lined out in that blog post above for the various JS actions to get processed correctly for the dashboard editor.

I followed the same tutorial for a Zen subtheme, spaces, dashboard and spaces_node and got it all working -- migrating to D7 looks like a pain in the future.

Please check the Homebox module. Homebox is also used on drupal.org to manage user profiles. Here is another good article about implementing dashboards: http://www.lullabot.com/articles/building-drupal-dashboard


Allow anonymous users to post content but require login/register before it is saved I have a website with a node form displayed as a block on the frontpage. This is done to make sure users get down to posting content easily and quickly.

However I'm interested in saving details of the poster so they can later be notified of comments, etc to their node. I would like for the user to then be required to login or register before their content is posted.

So from nodeform block, they click Save and then they are asked to login or register..After that content is saved.

Is there any module that does this, or what approach can I take to code my own?

Thanks

This module might be worth looking at as well: Create and Register. Below are some more details about this module, and how it works (summary from the module's project page).

  This module allows an anonymous user to create the content. After
  doing so the user must login (or registers to the site). Here are some
  more details about the process to do so:

  anonymous user creates a content.
  the user will be redirected to the login page (if you set it on the settings form) after the user finished the node creation.
  the user registers or logs in.
  the created node(s) will be assigned to the user after logging in.

anonymous users can post their answers without logging in/registering and if they want to receive notification when have new comment you can give an option to check/uncheck. Very easy.


Why isn't my new module listed in the list of modules? I am trying to build a new module, but, it is not listed in the list of modules.

This is the content of the add_new_chapter.info file:

;$Id$

name = Chapters field
description = Will create a field that will refrence a node of type chapter type
package = Online School Development
core = 7.x
files[] = add_new_chapter.module

I placed the add_new_chapter.info file in the directory "add_new_chapter" at
drupalroot/sites/all/modules/add_new_chapter.

what I expect is to see a new category ("Online School Development") in the page listing the modules but it doesn't get listed.

I tried to clear the Drupal cache, but the module didn't get listed too.

The first things I would check:

Permissions settings of the files (chmod - chown)
Remove a module to see if it has any effect

Yes, install the Devel module and set it to rebuild the theme registry on every page load.

Do not forget to turn this off on your production site. It will increase page load times for your users. Use it just for development.


How to enter text in a fieldset's summary? Using the form api to create a fieldset:

$form['fieldset'] = array(
 '#title' => 'title',
 '#type' => 'fieldset',
 '#collapsible' => TRUE,
 '#description' => 'desc',
);

Drupal will output:

<fieldset class="collapsible form-wrapper collapse-processed" id="edit-fieldset">
  <legend>

        Hide
         title

  </legend>

      asdf
      <input type="text" id="edit-testelement" name="testelement" value="" size="60" maxlength="128" class="form-text">

</fieldset>

The #title in the form array will be the  you click on to expand the fieldset.  I want to put text in the , which puts additional, non linked text beside the title.  I can't seem to do this with the form api, as #description will only put text within the fieldset that is hidden when it is closed.

What's the easiest way to do this?

See vertical_tabs_example_form_alter(), there it's written:

  Vertical tabs provide its most usable appearance when they are used to
  include a summary of the information contained in the fieldset. To do
  this, we attach additional JavaScript to handle changing the summary
  when form settings are changed.

  '#attached' => array(
    'js' => array(
      'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
    ),
  ),

In vertical_tabs_example.js it then goes on like so:

  Use the fieldset class to identify the vertical tab element. Depending
  on the checkbox status, the settings will be customized, so update the
  summary with the custom setting textfield string or a use a default
  string.

$('fieldset#edit-vertical-tabs-example', context).drupalSetSummary(function (context) {
  if ($('#edit-vertical-tabs-example-enabled', context).attr('checked')) {
    return Drupal.checkPlain($('#edit-vertical-tabs-example-custom-setting', context).val());
  }
  else {
    return Drupal.t('Using default');
  }
});

I am looking to do something similar, setting a summary in a manually output collapsible fieldset.

I looked into the collapse.js where it is defining the collapse behavior (line 56 of /misc/collapse.js).

At line 70, It looks like it is pulling the summary text from $.fn.drupalGetSummary().

I am not 100% on this (since it doesn't appear to mention in the Form API docs), but from looking at source codes, I think it might do the trick if you add to your array an entry for

'#summary' => "This is my fieldset!",

Other things you could experiment with:

'#summary callback' => 'my_module_example_fieldset_summary',
'#summary arguments' => array('bar'),

and you would probably need to define the summary callback in a module...

function my_module_example_fieldset_summary($foo){
  return t("foo is ".$foo.".");
}

or maybe you could just use something simple like:

'#summary callback' => 't',
'#summary arguments' => array('foo is bar.'),


Drupal Views : Cumulative filtering from an exposed tag cloud Sorry for this newbie question...
I hope you can help.

I need to set up a search result page, with a tag cloud as a filter.
If user select one tag (termX), the matching rows are being displayed.
He could refine his search by clicking on a second tag, to refine it even more (displaying results matching termX AND termY).

Ideally, the selected tags in the cloud, should be visually seen as "selected".

Any idea which module should I rely on ?
Do I need to go through a custom development instead ? Any hints ?

You could use views with exposed filters. You can set filter criteria to "exposed" so the user can choose which filter he would like to have. With the module "Better exposed filters" you have the possibility to format for example a select list as links.

All though the question is old. This answer might help someone else who is looking for a solution
Tagadelic filters


Saving additional node fields programmatically I have the following content type called stars with the following fields:

Title
Body
Distance (this is an added text field)

Here's what I have to save the node, but how do I add the distance field?

$node = new stdClass();
$node->type = "stars";
$node->status = 0;
$node->uid = $user->uid;
$node->title = 'This is the title';
$node->sticky = 0;
$node->language = 'en';

// Let's add standard body field
$node->body['und'][0]['format'] = 'filtered_html';
$node->body['und'][0]['value'] = 'Body info';

$node->revision = 0;

node_save($node);

You'd need to set the value for the Distance field just like you have already for the Body field. Lets assume that the name of your Distance field is field_star_distance. (To find the name of your field, check if you have the Field UI module enabled and head over to the Manage fields page for your content type)

// Your code
$node->{'field_star_distance'}[LANGUAGE_NONE][0]['value'] = 100;
// Your code

The general skeleton for setting the value for a field of an entity is:

$entity->{$field_name}[$language][$delta][$field_property] = $value

To understand the different field properties for a given field (like value in our example here), you need to look up its schema (see hook_field_schema() and see text_field_schema())

To see if $delta can be  > 1, you need to check the cardinality of the field instance.

$node->field_name[LANGUAGE_NONE][0]['value']= $name;

where 'field_name[LANGUAGE_NONE][0]['value'] 'is the name of the extra added node field.you can get this name by inspect property of browser.


How do I create a photobox for image? Can anyone please guide me on how do I create a photobox that contains image and I wanted to display that image on landing page.

I have created content type as an Image. But, I don't know how to display that image in landing page.

I am new to Drupal. Any help will be appreciated.

Thanks!

First of all: welcome to Drupal :) But then I right away have say sorry, but I think it's not really a good idea to ask people to "guide you on how to…". People here try to ask straight questions and give straight answers – if they can.

About your actual question: for displaying a specific page as your front page a.f.a.i.k. all you have to do is to go to Configuration > then Site Information > then you can adjust the Default front page setting by entering the path of any of your pages… Hope this helps…?

And last but not least I can just recommend you spend some time with some basic recources and tutorials – for example Drupal 7 – the Essentials is sheer greatness! And the Community Documentation has almost every important aspect of Drupal listed, that one could need for a start…

To get an image or any other field as content you should:

Edit your page.tlp.php
if theres only one image and if your field has a machine name 'image':
$image_url = file_create_url($node->image["und"][0]["uri"]);

  $node is where your content is stored

  "image" followed by "->" is your machine name where you get by array all values related to your field

  and final file_create_url() converts your uri to url like the method's name suggests

To output your image you can do something simple like this:

<?php
   (...)
      $image_url = file_create_url($node->image["und"][0]["uri"]);
      echo "<img src='{$image_url}' width='300' />";

   (...)
?>

You can always add a module like this one Photobox to get the job done. I am assuming that your are using D7. please precise your Drupal's version next time :)


Remove "read more" when there is no more text to read I have just set up a new website with Drupal 8. I created a new content with a regular HTML that contains basic text. I promoted it to homepage, I see a "read more" link. But there is no "more" to read.

How can I remove "Read more" link if there is no more content to read?

I found some modules for Drupal 7 but I am following a certain solution for this general problem.

And also I am curious; isn't it obvious that there shouldn't be a "read more" link when there is no more content? Is it a bug or something?

Neither of the other answers actually addresses the question, which is how to turn off "read more" selectively depending on whether there is more to read or not.

The standard read more link, as the comments in NodeViewBuilder say, is always displayed on a teaser by default because there is no (easy) way to know how the teaser content differs from the full view. Your content type might have several other text fields apart from the body which are only shown on the full page view.

However, it should be possible to implement a custom "read more" link that has the behaviour you seem to be asking for. I don't think anyone has implemented one yet, but the most fruitful approach would be a modest extension of the "summary or trimmed" field formatter, although you could probably also do something in a preprocess hook in your theme.

Edit: A demonstration module is up on github now. It's not perfect and I would like to refactor it and possibly make it more general-purpose but it works for the simplest case.

To remove the 'Read more' on Drupal 8 click on the following:-

Strucure, Views, Frontpage - edit, change 'Teaser' on dropdown to 'Default'.

Click 'save' = Job done :)

Please note there is no 'Read more module' in Drupal 8 as yet. Drupal 7 has one.


Implementing Google CSE Results Code I'm trying to implement the Google CSE Search Results code on a page that I created called search-results. When I implement the code using CKEditor (PHP mode) and save the page, the code does not show up when the page is rendered?

I was able to enter the Search box code no problem but I cannot seem to get the search results code to load on a page? I created a static html page and it works fine but will not work when I create the page in CKEditor. I also tried creating a block but this did not work?

How can I get the Google CSE Search results code snippet in a Drupal page? I'm not interested in using any of the Drupal modules for CSE as I don't like the way they render the results.

You should be using Google Custom Search Engine Module instead of embedding the code. Using this module would give you better integration option.

Additional Info: Avoid using PHP Filter as its creates security risk.


How can I change the default system message shown on form submission I've created a business card request form as an EntityForm and am scratching my head trying to figure out where in the module i can find the line - ( " The submission has been saved " ) .

This message displays after every form submission/edit/save, and I would like to get rid of it but cant figure out where its coming from !   :)

That message comes from entityform_edit_form_submit

You could try setting the translatable text string to an empty string in settings.php

$conf['locale_custom_strings_en'][''] = array(
  'The submission has been saved' => ''
);

Or else look into another way to alter drupal_set_message text.

Click edit and choose tab form overrides and Submission Confirmation Text. write your text.


Translate view header I add a simple text as view header but it is not exists in translatable text in admin/config/regional/translate.

In Drupal 7 we could even translate unformulated views header and footer with the following steps:

Go to admin/config/regional/i18n/strings
Check "full HTML" in "Translatable text formats" section
Go to admin/config/regional/translate/i18n_string
Click on Refresh strings

Has this feature been removed form Drupal 8? (I don't think so.)
How can I translate view header and footer simple text?

Enable "Configuration Translation" core module
Go to your view edit and you will see a "Translate view" tab
You'll find your language in the list there. Then click on "Edit"
next to the language
Expand panels and you will find your header text under the "Header"
panel

You can easy translate view header and footer text using the {% trans %} Twig tag in Drupal 8
Example:

{% trans %}
  Text for translate
{% endtrans %}

And after that you will be able find text in user interface translation "admin/config/regional/translate"


When creating content: Force the checkbox "Provide a menu link" to be checked by default When creating content, I would like to force the checkbox "Provide a menu link" to be checked by default.

What I'm really trying to do:

I created a new content type
I used node_add to get the form associated to my content type and render it into my template.
In my module I used the hook_form_alter to hide some fields of my form.

But when the user submit the form and the node is created, there is no menu link created by default.

I looked everywhere for this! The Menu Force module does this:

  This module enables you to make the Menu Settings required on specific content types.

After installing a "Make the Menu Settings mandatory for this content type" tick box becomes available on the settings for each content type.

Simple install https://www.drupal.org/project/default_menu_link and there you go.

There is a similar module called Menu Force that does just that. Whereas Menu Force mandates menu assignment, Default Menu Link merely changes the status of "Provide a Menu Link" to true. The user can still create content and choose to un-check this box. However, the default state (on node creation) will be true, and as long as you've set a default menu parent item, all content will be filed under that parent.


How to use the same URL alias for all translations of a node? I want to use the same URL alias for all nodes regardless of language.

On my site, the primary language is English.  Translation is enabled for nodes of type basic page.

At /admin/config/regional/content-language, content translation is enabled for the Title and Body fields.

With this configuration, on the node edit page, it shows "URL alias (all languages").  I set a URL alias manually for each English node.

However, when I add a translation in another language, even though I see my alias on the translation edit page, this alias is not applied for that language.  In other words, if the alias is myfolder/mypage in English, if I go to the Japanese translation at /ja/myfolder/mypage, I get a "page not found" error. Instead, the page is available at /node/5 or whatever the NID is.  But, on the "edit node" page for the Japanese translation, it does show the English alias with the text "all languages."

Workaround

I can go to /admin/config/regional/content-language and enable translation of URL alias and then manually set each additional language alias to the English alias, but this seems like a lot of extra work to keep the same alias.

As pointed out by @Rockabelly, this is a bug with Drupal core.  For now, there is a patch to fix the issue.

The Neutral Paths module should work in this situation.  From the project page:

  A module for multi-language web sites, allowing users to access
  content in languages other than the current one by using path aliases.


How to setup year increment? I use Date module in D7, and I create new field "decade" (field type is Date).

Also in the settings, I add a custom input format 'Y' (only years). There is increment for time (+/-30 minutes), but I need increments for years (+/- 10 year). In node add form I need selectbox with values like:

1700
1710
1720
1730
....
now
How can I do that?

You shouldn't use a date format for your field

I advice you to use CCK module (7.x-2.x-dev)

  some miscellaneous helpers to do things that core will not do, like
  maintain the PHP code snippets some fields may have been using to
  define allowed values (partially working)

With this module, you define these kind of allowed values from a php code


How do I construct the JSON data with session info for creating node? I am using Drupal 7 and the Services module 7.x-3.2. I am using Postman for Chrome (a http client) to test the API.

What I want to do is log in a user and create a node with the user using the Drupal service API.

I logged in the user with JSON POST request to http://example.com/api/user/login.

I successfully got the JSON result.

{
    "sessid": "KrZjlcY3rFr8v6iLoskcVQN9DmDWsg5yZqIjBeydEBY",
    "session_name": "SESS9fe39db36ccd7afd64e034fefa0129e1",
    "user": {
        "uid": "31",
        "name": "test_user",
        "mail": "services_user_2@example.com",
        "theme": "",
        "signature": "",
        "signature_format": "filtered_html",
        "created": "1352985941",
        "access": "1352991170",
        "login": 1352991510,
        "status": "1",
        "timezone": "",
        "language": "",
        "picture": null,
        "init": "services_user_2@example.com",
        "data": false,
        "roles": {
            "2": "authenticated user"
        },
        "rdf_mapping": {
            "rdftype": [
                "sioc:UserAccount"
            ],
            "name": {
                "predicates": [
                    "foaf:name"
                ]
            },
            "homepage": {
                "predicates": [
                    "foaf:page"
                ],
                "type": "rel"
            }
        }
    }
}

Then I tried to create an article via the API by sending the JSON POST request. (The user has the permission to create Article nodes.)

I got a 401 Unauthorized response.

I guess I need to include the session cookie information to send the POST request, to create a node.

I have the session information previously returned.

"sessid": "KrZjlcY3rFr8v6iLoskcVQN9DmDWsg5yZqIjBeydEBY",
"session_name": "SESS9fe39db36ccd7afd64e034fefa0129e1",

How can I utilize it to make a successful JSON POST request for creating a node?

{
   "title": "Just another drupal Post",
   "type": "Article"
}

notice no comma after the type:article tag so that your json works.

You need to set cookie="sessionname=sessionid" value in headers, where sessionname comes from the endpoint/user/login URL.


Sort result by taxonomy term weight $query = db_select('node', 'n');
   $query->join('field_data_taxonomy_catalog', 'tc', 'n.nid = tc.entity_id');
   $query->leftjoin('field_data_field_chip', 'fdc', 'n.nid = fdc.entity_id');

   $query->fields('tc',array('taxonomy_catalog_tid'));
   $query->fields('fdc',array('field_chip_tid'));

   $query->fields('n',array('nid'));

   $query->condition('tc.taxonomy_catalog_tid',$get_tid,'=');

   $query->orderby("fdc.field_chip_tid","ASC"); //I Want to sort the resultset on the basis of weight instead of the term Id.

   $result = $query->execute()->fetchAll()

I need to sort the result on field_data_field_chip weight instead of the term Id. I am new to Drupal and don't know how to fetch the weight of the taxonomy terms.

The weight column in the taxonomy_term_data table contains the information you need.

You can join it in to your current query via taxonomy_term_data.tid.

https://www.drupal.org/docs/7/api/database-api/dynamic-queries/ordering

See drupal standard documentations, it may help you


How can I make kint() load faster when debugging twig templates? I've seen quite a bit of discussion about how kint() from the Devel module is difficult to work with because it maxes out PHP memory limits and makes the browser drag. I've heard some thoughts on improving its speed by limiting the number of levels. For example, in settings.php, you can do the following:

require_once DRUPAL_ROOT . '/modules/contrib/devel/kint/kint/Kint.class.php';
Kint::$maxLevels = 3;

Any other ways to improve the speed of kint()?

There are two other ways other users have mentioned for setting the max output levels in addition to the settings.php method mentioned in the question, plus a couple other ideas below:

Create a /modules/contrib/devel/kint/kint/config.php file and add / modify the line $_kintSettings['maxLevels'] = 3; (by @mdrummond on Slack)
In a preprocess function, add the following: (by @thpoul on Slack)

kint_require();
Kint::$maxLevels = 3;

Be sure to never click the + sign, that shows the entire tree. Click the block instead. You can click the right arrow to open the output in a new window for easier viewing (like when the output is in a block). (by @cwightrun on Slack)
Instead of using kint(), create a preprocess function and use a debugger to explore the variables. (by @danny_englander on Slack)
Pass kint() a specific variable instead of making it roll through the whole tree (by @No Sssweat below).
If you just need to know what variables exist, you can just view the keys by doing a {% for key, value in _context  %} loop (by @mortendk below)

Adding $GLOBALS['_kint_settings']['maxLevels'] = 4; in your settings.local.php should do the trick. Feel free to change the number of levels here.


Post method trow an Preflight not successful response Im working with Drupal 8 and Angular.

I want to create a content from angular.

I have the Get method working.

The problem is with the Post method, I don't know how to configure it.

With the Rest Ui module, i have this configuration:

And in the services.yml file I have this one:

  cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: []
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: []
    # Configure requests allowed from specific origins.
    allowedOrigins: ['*']
    # Sets the Access-Control-Expose-Headers header.
    exposedHeaders: false
    # Sets the Access-Control-Max-Age header.
    maxAge: false
    # Sets the Access-Control-Allow-Credentials header.
    supportsCredentials: false

It works fine for the Get method, but for the POST, it gives me this error:

  XMLHttpRequest cannot load http://drupal.dd:8083/entity/node.
  Preflight response is not successful task.service.ts:92

The task.service.ts is from my Angular app.

Questions:

1) Is the problem from Drupal configuration or from angular? (if is from angular, i will move the post. )

2)Wich on is the correct way to configure Post Method in Drupal?

Extra info from the method

This is the right cors.config configuration:

 cors.config:
        enabled: true
        # Specify allowed headers, like 'x-allowed-header'.
        allowedHeaders: ['*']
        # Specify allowed request methods, specify ['*'] to allow all possible ones.
        allowedMethods: ['*']
        # Configure requests allowed from specific origins.
        allowedOrigins: ['*']

resources:
    entity:node:
        GET:
            supported_formats:
                  - hal_json
            supported_auth:
                  - basic_auth - cookie
        POST:
             supported_formats:
                 - hal_json supported_auth:
                - basic_auth - cookie

Curl request

curl --include \ --request POST \ --user klausi:secret \ --header 'Content-type: application/hal+json' \ --header 'X-CSRF-Token: <obtained from http://example.com/rest/session/token>' \ http://example.com/entity/node?_format=hal_json \ --data-binary '{"_links":{"type":{"href":"http://example.com/rest/type/node/article"}},"title":[{"value":"Example node title"}],"type":[{"target_id":"article"}]}'

jQuery Request

function getCsrfToken(callback) { jQuery .get(Drupal.url('rest/session/token')) .done(function (data) { var csrfToken = data; callback(csrfToken); }); } function postNode(csrfToken, node) { jQuery.ajax({ url: 'http://example.com/entity/node?_format=hal_json', method: 'POST', headers: { 'Content-Type': 'application/hal+json', 'X-CSRF-Token': csrfToken }, data: JSON.stringify(node), success: function (node) { console.log(node); } }); } var newNode = { _links: { type: { href: 'http://example.com/rest/type/node/article' } }, type: { target_id: 'article' }, title: { value: 'Example node title' } }; getCsrfToken(function (csrfToken) { postNode(csrfToken, newNode); });

Note: If using Basic Auth You need to set the "Authorization" header Here is an example:

function formatBasicAuth(userName, password) {

var basicAuthCredential = userName + ":" + password;
  var bace64 =  btoa(basicAuthCredential);
  return 'Basic ' + bace64;
}

// then in your post
var basic = formatBasicAuth('userName', 'password');
...

'X-CSRF-Token': csrfToken,
'Authorization': basic,


Creating Views based on html source Is it possible to create a view from third-party source that includes html, js and css?

Example: http://www.addyosmani.com/resources/shinetime/

I want to create a view of the example shown in the link and display it as a block on my site.
Is there an automated process for doing this or I would have to do it manually? If manually then how? Thank you

If all you want to do is display that in/on your website, include it in an iframe, eg, create a block that just has:

<iframe src="http://www.addyosmani.com/resources/shinetime/"></iframe>

in it.

Now, if you are wanting to create a View, eg http://drupal.org/project/views, then you need to give some more specifics of what you are wanting to do.

In my opinion, you can create a basic page and code the PHP + HTML code. (You must enable PHP filter in module page)

For the php code, you create a SQL statement to get the data that you want, for example, db_query in Drupal


Loading default image from a node field in page.html.twig I want to print the default image of a node field into the page.html.twig template file in Drupal 8. On doing my research the easiest approach I could find was

{% if node.field_image.entity %}

{% endif %}

This works if I load an image in the field but not otherwise with the default image of the image field. I want to use the above code to print the default image that I pick for this image field. Currently the above method gives  for the default image

How can I access the uri value of the default image in the src of the image tag above. Is there any other way to print the default image of a node in the page.htm.twig preferably from within the template layer as I don't have any experience with preprocess functions etc.? My objective is to have a static image which is the same throughout the content type.

Here's one approach, using a helper method. It assumes you have access to the loaded node entity ($entity), and would like to get either the set, or default image for a given image field. I've also left comments and links that explain why Drupal::service('entity.repository') is being used, and how I discovered the way in which the Image module loads the default image settings.

    /**
 * Get the set or default image uri for a file image field (if either
 * exist).
 * @param $entity
 * @param $fieldName
 * @return null|string
 */
function get_image_uri($entity, $fieldName) {
  $image_uri = NULL;
  if( $entity->hasField($fieldName) ) {
    try {
      $field = $entity->{$fieldName}; //Try loading from field values first.
      if ($field && $field->target_id) {
        $file = File::load($field->target_id);
        if ($file) {
          $image_uri = $file->getFileUri();
        }
      }
    } catch (\Exception $e) {
      \Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
    }

    // If a set value above wasn't found, try the default image.
    if (is_null($image_uri)) {
      try {
        $field = $entity->get($fieldName); // Loading from field definition
        if ($field) {
          // From the image module /core/modules/image/ImageFormatterBase.php
          // $default_image = $test->fieldDefinition->getFieldStorageDefinition()->getSetting('default_image');
          $default_image = $field->getSetting('default_image');
          if ($default_image && $default_image['uuid']) {
            // $defaultImageFile = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']));
            // See https://www.drupal.org/node/2549139  entityManager is deprecated.
            // Use entity.repository instead.
            $entityrepository = Drupal::service('entity.repository');
            $defaultImageFile = $entityrepository->loadEntityByUuid('file', $default_image['uuid']);
            if($defaultImageFile) {
              $image_uri = $defaultImageFile->getFileUri();
            }
          }
        }
      } catch (\Exception $e) {
        \Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
      }
    }
  }

  return $image_uri;
}

Drupal 8 preprocessor

My template_preprocess_page() implementation to get theme path in page.html.twig:

<?php
/**
 * Implements template_preprocess_page().
 */
function THEME_preprocess_page(&$variables) {
  $theme = \Drupal::theme()->getActiveTheme()->getName();
  $variables['theme_path'] = drupal_get_path('theme', $theme);
}
?>

...and in my page.html.twig file:

<img src="/{{ theme_path }}/images/image.jpg" class="img-responsive" alt=""/>


How to redirect to the webform node when it just created? I followed the webform cookbook and created a custom module to "automatically create a Webform node when adding a Webform". Moreover, I need to redirect to the Webform Node at the same time, so I add the "RedirectResponse" code, but it didn't work. Following is my code:

function webform_chshb_webform_insert(\Drupal\webform\WebformInterface $webform) {
    $webformnode = \Drupal\node\entity\Node::create([
        'type' => 'webform',
        'title' => $webform->label(),
        'webform' => ['target_id' => $webform->id()],
    ]);
    $webformnode->save();
    drupal_set_message(t('Node %label created.', ['%label' => $webformnode->label()]));

    $nodeid = $webformnode->id();
    $response = new RedirectResponse("/node/$nodeid/edit");
    $response->send();
}

Thank you.

try it with return

function webform_chshb_webform_insert(\Drupal\webform\WebformInterface $webform) {
    $webformnode = \Drupal\node\entity\Node::create([
        'type' => 'webform',
        'title' => $webform->label(),
        'webform' => ['target_id' => $webform->id()],
    ]);
    $webformnode->save();
    drupal_set_message(t('Node %label created.', ['%label' => $webformnode->label()]));

    $nodeid = $webformnode->id();
    $response = new RedirectResponse("/node/$nodeid/edit");
    $response->send();
    return;
}


Changing Drupal theme completely I am a newbie, I am in the middle of the website which was already created using the bartik theme and I want to change the theme completely like the way Main-menu looks and adding the slideshow in the middle of the page. I really don't understand how to do it. Any suggestions? Thanks.

I would recommend starting with the "Stark" Drupal theme.  It's the minimal theme,  easier to customize.

You are also going to need to read about some basic Drupal concepts.  Views, blocks, page templating.

Your question is far too "big" to be answered in this forum.  You will have to read the documentation at drupal.org

The short answer is to make changes to the CSS files of you theme. Drupal Themes are more of a developer friendly environment than a graphic design environment like Wordpress themes.

Drupal "best practices" procedure is to work with a base theme and an overriding subtheme. The Zen theme is one of the most popular ways to do that. The reason to work this way is that you can update the theme without over-writing your subtheme, and hopefully the subtheme changes would be minimal.

Probably the easiest way to install a slideshow is with the Field Slideshow module. You need to add an image field to one of your content types, upload the images, and Field Slideshow instantly makes a slideshow, which you can put on any page with the block system. Well, not quite instantly, you need to grab a slideshow jquery library, but you don't have to use the amazing but complex Views module.


How to mark calendar days between two dates? I added two cck for start date and end date. I want to mark the dates on calendar.

If I select the start date and end date in single field by enabling requires to date option it works fine.

But I have a different date field for end date.How to do it?

I did this with the same date field and enabled the to date option.


How to prevent users with negative balance of user points from viewing nodes? I have a rule that deducts 1 point from users viewing a node, however the problem is that users with a negative balance can still view a node. So I would want to prevent this.

I'm using Drupal 7 with modules Rules and User Points.

Any suggestions?

Your question actually contains 2 challenges:

Which Rules Event to use?
Check the current balance of user points of the user?

Read on for an answer to address each of those challenges.

1. Rules Event to use

If you'd use Rules event node_view, then you're too late, because the node is already being viewed (which is exactly what you want to prevent). Instead you need to use (System) event "Drupal is initializing" (= init), which is actually BEFORE the node is actually being viewed.

2. Check current balance of user points

However, you also want to disallow viewing nodes for users who have a negative user points balance. The challenge with that is that there is no out-of-the-box Rules Condition to check that balance.

Have a look at this Rules example (in Rules export format):

{ "rules_stop_node_access_for_user_with_negative_points" : {
    "LABEL" : "Disallow node/* access for a user with negative points",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "0" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have insufficient points (you only have [total-points:value] points ...)." } },
              { "redirect" : { "url" : "no_access" } }
            ]
          }
        ]
      }
    ]
  }
}

The Rules Condition added here, is to only perform the Rules Action for attempts to browse a path like node/* (adapt to what fits for your case).

This rule retrieves, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If it is negative, it will display an appropriate message starting with "You have insufficient points ...", and it redirects to a relative path like no_access (adapt to what fits for it).

This rule uses the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module.

The clue to make this rule work is the very first Rules Action "Load user points of a user". Refer to my answer to "How to access current amount of earned userpoints in a Rules Condition?" for more details on this.

Add rule for node_view with custom php as condition. In condition check for negative points. If negative points, condition returns true. Execute custom php with drupal_access_denied()


Add active class to link  using l() Seems so elementary but how does one get the active state onto the
 of a link when manually using the l() function?

<?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?>

The above of course outputs the link in a list item with an active class on the link if the page is current, but how do I get that class onto the
?

You can't. The l() function is only responsible for rendering the HTML link, it has no concept of the tag it's being wrapped in (or indeed if it's even being wrapped in another tag at all).

The simple answer based on your question is to add it manually:

<?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?>

$output = '';

$submit_links = array();

$outp = array('0'=>10, '1'=>'20');

foreach ($outp as $key => $value) {
  // if you have dynamic links
  $submit_links[] = l(t('LINK TEXT HERE'), 'node/'. $value, array('attributes' => array('target'=>'_blank', 'class' => 'menu',), 'html' => TRUE));
}

$output = theme('item_list', array('items' => $submit_links));

return $output;


drupal commerce browsable catalog I am finding some troubles how Views works with taxonomy terms. I hope you can help me. :-)

I am building an e-commerce site with Drupal Commerce since it has all features I need for my project requirements but I don't know how I can list terms and nodes belong to concrete taxonomy on Views.

I have a product hierarchy taxonomy with all the site product categories. I use Taxonomy menu in order to show this taxonomy in a menu block allowing the user to select any term. A product display node only can be referenced to a sheet term on the taxonomy tree.

I want to use Views by listing as terms as nodes, if the user click on a non-sheet term on taxonomy menu, the view should show the subterms from clicked term. But in the other hand, if the user clicks in a sheet term then the view should show nodes referenced to the clicked term.

For instance,

Let's imagine I have the next taxonomy menu:

products

term1

term1.1
term1.2

node1
node2

term1.3

term2

node3
node4

If the user clicks on term1 term the view should list term1.1, term1.2 and term1.3 but if he/she clicks on term1.2 it should list node1 and node2.

How can I do this on Views? How can I list two different types of entities depending what term is clicked?

Thanks in advance!!

I doubt this is possible in views but you could try a combination of menu block and display suite modules, if you can't custom-code it.

You might also need a module which creates fly-out menus. Display suite is capable of pulling in various entities into your display, and there is a great set of tutorials available on Youtube that will show you how to achieve this.

This site is built with Drupal commerce, display suite and menu blocks; although I didn't add nodes to my menu blocks, it is possible.

I found a solution here. I only had to adapt a little but it worked for me! :-)

See you!


Drupal Language Switcher menu item I am using D 7.28 with Boostrap theme (https://www.drupal.org/project/bootstrap).
I am using the theme's 'Main menu' to display my links. The language switcher works well for me (changing homepage, Hero banner block and navigation into the appropriate language).

I would like to move the language switcher to the 'Main menu' and display it as an item only showing the inactive language.

Could anyone please provide instructions how to do it?

I have a small module hosted on GitHub that does just that:
Locale Menu
From the README file:

Overview
Alters the href of any menu item whose title is "English" or "Español" to point to the translated version of the current menu item. If no translation exists for the current menu item, the link will point to the translated version of the homepage.

You'll need to tweak Lines 6, 15, and (especially) 21 of the localemenu.module file to match the name and language code of your language.

I have created a module that provides a language switcher dropdown for Bootstrap-enabled themes. It is available as a sandbox module here: https://www.drupal.org/sandbox/pascalanimateur/2493639


How to programmatically insert and update Field Collection values? I would like to insert and update Field Collection values. I'm using Drupal 8 with field_collection 8.x-1.0-alpha1.

Setup

I have created a new content type test_content_type with the following fields:

Title
Body
…
Test Field Collection

Machine name: field_test_field_collection
Type: field collection

The field collection field_test_field_collection has only one field:

Example Text

Machine name: field_text
Type: text

The Problem

I also created a node with values, for instance Lorem Ipsum as field_text.value, but I don't know how to read and define the value programmatically. I tried the following, which updates body but doesn't update field_text:

<?php

namespace Drupal\my_module\Controller;

use Drupal;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityStorageInterface;

class FieldCollectionTestController extends ControllerBase {
    /**
     * @return array
     */
    public function content() {
        $nodeId = 1402;

        /** @var EntityStorageInterface $entityStorage */
        $entityStorage = Drupal::entityTypeManager()->getStorage('node');
        $node = $entityStorage->load($nodeId);

        // Dump.
        {
            ob_start();
            var_dump($node->field_test_field_collection->field_text);
            $dump = ob_get_clean();
        }

        // Update node and field collection.
        {
            $exampleText = "Updated at " . time();

            $node->body = $exampleText;
            $node->field_test_field_collection->field_text = $exampleText;

            $node->save();
        }

        $response = [
            '#theme' => 'item_list',
            '#title' => 'Dumps',
            '#items' => [
                [
                    '#type' => 'markup',
                    '#markup' => $dump,
                ],
            ],
        ];

        return $response;
    }
}

The value of $dump is null.

Question

How do you insert, update and delete Field Collections in Drupal 8?

The following snippet (compatible with field_collection 8.x-1.0-alpha1) reuses an existing FieldCollectionItem or creates a new one on demand. The last few lines show how to modify fields inside the FieldCollectionItem.

If one has a field collection with a different name, then it should be enough to replace all occurrences of field_test_field_collection with the custom field collection's machine name.

<?php

// […]

$nodeId = 123;

/** @var EntityStorageInterface $entityStorage */
$entityStorage = Drupal::entityTypeManager()->getStorage('node');

$node = $entityStorage->load($nodeId);
$node->body = 'Body Update: ' . date('c');

/** @var Drupal\Core\Field\FieldItemList $fieldItemList */
$fieldItemList = $node->field_test_field_collection;

// Reuse existing Field Collection.
if (count($fieldItemList))
{
    /** @var \Drupal\field_collection\Plugin\Field\FieldType\FieldCollection $fieldCollection */
    $fieldCollection = $fieldItemList[0];
    $fieldCollectionItem = FieldCollectionItem::load($fieldCollection->value);
}

// Create new Field Collection.
else
{
    $fieldCollectionItem = FieldCollectionItem::create([
        'field_name' => 'field_test_field_collection',
    ]);

    $fieldCollectionItem->setHostEntity($node);

    $node->field_test_field_collection[] = [
        'field_collection_item' => $fieldCollectionItem,
    ];
}

$fieldCollectionItem->set('field_text', 'Last Update: ' . date('c'));

$node->save();

Deleting an existing collection is as simple as: fieldCollectionItem->delete();

Please have a look at the source code of the unit test class Drupal\field_collection\Tests\FieldCollectionBasicTestCase for more information.

Check the below link,

https://www.drupal.org/node/2683787

That may help you in your case.


What is the best approach to write hooks? I had to use some hook functions on almost every project I worked, right now I am working on a project ( basically to collect donations and maintain organizations list ) where I need to write lots of custom code, at first I started to write all the code in theme i am developing, later I realized that its not going good with all the functions in theme because some hooks need to be written in modules so now some of the code is written in module and some is in theme which breaks the functionality when switch theme or with admin theme.

So I am thinking to write all the code again but not sure what is the best approach to write custom code in a drupal project.

if all code goes in custom module some of the theme sections needs to be rebuild and I didnt find any proper article on net on this

I think your question is more of in-general type . Please specify for what all purpose you need to use hooks .
I think this might be helpful for you : http://www.stephanemartinw.com/articles/25-theme-drupal-hooks-templates-functions

Thanks


Weird permissions problems for sites/default/files I have this weird problem related to permissions on a VPS where I run 2 Drupal 7 websites.

I have an old site, which was migrated over several hosting providers and VPS setups. I also have a freshly installed website.

The new one works perfectly and I can set it to aggregate and compress CSS files plus JavaScript files. All is smooth and without errors.

The old one... each time I set it to do this, It gives me errors such as:

The specified file temporary://filepIYgt4 could not be copied to public://js/js_IaQHoIpFqzgiVl19GZEd2HEQg6iqLy6d1_xllBmEbqE.js.
The specified file temporary://fileTbJH3r could not be copied to public://css /css_Lnc8IK4qbp4ueX76wBYIBGAqVihLWtCHHNP7WBSphEM.css.

Both websites are configured the same way. The difference though seems to be in the permissions set for the sites/default/files folder. The new website (which works fine) has the permissions set to 0777 and the group and owner are set to apache.

The old website (which generates errors) has the permissions set to 0777, the group to psacln and the owner is the user I'm using to login to the website via SSH or FTP.

If I change the owner and the group to apache for the old website, things still don't work. I get warnings like these:

Warning: realpath(): SAFE MODE Restriction in effect. The script whose uid is 10002 is not allowed to access /var/www/vhosts/.../httpdocs/sites/default/files/css owned by uid 48 in DrupalLocalStreamWrapper->getLocalPath()

Warning: realpath(): SAFE MODE Restriction in effect. The script whose uid is 10002 is not allowed to access /var/www/vhosts/.../httpdocs/sites/default/files/js owned by uid 48 in DrupalLocalStreamWrapper->getLocalPath()

Warning: realpath(): SAFE MODE Restriction in effect. The script whose uid is 10002 is not allowed to access /var/www/vhosts/.../httpdocs/sites/default/files/ctools owned by uid 48 in DrupalLocalStreamWrapper->getLocalPath()

As you can see, Drupal still can't write to the same troublesome folder. :(

What am I doing wrong? Any advice how to fix this?

I managed to figure this out with the help of the company providing the hosting. So, I'm sharing the solution, in case others have similar issues.

The solution is to make PHP run as a "FastCGI application", instead of an "Apache module". This way, Drupal uses the same user I use to upload files via FTP, when it creates files, etc.

The new website worked fine because I used the one-click installer offered by the hosting provider, which ran everything using the apache user. The old website did not do this.

This solution & problem should apply to all hosting providers using Plesk.

What worked for me was to navigate first to the user roles:
People --> Permissions --> Roles

and then select the 'edit permissions' link for the particular role I wanted to edit.

So:
Going straight to the Permission page where all roles are listed in columns did not work.
But opening the permission page only for the particular role worked.

Cheers,

Pimmy


How to remove stylesheets only for anonymous users? I am trying to remove all unnecessary/unused stylesheets for anonymous visitors to get better performance and a clean <head> section. This works fine by listing them inside mytheme.info.yml:
stylesheets-remove:
  - path/to/stylesheet.css
  - path/to/another/stylesheet.css
  - core/modules/system/css/components/hidden.module.css

However, the third entry in this example breaks the styling of the toolbar - which is only visible to the admin. Is it possible to programatically tell Drupal which stylesheets to remove only for anonymous visitors? I appreciate your help!

Having tried to do this myself before, this is probably not a route you want to go down.  This approach becomes harder to maintain as you install more modules (different modules can inject CSS on different paths), and often can turn into a maintenance nightmare.
Drupal can aggregate CSS files out of the box; this is often all you need to improve performance dramatically.
To turn on the basic aggregation, you can check Aggregate CSS files at /admin/config/development/performance.
To do something more complicated, try using the Advagg module. Configuring this module can be complex but it allows you to do more specific aggregation, CSS minification, and so on.

you can use hook bellow (check for the right path)
function MYMODULE_page_attachments_alter(array &$attachments) {
  if(\Drupal::currentUser()->isAnonymous()) {
    unset($attachments['#attached']['library']['core/modules/system/css/components/hidden.module.cs']);
  }
}


How do I send data using JSON as output format? There are separate web forms created on the basis of the Webform module (Drupal 7), sending by default goes to the required e-mail. Everything is within the module.

In addition, there was a need to send the data of the webform application (field) to various CRM (custom) based on JSON.

Request format

{
    "aCode": "zzz",
    "importdata": {
        "id": "zzz",
        "user_data": {
            "name": "zzz",
        },
        "contact": {
            "phone": "zzz",
        }
    }
}

How do I properly implement this functionality?

Process:

External url for accepting JSON lead requests (example): http://example-server.com:8083/api/submit

After the webform has been filled in, it is necessary to automatically send the field data in the raw postdata format to the external CRM with the JSON request format specified above in the code.

You will need to write a custom module that will select data from the webform tables in the database, encode your response and then call the URL

$crmurl = 'http://www.crmdomain.com/api/datafromdrupal';

if (isset($response)) {
  $json_response = drupal_json_encode($response); /* Pure json encoding */

  $options = array(
             'method' => 'POST',
             'data' => $json_response,
             'timeout' => 15,
             'headers' => array('Content-Type' => 'application/x-www-form-
             urlencoded'),);
  $result = drupal_http_request($crmurl, $options);
}


How to use Views Photos Grid module with custom minimal theme I use Views Photos Grid module and it shows the results correctly with Stark theme.
However, it shows all the images stacked in only place in my custom theme.
I do include modules css and js files:

<link rel="stylesheet" href="/modules/views_photo_grid/css/views-photo-grid.css">

I also render the expected divs:

...more views-photo-grid-item divs are here...

Java script console shows no errors.
I've checked in debugger that the main JS function (function ($, Drupal, drupalSettings) is called but none of the other JS functions is called.
Could this be the cause?

Issue was missing JS includes.
The working set is:

  <script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","currentPath":"screenshots","currentPathIsAdmin":false,"isFront":false,"currentLanguage":"en"},"pluralDelimiter":"\u0003","google_analytics":{"trackOutbound":true,"trackMailto":true,"trackDownload":true,"trackDownloadExtensions":"7z|aac|arc|arj|asf|asx|avi|bin|csv|doc(x|m)?|dot(x|m)?|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt(x|m)?|pot(x|m)?|pps(x|m)?|ppam|sld(x|m)?|thmx|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls(x|m|b)?|xlt(x|m)|xlam|xml|z|zip"},"viewsPhotoGrid":{"gridPadding":"1"},"user":{"uid":0,"permissionsHash":"797a0805952a191ed3acd8cc0feee5a8b53895cab4446ce069563dbdd87139da"}}</script>

  <script src="/core/assets/vendor/domready/ready.min.js?v=1.0.8"></script>
  <script src="//code.jquery.com/jquery-3.3.1.min.js?v=3.2.1"></script>
  <script src="/core/misc/drupalSettingsLoader.js?v=8.6.3"></script>
  <script src="/core/misc/drupal.js?v=8.6.3"></script>
  <script src="/core/misc/drupal.init.js?v=8.6.3"></script>
  <script src="/modules/views_photo_grid/js/views-photo-grid.js"></script>

It doesn't work without the first messy line with data-drupal-selector. I wish I knew was is this good for...


How do I store URL parameter in user registration field? I'm trying to store a url variable into a field on the user registration page.

http://domain.com/user/register?aid=74

Can I use javascript to pull that variable and store it in one of the input fields?

Using hook_form_alter you can set the default value of your field to be this query parameter.

function MY_MODULE_form_alter(&$form) {
  $q = drupal_get_query_parameters();
  $form['parameter_field']['default value'] = check_plain($q['aid']);
}


Create a webform which creates a user account I'm looking to create a user registration form on a Drupal 8 site that has multiple clearly defined sections (possibly on separate pages).

I've explored doing this with the standard Drupal registration form building tools in account settings but it doesn't seem possible to create a form with such a layout using just account settings (correct me if I'm wrong).

The webform module allows me to create a form which is styled exactly how I want but I'm not sure how to create a user account with data entered into a webform. Is there another module I can use for this or can I do it from within the webform module?

There is a module for that.

Forms Steps provides an UI to create forms workflows using forms modes. It creates quick and configurable multisteps forms.

As stated, if possible, you'll have a much easier time using the standard Drupal registration process, rather than trying to create a webform and sync fields with the registration form.

Depending on your site needs / restrictions, you could always "fake" a multi-step form with a custom template. If all of the form fields print out on the same page, you can use the template to split those fields into "sections" and then use JS to let the user step through the full process while staying on the same page.

A great example is provided here - https://www.w3schools.com/howto/howto_js_form_steps.asp - which also includes form validation on the form step buttons, so that users can't skip a required field on Step 1 before moving on to Step 2.


How to theme Panels properly? I am using Page Manager and Panels, providing custom node panels with selection rules by type (e.g. one panel variant for article-, one panel variant for blog-content type). This works smooth so far, styling is also neat. But, how can I get more power over the rendering of elements?

There are multiple ways to render specific elements: adding fields, using token, using a custom view only rendering specific fields, using rendered node entity with view mode. using custom panel content with placeholders etc.

What is the best approach here? It would be great to have the ability to add a custom (something) pane element that can be styled in a *.tpl.php.

My current approach would be using display suite, creating view modes for different parts / panel regions and using theme hook suggestions for adding custom node.tpl.php for each view mode. It would not need to invoke views, which is pretty much a overkill?! rendering, additional queries...) and can use already cached entities.

function mytheme_preprocess_node(&$vars) {
  if ($vars['node']->type == 'my_content_type' && $vars['view_mode'] == 'panel_region_left') {
    $vars['theme_hook_suggestions'][] = 'node__my_content_type__panel_region_left';
  }

  if ($vars['node']->type == 'my_content_type' && $vars['view_mode'] == 'panel_region_right') {
    $vars['theme_hook_suggestions'][] = 'node__my_content_type__panel_region_right';
  }
}

I am not sure how well this will be cached and how much resources it will consume. Any advice would be grateful.

As the official doc says you can do something like

  panels-pane_node-title.tpl.php

  panels-pane_panel_node_title.tpl.php

  panels-pane-node-title.tpl.php

  panels-pane-node_title.tpl.php

After some search i have found that the suggestions are not detecting by panels, and i end up in this preprocess function.

function MYTHEME_preprocess_panels_pane(&$vars) {
// get the subtype
$subtype = $vars['pane']->subtype;

// Add the subtype to the panel theme suggestions list
$vars['theme_hook_suggestions'][] = 'panels_pane__'.$subtype;

return $vars;
}

After a long search in forums i found this too,

<?php
function THEMENAME_preprocess_page(&$vars) {
    global $theme_path;
    if($panel_page = page_manager_get_current_page()){

        $target_menu = 'menu-sixth-form-college';
        $current_path = menu_get_item();

        $target_menu_links = menu_load_links($target_menu);
        foreach($target_menu_links as $links) {
            $link_paths[] = $links['link_path'];
        }
        $preferred_link_paths = $link_paths;
        // if the current link is inside menu_load_link
        if(in_array($current_path['href'], $preferred_link_paths)) {
            $vars['theme_hook_suggestions'][] = 'page__sixthform';
        }
        if($panel_page['name'] == 'page-sixth_form_college') {
            $vars['theme_hook_suggestions'][] = 'page__sixthform';
        }
    }
?>

Theme and Cache.

When it comes to caching, i believe Drupal will handle template caching for you as normal page cache. If your dont think it work you can do something like

<?php
function my_module_function() {
  $my_data = &drupal_static(__FUNCTION__);
  if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $my_data
      // with the correct stuff..
      cache_set('my_module_data', $my_data, 'cache');
    }
  }
  return $my_data;
}
?>

The best and easiest way to add custom content to panels and theme it your way is, make custom content panes, add your code using the filter mode as php filter, and encapsulate your custom php/html content into custom div tags.

Now to theme this custom content pane, all you have to do is add your custom css rules for this div tag into your local.css

If you have any specific requirements, please state them here.


Display terms, username and user picture in a view block I created a new view block and it appears in Article - Content type; In these block I want to display the author's user picture, author's username, post date, category, tags, and comment count.

I succeeded to display user picture, username, but the post date, category, tags, and comment count are from the other article (the first or the last article written by the same author).

I used a few relationships and contextual filters, without success.

Example

I have an article with title "One two three", category numerals, tags "one, two, three, numeral". When someone reads these article, I want that block to show these values:

Category: numerals
Tags: one, two, three, numeral
username
user picture

Is it possible to display all these things in one view?

There was a recent answer very much along these lines here that recommended the module Author Pane.  This module is extensible with hooks; might be the easier way for you to go as well.

  Author Pane is a block of information about a given user, like those typically found on a forum post, but can be used in other places as well. From core, it collects the user picture, name, join date, online status, contact link, and profile information. In addition, any module or theme can feed it more information via the preprocess system. All of this information is then gathered and displayed using a template file.

You need the Chaos tool suite, Views and Quick Tabs modules. Under Chaos tool suite module enable Chaos tools, Page manager and Views content panes; under Views module enable Views and Views UI.

Go to Structure/Views (admin/structure/views); click "Add a new view"; give a name and don't select "Create a page" or "Create a block" and click "Continue & edit".
Remove "Content: Post date (desc)" from Sort criteria.
Under Contextual Filters add "Content: Nid"; under "When the filter Value is not available", select "Provide default value, Type - Content ID from URL"; under "When the filter value is available or a default is provided" select "Specify validation criteria", "Validator - Content", under "Content types" select "Article", and then click "Apply (all displays)."
Remove "Content: Title from fields" and add "Content: Tags (Tags)", "Content: Category (Category)", "Content: Comment count (Comments)" and "Content statistics: Total views (Total views)".
Under "Relationships" add "Content: Author", and check "Require this relationship"; click "Apply (all displays)".
Under "Fields", add "(author) User: Name" and "(author) User: Picture".
Under "Pager", click on "Full" and "Display a specified number of items"; click "Apply". At "Items to display" set 1; click "Apply".
Then you need to add a display to this view: click on "Add button" and select "Content pane".
Under "Pane settings", click "Edit" at "Argument input"; at "Content: Nid source", select "From context"; at "Required context", select "Content ID" and check "Context is optional"; click on "Apply".
Go to Structure/Quicktabs, click on "Add Quicktabs Instance", and scroll down; you'll find a table. At "Tab type", select "view"; at "Select a view", choose the view you created; at display select *"panel_pane_1: Content pane"*; give a name in "Tab title", and click on "Save".
Go to Structure/Blocks (admin/structure/block) find your quick tab block, and put it in articles pages.

Now play with CSS.

Here is my view export:

$view = new view;
$view->name = 'info_about_the_current_article_w';
$view->description = 'I try to create a custom content pane (block) that display the information about who written the article that is viewed, etc.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Info about the current article when is viewed';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = 1;
/* Field: Content: Tags */
$handler->display->display_options['fields']['field_tags']['id'] = 'field_tags';
$handler->display->display_options['fields']['field_tags']['table'] = 'field_data_field_tags';
$handler->display->display_options['fields']['field_tags']['field'] = 'field_tags';
$handler->display->display_options['fields']['field_tags']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['external'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['field_tags']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['field_tags']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['trim'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['html'] = 0;
$handler->display->display_options['fields']['field_tags']['element_label_colon'] = 1;
$handler->display->display_options['fields']['field_tags']['element_default_classes'] = 1;
$handler->display->display_options['fields']['field_tags']['hide_empty'] = 0;
$handler->display->display_options['fields']['field_tags']['empty_zero'] = 0;
$handler->display->display_options['fields']['field_tags']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['field_tags']['group_rows'] = 1;
$handler->display->display_options['fields']['field_tags']['delta_offset'] = '0';
$handler->display->display_options['fields']['field_tags']['delta_reversed'] = 0;
$handler->display->display_options['fields']['field_tags']['delta_first_last'] = 0;
$handler->display->display_options['fields']['field_tags']['field_api_classes'] = 0;
/* Field: Content: Category */
$handler->display->display_options['fields']['field_categories']['id'] = 'field_categories';
$handler->display->display_options['fields']['field_categories']['table'] = 'field_data_field_categories';
$handler->display->display_options['fields']['field_categories']['field'] = 'field_categories';
$handler->display->display_options['fields']['field_categories']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['external'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['field_categories']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['field_categories']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['trim'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['html'] = 0;
$handler->display->display_options['fields']['field_categories']['element_label_colon'] = 1;
$handler->display->display_options['fields']['field_categories']['element_default_classes'] = 1;
$handler->display->display_options['fields']['field_categories']['hide_empty'] = 0;
$handler->display->display_options['fields']['field_categories']['empty_zero'] = 0;
$handler->display->display_options['fields']['field_categories']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['field_categories']['field_api_classes'] = 0;
/* Field: Content: Comment count */
$handler->display->display_options['fields']['comment_count']['id'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['comment_count']['field'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['label'] = 'Comments';
$handler->display->display_options['fields']['comment_count']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['external'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['comment_count']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['comment_count']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['trim'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['html'] = 0;
$handler->display->display_options['fields']['comment_count']['element_label_colon'] = 1;
$handler->display->display_options['fields']['comment_count']['element_default_classes'] = 1;
$handler->display->display_options['fields']['comment_count']['empty'] = '0';
$handler->display->display_options['fields']['comment_count']['hide_empty'] = 0;
$handler->display->display_options['fields']['comment_count']['empty_zero'] = 0;
$handler->display->display_options['fields']['comment_count']['hide_alter_empty'] = 0;
$handler->display->display_options['fields']['comment_count']['separator'] = '';
$handler->display->display_options['fields']['comment_count']['format_plural'] = 0;
/* Field: Content statistics: Total views */
$handler->display->display_options['fields']['totalcount']['id'] = 'totalcount';
$handler->display->display_options['fields']['totalcount']['table'] = 'node_counter';
$handler->display->display_options['fields']['totalcount']['field'] = 'totalcount';
$handler->display->display_options['fields']['totalcount']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['external'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['totalcount']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['totalcount']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['trim'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['html'] = 0;
$handler->display->display_options['fields']['totalcount']['element_label_colon'] = 1;
$handler->display->display_options['fields']['totalcount']['element_default_classes'] = 1;
$handler->display->display_options['fields']['totalcount']['empty'] = '0';
$handler->display->display_options['fields']['totalcount']['hide_empty'] = 0;
$handler->display->display_options['fields']['totalcount']['empty_zero'] = 0;
$handler->display->display_options['fields']['totalcount']['hide_alter_empty'] = 0;
$handler->display->display_options['fields']['totalcount']['separator'] = '';
$handler->display->display_options['fields']['totalcount']['format_plural'] = 0;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['external'] = 0;
$handler->display->display_options['fields']['name']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['name']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['element_default_classes'] = 1;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['name']['link_to_user'] = 1;
$handler->display->display_options['fields']['name']['overwrite_anonymous'] = 0;
$handler->display->display_options['fields']['name']['format_username'] = 1;
/* Field: User: Picture */
$handler->display->display_options['fields']['picture']['id'] = 'picture';
$handler->display->display_options['fields']['picture']['table'] = 'users';
$handler->display->display_options['fields']['picture']['field'] = 'picture';
$handler->display->display_options['fields']['picture']['relationship'] = 'uid';
$handler->display->display_options['fields']['picture']['label'] = '';
$handler->display->display_options['fields']['picture']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['picture']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['picture']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['picture']['alter']['external'] = 0;
$handler->display->display_options['fields']['picture']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['picture']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['picture']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['picture']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['picture']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['picture']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['picture']['alter']['trim'] = 0;
$handler->display->display_options['fields']['picture']['alter']['html'] = 0;
$handler->display->display_options['fields']['picture']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['picture']['element_default_classes'] = 1;
$handler->display->display_options['fields']['picture']['hide_empty'] = 0;
$handler->display->display_options['fields']['picture']['empty_zero'] = 0;
$handler->display->display_options['fields']['picture']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['picture']['link_photo_to_profile'] = 1;
$handler->display->display_options['fields']['picture']['image_style'] = 'thumbnail';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['nid']['specify_validation'] = 1;
$handler->display->display_options['arguments']['nid']['validate']['type'] = 'node';
$handler->display->display_options['arguments']['nid']['validate_options']['types'] = array(
  'article' => 'article',
);
$handler->display->display_options['arguments']['nid']['validate_options']['access'] = 0;
$handler->display->display_options['arguments']['nid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['nid']['not'] = 0;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Content pane */
$handler = $view->new_display('panel_pane', 'Content pane', 'panel_pane_1');
$handler->display->display_options['argument_input'] = array(
  'nid' => array(
    'type' => 'context',
    'context' => 'entity:node.nid',
    'context_optional' => 1,
    'panel' => '0',
    'fixed' => '',
    'label' => 'Content: Nid',
  ),
  'uid' => array(
    'type' => 'context',
    'context' => 'entity:user.uid',
    'context_optional' => 1,
    'panel' => '0',
    'fixed' => '',
    'label' => 'Content: Author uid',
  ),
);

I found an easier way to do that: Install the Display suite module; you can watch this screencast made by swentel on Youtube.


how to create a apply button in view table result ? I have created a view with display format as table
I want to create a button in the last column for every row
So that when user click on that button form then form open.
So how can I create that button for every row

1) On the left side of the Views admin screen, click the "Add" button next to Fields to add a new field

2) Search for "custom field" and select Custom Field

3) For Create a Label, enter: Apply for Job

4) For Text, enter:

Apply for Job

(class="button" is what makes the link look like a button)

5) Replace /link/to/destination above with the location of where they can apply for the job. If you need to use replacements in the URL like the node ID number, add the NID field to the view, and replace the URL with something like /node/[nid]/apply

View attached screenshot for what it should look like.

Take a look at Views accordion module.

  Features

  Works with field grouping and relationships.
  Option to use the field
  grouping headers as the headers for the accordion items. (yay!)
  Configure settings for jQuery UI Accordion through the views
  interface.

Have a look at this is quick demo video.


Referencing CSS file from theme library inside Embedded Widget Paragraph type I have an article page in Drupal 8 that contains a chart (inserted into the page using Text paragraph). The chart uses CSS classes that I have created inside the global stylesheet. It works, but I don't want these CSS classes to be loaded on every single page on my website.
I'm thinking that I would move the CSS classes into a separate file. Then I would move the HTML code for the chart into an Embedded paragraph and reference the theme library.
I'm new to Drupal 8 theming so I'm not sure how I would go about doing that. Can someone give me the general steps?
I think need to do the following.

Move CSS classes to a new file
create a library refencing the new CSS file that is not loaded by default
Add the CSS file URL to the embedded widget "Javascript Source" field

I'm not sure how to add the library refence to my theme or to make it not load by default.

Your thought process is correct. To implement below script tag is to be referenced inside the embedded widget
Like: Js
<script type="text/javascript" src="/custom.js"></script>

Like : Css
<link href="/custom.css" rel="stylesheet" />

Thanks


Form API 'image_button' vs 'submit' breaks my AJAX form I have an AJAX form that works as expected with the following submit code:

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Go'),
);

I want to use an image for the button, but the type 'image_button' breaks the AJAX functionality (multiple repopulating select fields, won't appear, or update):

$form['submit'] = array(
  '#type' => 'image_button',
  '#src' => '/themes/moon/images/go.gif',
  '#value' => t('Go'),
);

Oddly, the 'image_button' works fine when clicking it (form works as expected) it's just the AJAX updating of the form that stops working? Drupal Form API Reference

You have to set an unique '#name' tag for EVERY button (submit, image_button, button) on the page. This worked for me.


Put Site-Wide Contact Form in a Block I want to display the contact form inside a block, so that a user can access it directly from another page. Using Webform Module to create a new form would be overkill.

Is there a simple way to do this, either core, a small module or custom module?

Use the Form Block module. Enables the presentation of user registration, site wide contact, or node creation forms in blocks.

You can achieve this by using:

hook_form_info() to define the block you want to add.
hook_block_view($delta) to define the content you wish to add to your block. Basically just add this

$block = [];

switch ($delta) {
  case 'block_contact_form':
    module_load_include('inc', 'contact', 'contact.pages');
    $block['subject'] = t('Contact');
    $block['content']['form'] = drupal_get_form('contact_site_form');
  break;
}

return $block;


How to get Tb Mega Menu working in Chrome? I have a website and integrated Tb Mega Menu for the navigation. But the problem is my dropdown is not working in Google Chrome, though it is perfectly working in Internet Explore, Mozilla. My version of Google Chrome is 45.0.2454.85 m.
How to solve this issue? I did search for this, but found nothing suitable.

After so much time I found an answer. I Just increase the z-index for that li and the dropdown start working for me.


How do I let users unpublish and publish their own content? I want to let users unpublish and publish their own content. By default, you have to give "administer nodes" permission for users to be able to unpublish or publish content. That is way to broad though. I want to let users unpublish or publish a node if and only if they created it. This also means they should be able to view unpublished nodes if and only if they created it.

A UI approach which I have used on some sites is the Override Node Options module, adds permissions similar to those that my other answer provides, plus a bunch extra.

The content access module should cover what you want.

  This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.


Rule condition to check which language is used by the visitor? I have a multilingual website (English, Spanish).

Is there any way to create a rule condition to compare the language used by the visitor against a fixed value?

The condition would something like: if language is English then go ahead with the actions.

Seemed like a useful thing to have.

I created a patch for Rules, adding this functionality. I posted it in the Rules issue queue. That seemed better than providing the code directly here, as this way you can still use it anyway that suits you, yet it may actually get into core Rules.

Also see this question, "How do I add a new condition in Rules 2?".

You can try to accomplish this adding additional field to profile and using 2 different rules.

1st will set the value of the field, using this functions

2nd will compare the profile field value using account:profile_lang data selector


How to theme regions in non-standard themes like Consilium? So I'm stuck with a theme that is very difficult to work with because it is nonstandard. It seems like it would like to be Omega and put lots of functionality into the admin UI and out of template files but it seems they forgot to actually add that functionality in there.

So the goal is to add regions and edit existing ones. Normally I would do this in page.tpl.php but this theme does not define region order and html inside a template like this. They've provided a Layout section in their appearance settings but there's no way to actually do anything in this section. No drag, no select, nothing.

So my question is that somewhere in some file, these regions have to be defined in a specific order so where? It's not in page.tpl but it has to be somewhere or else drupal wouldn't know what to do with these regions or how to structure their html.

I know a few suggestions would be to contact the theme maintainer but they are horrible on support. Another suggestion might be to choose another theme but my company picked this one and so I have no choice. I also have a Friday deadline and just got to start this week so figuring out this silly theme has been taking up all my time.

regions are normally defined in the [theme_name].info file in the theme directory. Here is an example from the Bartik theme:

  name = Bartik

  description = A flexible, recolorable theme with many regions.

  package = Core

  version = VERSION

  core = 7.x

  stylesheets[all][] = css/layout.css

  stylesheets[all][] = css/style.css

  stylesheets[all][] = css/colors.css

  stylesheets[print][] = css/print.css

  regions[header] = Header

  regions[help] = Help

  regions[page_top] = Page top

  regions[page_bottom] = Page bottom

  regions[highlighted] = Highlighted


How can I prevent text areas from being resizable? Text areas in Drupal 7 are resizable by default.  I would like to turn this off, but when I checked a text area with Firebug, I couldn't find the CSS that was making it resizable.

How can I prevent text areas from being resized?

It's JS that makes the text areas resizable, not CSS. I think the simplest way to disable this behaviour for all textareas is to implement THEMENAME_textarea() in your theme and remove it there:

function THEMENAME_textarea($element) {
  $element['element']['#resizable'] = false ;
  return theme_textarea($element) ;
}

I was recently solving this problem too and found out these 2 solutions:

First one I prefer the most: Use this code in your theme's template.php and all grippies and textarea.js will disappear:

/**
 * Override of theme('textarea').
 * Deprecate misc/textarea.js in favor of using the 'resize' CSS3 property.
 */

function THEMENAME_textarea($variables) {
  $element = $variables ['element'];
  element_set_attributes($element, array('id', 'name', 'cols', 'rows'));
  _form_set_class($element, array('form-textarea'));

  $wrapper_attributes = array(
    'class' => array('form-textarea-wrapper'),
  );

  $output = '<div' . drupal_attributes($wrapper_attributes) . '>';
  $output .= '<textarea' . drupal_attributes($element ['#attributes']) . '>' . check_plain($element ['#value']) . '</textarea>';
  $output .= '</div>';
  return $output;
}

Don't forget to change THEMENAME to your theme name and flush all caches.

Second way is to install module Disable resizable textarea but I try to keep number of modules in my installations as low as possible.


Does Drupal have a collaborative editing module? What I would like to offer my users is the ability to propose a writing project to a group of people (users and non users) and the people who want to join the writing project are able to edit the same node together in separate locations.

The answer from knowledges33ker is a good start.

However the workbench module - https://drupal.org/project/workbench
 - might also help with this and add further functionality.

Particularly in that it offers good tracking of edits that have been made to content and you can revert content to previous revisions etc.

With the user reference field set up, you could also, if you wanted, use the Rules module - https://drupal.org/project/rules - to fire emails or notifications to users when the content is edited/updated.

You could install the references module, then add a user reference field to the content type. Then, install the Node Access User Reference Module (https://drupal.org/project/nodeaccess_userreference). You can set your configuration so that users of a given role can add another user(s) to the node and you can specify what permissions those editors can have (e.g. edit but not delete the node, etc). This gives you (and/or your users) more control over when specific people get to "join" a writing project with editing permissions.

You could also try the drupal wiki install profile: https://drupal.org/project/drupal_wiki


Add a custom VBO action I want to add a custom VBO action.

It display in the actions list of the view, it should like a tree, like this:

-Add Role-

RoleA

RoleB

-Remove Role-

RoleA

RoleB

And When I select RoleA(-Remove Role-), check some users, click the submit.

The users checked should be removed RoleA.

How can I code a custom VBO action like this ?

You can create custom VBO action by implementing hook_action_info() hook. Here are some useful links which can help you achieve what you want:

Views Bulk Operations development guide (Drupal 7)

Programmatically adding and removing roles to users in Drupal
HOWTO assign a user to a role programatically

additionally, Examples module can help you to learn about Actions.


Global search/replace on special characters accidentally taken in on an import ( â€™ ) I have imported (through CSV using Feed Import) and large amount of information. I have a large amount character encoding issues such as

  Grimsbyâ€™s teaching focus is on...

Where â€™ is in place of the apostrophe. Is there any way to search/replace myself out of this? Could I use an input filter?

You can try the scanner module to do these sitewide text search and replace operations but it may be a little tricky because of the characters you're replacing (they look like MS smart quotes?)

Better solution might be to rollback your import, rexport your CSV with a UTF-8 character set and try your import again.

I successfully used the Scanner module to replace smart/curly quotes with plain quotes.