Drupal 7 - Error on Checkout, e-Commerce I installed a e-commerece module for my website. And enalbed all the supporting files under 'modules'. I'm able to add products and view them and can also add to the shopping cart. however when i checkout, it sends me some here..like this

PDOException: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column
'exid' at row 1: INSERT INTO {ec_customer} (type, exid, uid, name) VALUES
(:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2,
:db_insert_placeholder_3); Array ( [:db_insert_placeholder_0] => anonymous
[:db_insert_placeholder_1] => 4mePOKXg5_hhSCYgVSumyWMhsej6EZ5LRLKafRfPBTA
[:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => ) in drupal_write_record()
(line 6975 of C:\xampp\htdocs\cart\includes\common.inc).

Does anyone know why is it throwing an error.

If you're new to Drupal commerce, try installing Commerce Kickstart.  There are detailed installation instructions available.

Drupal Commerce is fairly complex and there are lots of different types of errors that can result.  Commerce Kickstart is a package (known in Drupal as an installation profile) that sets up most of the commerce stuff for you.  If you're not experienced in working with Drupal, this is an easy way to get started without having to troubleshoot error messages.

If you do try Commerce Kickstart, do so from a new site.  If you try to install over Drupal Commerce it could get messy.


Remove all js from template I'm trying to remove all javascript for anonymous users but I've hit a roadblock.

This is the php I'm using in template.php (phptemplate_preprocess_page function):

$js = drupal_add_js();
unset($js['core']);
unset($js['module']);
unset($js['setting']);

$vars['scripts'] = $js;

print_r($vars['scripts']); // prints what it should
print_r(drupal_add_js('header', $js));  // prints everything like nothing happened!

You can do it in function phptemplate_preprocess_page exists in template.php

The below is code to remove unwanted js

function phptemplate_preprocess_page(&$vars) {

  $scripts = drupal_add_js();
  //PRINT THIS ARRAY AND UNSET THE UNWANTED ARRAY
  // unset($scripts['module']['sites/default/files/js/jquery-min.js']);
  unset($scripts['module']['YOUR_PATH_TO_JS']);
  $vars['scripts'] = drupal_get_js('header', $scripts);

}


Language specific settings for field formatters I've created a custom field formatter widget for numeric fields. The formatter has A LOT of settings to customize the visual output of that number, to whatever designers/marketing wants (adding a lot of HTML markup, with[out] leading/trailing zeros, zeros as dash, one or two fractions, rounding, prefixes/infixes/suffixes,... ).  Some of those settings are language-dependant though, so I'd like to enter different formatter settings in

/en/admin/structure/types/manage/MY_CONTENT_TYPE/display
/de/admin/structure/types/manage/MY_CONTENT_TYPE/display
/fr/admin/structure/types/manage/MY_CONTENT_TYPE/display

I've noticed that there is a $langcode parameter in
FormatterInterface::viewElements(FieldItemListInterface $items, $langcode)

but I don't know how to make
FormatterInterface.php FormatterInterface::settingsForm(array $form, FormStateInterface $form_state)
language-aware.

Is it possible at all to have language-specific settings in a field formatter? If yes, how to I store and retrieve those settings in the correct language?

Define a schema in your module
config/schema/mymodule.schema.yml.

Example from the date range module:

core/modules/datetime_range/config/schema/datetime_range.schema.yml

field.formatter.settings.daterange_default:
  type: field.formatter.settings.datetime_default
  label: 'Date range default display format settings'
  mapping:
    separator:
      type: label
      label: 'Separator'
      translation context: 'Date range separator'

For more information see
Block configuration form values are not translated
You need an UI to translate, which is unfortunately not ready
yet, see this issue:

Entity view/form mode formatter/widget settings have no translation
UI

Until then you can edit the translated yaml file of an exported
config in config/sync/language/[LanguageID] or install the patch from the
issue.


How to bulk update select list fields? I have a content type and it has a select list field. There are two options Yes or No and this field is not a required field.

The website has about 100,000 nodes and I want to bulk update all nodes in order to select the "Yes" for each node. Is there any way to do this?

You have multiple options:

You can use code that iterates over all nodes and changes the value of the field (you will need some module to execute the code, for example devel).
Other option is to use the Views Bulk Operations module, build a view which shows a list of nodes of that type, and add a views bulk operations field which has the option to edit a node, and this will allow you to select all the nodes in a view and modify a field with the same value.


How to make form_alter act upon boolean choice rather select list I am working on a form_alter() based on Form API states which is about switching a field choice based on the value of a select field as below;

'select[name="field_date_type"]' => ['value' => 'allday']

I would like to know what syntax is required for changing the field widget from select to boolean or checkboxes or radios.

I have tried switching select to boolean, checkbox and radio but none are working for me.

What am I doing wrong?

Assuming you mean checkbox (HTML doesn't have a boolean input type), the property is checked, so you can use:

':input[name="field_date_type"]' => ['checked' => TRUE]


How to re-create content types using the feature module which removes deleted fields? I've been looking into the Feature module to move changes from Dev to Staging without redoing everything.

On my Dev site I made changes in the content types (added new fields, deleted some field). Then I exported all content types as a feature and imported in to Staging. But still I see the deleted fields on staging.

I thought to delete all content types on staging and enable the module exported by feature but there is no delete option in content types.

Am I doing it in the correct way?

The answer to your question boils down to what is mentioned by the Features maintainer in this comment, i.e.:

  FInally going to mark this as "won't fix" until somebody proposes something better.

  1) Features will never do anything that might cause content to be lost on your site. This includes deleting fields. Just because you remove a field from a feature doesn't mean you might not still have content stored that would be lost if features auto-deleted it. I've never been in favor of any sort of auto-deletion.

  2) Now that fields are split into bases and instances, this gets even more complicated.

The next comment in that same issue includes a link to a 32 steps process, which describes Deleting a Drupal Field Saved in Features. IMHO this is "as good as it gets" today (and my recommended work around until further notice).


Which files do I need to edit to alter webform #states with hook_form_alter? I need to create #states conditions between either the fields in any one element in a webform or across other elements in the same form. I'd hoped I could do it via the WF yaml editor but it seems I couldn't [1].  As per @jrockowitz 's comment on the attached link #1, I

  might be able to use a form alter hook to add the needed #states

I am not a developer but it seems with drupal 8+ I do need to learn to start to be one and that's on my list for sure. I'd love to be able to contribute something to Drupal and especially webform but I find the learning process intimidating especially with the lack of "beginner-type" tutorials at least when it comes to creating custom modules with more than "hello world!".

For now, I need to know the steps I need to follow @jrockowitz 's advice and use hook_form_alter to serve my goal. My understanding is that could be done either on a theme level or custom module level (please correct me if wrong) and since I'm more comfortable with the theme way and I feel it's simpler for someone like me, I like to know (at least):

which files ( other than MYTHEME.theme) I need to edit or/and create to start with and
what info do I need to look for and study so I can do the job and begin my learning journey.
I learn best by example and so any extra clear a-b-c type tips to get me started is greatly valued if any.

If the custom module way is more advisable or the only way:

What is the minimal skeleton of a custom module that I need to have for the purpose.
What do I need to study to learn how to create such a module.

(I'm not sure if the last question should be a separate question so please forgive my newbie status here but I promise I've done my best)

Thanks so much everyone

A sample of what I want to achieve:

some_question:
  '#type': tableselect
  '#title': 'some question'
  '#options':
    q1: 'q1 (hide if q2 is checked)'
    q2: 'q2 (hide if q1 is checked)'
    q3: q3
    q4: q4
    q5: q5
    q6: q6
    q7: q7

Related links:

[1] Why isn't my custom Form API #states applied in my webform yaml editor working?

[2] https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.7.x

[3] https://www.jrockowitz.com/blog/add-ons

Ok, if you need to rely on custom dev, you can indeed use hook_form_alter().

It would work if you set it in your mytheme.theme file but for unrelated theme issues I prefer to rely on custom modules.
To create your module:

Create a mymodule.info.yml file in the folder /modules/custom/mymodule of your Drupal website. See this page for providing your file with the minimal content to have your module detected by Drupal.
With only this file you should be able to enable your module
Create a mymodule.module file at the same level as your .info.yml file
In your .module file (or mytheme.theme if you chose not to create a module), add the following:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Target your form
  if($form_id == "your_form_id") {
    // Use Devel Kint module to display the architecture of your form and make it easier for you to find the elements you wish to alter
    kint($form);
    // Now you can access the elements of your form and edit the desired ones

    // Hide checkbox "my_checkbox_name" if checkbox "my_other_checkbox" is checked
    $form['my_checkbox_name']['#states'] = array(
      'invisible' => array(
        ':input[name="my_other_checkbox"]' => array('checked' => TRUE),
      )
    );
    // Make field "some_input_text" required if input field "some_other_input" is filled with value 'hello'
    $form['some_input_text']['#states'] = array(
      'required' => array(
        ':input[name="some_other_input"]' => array('value' => 'hello'),
      )
    );
  }
}

I recommend you to have a look at this page for the list of available #states and some examples as well.

Happy coding!


Update commerce cart block when product added through ajax Hii How can I update commerce_cart_block when my product is added through ajax.
Any suggestion will be helpfull.

You need to extend your custom ajax call (or how is your setup ?) with an update cart ajax command, there's a module for it named: commerce_ajax_cart

If you want it all out of the box, then use the dc_ajax_add_cart module.


What is the use of has_js cookie? I am building an Android app that talks to Services module using REST endpoint.  When I post any content without setting the "has_js=1" cookie to the REST endpoint in JSON format, my content is never accepted by Drupal or Service module.

What is the use of has_js cookie and why do I need to send along with my POST requests?

Update:

Following is my code to post the article content type. If I do not add the has_js=1 cookie, article won't be posted to Drupal site.

 protected Integer doInBackground(String... params) {

        //read session_name and session_id from passed parameters
        String session_name=params[0];
        String session_id=params[1];

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://ec2-54-***-**-***.us-west-2.compute.amazonaws.com/cmac/rest/node");

        try {

            //get title and body UI elements
            TextView txtTitle = (TextView) findViewById(R.id.editTitle);
            TextView txtBody = (TextView) findViewById(R.id.editBody);

            //extract text from UI elements and remove extra spaces
            String title=txtTitle.getText().toString().trim();
            String body=txtBody.getText().toString().trim();

            //create JSON object to pass to Services endpoint
            JSONObject json= new JSONObject(" { \"title\":\""+title+"\",\"type\":\"article\",\"body\":{\"und\":[{ \"value\":\""+body+"\"}]}}");

            StringEntity se = new StringEntity( json.toString());
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httppost.setEntity(se);

            BasicHttpContext mHttpContext = new BasicHttpContext();
            CookieStore mCookieStore      = new BasicCookieStore();

            //create the session cookie
            BasicClientCookie cookie = new BasicClientCookie(session_name, session_id);
            cookie.setVersion(0);
            cookie.setDomain(".ec2-54-***-**-***.us-west-2.compute.amazonaws.com");
            cookie.setPath("/");
            mCookieStore.addCookie(cookie);
            cookie = new BasicClientCookie("has_js", "1");
            mCookieStore.addCookie(cookie);
            mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);

            httpclient.execute(httppost,mHttpContext);

            return 0;

        }catch (Exception e) {
            Log.v("Error adding article",e.getMessage());
        }

        return 0;
    }

The has_js cookie has been used by the Batch API. Without this cookie, or when JS is disabled in the client browser, the batch API will give you a WSOD.

See $_COOKIE['has_js'] must die.

If your service endpoint is dealing with the Batch API internally, then you will have this problem.


easiest way to implement alternating row colors? DISCLAIMER,

I am not a programmer.

What would be the easiest way to implement alternating css row colors in a table for a drupal 7 theme?  Thanks!

The easiest way would be straight CSS using the :nth-child pseudo-selector:

tr:nth-child(even) td { background: #ccc; }
tr:nth-child(odd) td { background: #aaa; }

The usual caveats apply (i.e. it doesn't work in Internet Explorer <9)


My .js file is not included in my site I am working on Recruiter distribution which uses a Cloudy theme.

I have tried 2 ways to add custom javascript to my site:

  1)Adding jquery code to the .info file of Cloudy theme(default theme)
  called cloudy.js.

  2)Adding a new .js file under js/myjs.js and added
  this to the .info file of Cloudy theme scripts[] = js/myjs.js

However,when I view the source code of my frontpage, neither cloudy.js nor myjs.js is loaded and as a result the jquery code doesn't work.

What am I missing? Has anything to do that it is a distribution and not a drupal site?
thanks

***EDITED****

How about if you add the js into the HEAD tag .

This goes into your default Theme that is being used and you need to add this hook to the template.php file ; if it doesn't already exist.  Remember to Clear you cache afterwards also.

/**
* hook_preprocess_html
*/

function yourtheme_preprocess_html(&$variables, $hook) {

   drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/common.js');

}


How to get Responsive Image Styles to work with existing images? We have existing images that never had an image style applied to them. As part of the cleanup, we are now using Responsive Image Module to do this per breakpoint. AFter creating the different image styles, we created the appropriate Responsive Image styles and applied them to the image fields through the View Modes. However, when we load the page after the Responsive image styles is applied, we get a 404 error for the image's URL. Looks like it did not create one.

How can we create the necessary images with the appropriate image styles such that we only need to modify/clear the images for that image style? We attempted to re upload the image and deleting it and adding it, but neither worked.

We even attempted the following Drush commands but they did not work. According to Drush Commands for image flush the images would be regenerated on the fly but that is not happening.

drush if --all
drush if max_650x650

Updated solution:

I simply changed themes and then switched back to my desired theme and it seemed to work. It was very odd, but effective. I did not have to make any other changes.

What web server are you using? If nginx you might want to look at your site config.

I have the following in my drupal nginx config:

  # Set up a rewrite.
  location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
    try_files $uri @rewrite;
  }

  location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    try_files $uri @rewrite;
    expires max;
    log_not_found off;
  }

Since you said you never used image styles before, I assumed you might be missing these in your configuration.


Can I post a blog entry in a user's name? I just found a new user has posted a dozen or so "blog entries" which were actually all posted as comments to a single forum question

I have explained to the user who will - hopefully - "add content" / "type = blog" in future.

Ideally, I would like to somehow edit those user comments and change them into user blog posts. Can I do that?

If not, I can copy /paste them; but can I create a new blog post entry in the user's name? And can I change its time-stamp to agree with the original?

If not, I can copy /paste them; but can I create a new blog post entry in the user's name? And can I change its time-stamp to agree with the original?

In Drupal 6, the users with the permission of administer nodes can set the author of a node they are creating, using the following field set:

It is possible to change the author of a node already existing, and a node that is being created.

The same is true for Drupal 7.


Ajax Link In A FAPI tableselect Row I'm trying to add an ajax link to my tableselect rows and replace part of this form with ajax.

$options = array();
foreach ($result as $camp) {
    $options[$camp->uuid] = array(
        'select_link' => array('data' => array(
            '#type' => 'link',
            '#name' => 'select_link',
            '#title' => t('use'),
            '#href' => 'ajax_use_data_callback/nojs/',
            '#attributes' => array(
                'class'=>array(0=>'use-ajax')
            ),
            '#ajax' => array(
                'wrapper' => 'selected-data-div',
                'method' => 'replace',
            ),
        )),

        ...

    );
}

This triggers an alert with a 404 error and the site's default html. How do I tell this ajax link to be handled like a regular ajax form element?

This can be solved by building a 'select' element with an option for each row id in the tableselect that gets an ajax link. Then we can add links to the tableselect row with '#markup' and use Drupal.behaviors to attach a function that sets the value of the select element and triggers its 'change' event. In the form building function, if $form_state['triggering_element']['#name'] is the new select element, $form_state['triggering_element']['#value'] is the one we want to process.

The select element could then be hidden and the in-row ajax links are still fairly clean. Of course this won't work if javascript is off.


Custom form multiple file upload with different extension I am working multi file upload functionality with different extensions(pdf,doc,png,jpg).
Following code is working fine for multiple images upload. I would like to know how this code modify for different extension like doc, pdf, png,gif etc.

function mymodule_form($form, &$form_state) {
    $form['file'] = array(
        '#type' => 'file',
        '#name' => 'files[]',
        '#title' => t('Upload some photos'),
        '#attributes' => array('multiple' => 'multiple'),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),

    );
}

form mymodule_form_validate($form, &$form_state) {
    //Save multiple files
    $num_files = count($_FILES['files']['name']);
    for ($i = 0; $i < $num_files; $i++) {
        $file = file_save_upload($i, array(
            'file_validate_is_image' => array(),
            'file_validate_extensions' => array('png gif jpg jpeg'),
        ));
        if ($file) {
            if ($file = file_move($file, 'public://images')) {
                $form_state['values']['file'][$i] = $file;
            }
            else {
                form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
            }
        }
        else {
            form_set_error('file', t('No file was uploaded.'));
        }
    }
}

You can use '#type' => 'managed_file' instead of    '#type' => 'file'

managed_file types is powerful tools support any kind of files format with ajax upload.

example :
$form['file'] = array(
        '#type' => 'managed_file',
        '#name' => 'files[]',
        '#title' => t('Upload some photos'),
        '#attributes' => array('multiple' => 'multiple'),
    );

you can also add upload location of files like

'#upload_location' => 'public://myfiles/'

for more info.
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#managed_file


How to set the time as 09.00 - 10.00 , 10.00 - 11.00 in day calendar view display? I'm creating a calendar of event content types by using the date and calendar modules.

I already know how to customize the time grouping settings to set the time from particular time to the other (from Calendar: How to limit the range of hours in Days display?).  Now I want to display the time as a duration like 09.00 -10.00 AM, 10.00 - 11.00 , 11.00 -12.00 , 12.00 - 1.00 format.  I also don't want to display the times which don't have an event at the time.

For e.g :

Event one - 09.00 -10.00 Am
Event Two - 10.00 - 11.00
Event Three - 12.00- 2.00
Event Four - 04.00 - 06.00

I want to display this as :

09.00 -10.00 - Event one
10.00 - 11.00 - Event Two
12.00- 2.00 - Event Three
4.00 - 6.00 - Event Four

This is the result I'm trying to get from the day calendar view display.  In the display, the time which doesn't have an event is not listed in the time column (e.g., from 2.00 - 4.00). Could anyone help me in this?

Thanks in advance.

Ranjani, if you want to collapse all times which don't contain events for the day, then I don't think you really need to be using a day-calendar format? I think your best bet would be to just do a regular table display for your view.

Change your view to be a table format
Have the time range in one column and the event title in the other
To get the range in the first column, just display your date in two separate fields, the first time, display the 'from' time, in the second one display the 'to' time
Go into your field settings (screenshot) and select those date fields to be shown inline.  You can then specify which character should separate the inline fields.  Use a '-' in your case.

Does that get things close to what you were hoping?


Permissions on remote server problem I have this error message:

The specified file temporary://fileYU5WGQ could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

I know it's a folder permission problem. But I can't figure out which folder is the cause.

In sites/default/files I have these three folders, all of them with permission set to 777:

tmp

temp

temporary

Then I don't know where is the problem??
I attached a image capture of the sistem file setting:

Did you check what user is the owner of each of your folders in question ?
Use chown username:groupname to change owner/group of a folder.


Fetching only first row from database I work with:

$mandator = $this->database->select('Mandators', 'm')
     ->fields('m')
     ->condition('idMandators', $mandatorId)
     ->execute()
     ->fetchAll();

to retrieve my data from database. The result is an array with 1 array item. How can I retrieve always only 1 object, without the array? Like e.g. ->fetchOne?

$query = \Drupal::entityQuery('node')
            ->condition('status', 1)
            ->condition('type', 'my_content_type')
            ->condition('field_ref_au', $nid, '=')
            ->range(0,1)
            ->sort('created', 'DESC')
        ;


Image field file upload issue I'm using Drupal 8 and paragraphs together, and I've got an image field attached to an image paragraph. When adding content, if I nest this inside of another paragraph (as a paragraph reference field), the file upload fails. I get the throbber gif, and then "No file chosen." If I use this paragraph type without nesting it, it works fine.

Logs and watchdog show no errors, and all other file related things (logo's, other image and file fields) work properly on their own (verified it's not a permissions or other related issue).

Spent some time looking around for an answer to this, so I thought I'd write it up even though I figured it out.

The combination of machine names involved in my nesting for the paragraph type and the paragraph reference field were overloading the ajax link length. I shortened the paragraph reference field machine name and nesting now works beautifully!


How to check in a rules condition if an image field has value? Is there any way to check if a field has no value (image field) after saving the content in Rules? I tried Data Value is Empty, but it doesn't work!

Output of the rules:

{ "rules_autos_featured_listing_without_image" : {
    "LABEL" : "Autos: featured listing without image",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "autos" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--listing" : { "bundle" : "listing" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_listing_grouping" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_feature" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_images" } },
      { "data_is" : {
          "data" : [ "node:field-feature" ],
          "value" : { "value" : { "feature" : "feature" } }
        }
      },
      { "data_is_empty" : { "data" : [ "node:field-images" ] } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-listing-grouping" ], "value" : "1302" } }
    ]
  }
}

Make sure the field you are trying to "test" (for its value), is available at the time Rules tries to do so.

That's why I always add a entity_has_field condition (and put it as the first condition) which looks something as in this example (part of a rules export of some rule):

"IF" : [
  { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_appointement" } }
],

In my sample here, it is related to entity account, and my field's machine name is field_next_appointement.

So retry your rule with the Data Value is Empty condition, but put such entity_has_field condition in front of it. So that in the end your rule has 2 conditions (no PHP coding at all involved), something like so:

entity has field ...
NOT Data Value is Empty ...

Below is a (simple) rule from my training class examples. It'll display a message like "Watch, this is ONLY 100 EUR !!!!" for a node which has a field_article_price field, whereas that price is exactly 100 EUR.

{ "rules_this_article_is_for_sale" : {
    "LABEL" : "This article is for sale",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_price" } },
      { "data_is" : { "data" : [ "node:field-article-price" ], "value" : "100" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Watch, this is ONLY 100 EUR !!!!", "type" : "warning" } }
    ]
  }
}

Looking at your (updated) question (now including your current rule), I think you should try to work step-by-step to investigate which part of your rule "doesn't" work. If I was in your shoes, I'd experiment with these variations (only for debugging):

Replace the ACTION with just a drupal_message:

if you get a message then, your problem is within ACTION. Todo: fix the Action.
if not your problem is in the EVENT of CONDITION(s). Todo: go to item 2.

Remove all CONDITION(s):

if you get a message then, your problem is within CONDITION(s). Todo: fix the CONDITION(s).
if not your problem is in the EVENT. Todo: go to item 3.

Review the EVENT: if the event you're trying to use to make the Rule work does not actually happen, or if you're "too late", then of course that needs to be fixed/reviewed. In my experience, there are quite a few Rules scenarios where you should use "When Drupal is initializing". My (personal favorite) sample of that is about "before content is going to be viewed" ...

I realize the above 3 steps do not actually "answer" your question, but they may help to debug what's actually the problem.


How to save a field value according to another field value and with a user presave hook I'm using Drupal 8

There are field_a and field_b. I'd like to field_b have the same value with field_a but different format after user submit his user edit page.

my_module_user_presave($account)

{
 $data = $account->field_a->value; // There is no value, since this user did not save yet. This is the problem.
 $account->field_b->value=format($account->field_a);//format function will change the format of field_a value, and this is not a problem
}

Since the user did not save yet, so there is no value for field_a. So I am trying to use drupal_register_shutdown_function as below.

my_module_user_presave($account)

{
 drupal_register_shutdown_function('_my_module_user_presave',$account);
}
_my_module_user_presave($account)

{
 $data = $account->field_a->value;
 $account->field_b->value=format($account->field_a); //format will change the format of field_a value.
}

Now the field_a got the value. But field_b value will not be saved since drupal_register_shutdown_function.

What should I do?

Thanks!

To change a field according to another field:
function mymodule_user_presave($account) {

 $data = $account->field_a->value;
 $account->field_b->value = strtoupper($data);

 drupal_set_message($account->original->field_a->value . ' > ' . $account->field_a->value);
 drupal_set_message($account->original->field_b->value . ' > ' . $account->field_b->value);

}

To get the original values you would have to use $account->original. Otherwise you get the new values. To prove that it's working this is the output in messages from the code above after I entered abcdef in field_a:

abc > abcdef
ABC > ABCDEF
The changes have been saved.


strange PDOException error 1153 This morning my Drupal 7 site suddenly not working. I get the
"PDOException: SQLSTATE[08S01]: Communication link failure: 1153" error. The error goes away when I disabled "Aggregate JavaScript files." in config/development/performance page. I clear the cache several time, but when I re-enable "Aggregate JavaScript files" the error comes back.

This error happens only on certain pagee.

Can anyone shed some light on this problem? It doesn't make any sense to me. Thansk.

i think you need to increase your max_allowed_packet in your my.cnf/my.ini in mysql,
maybe the problem is with packet size.


How do I validate an entity before programmatically saving it? I have various functions/methods that programmatically create entities (nodes). I just noticed that invalid data has been getting stored in the db though these functions (invalid in that it doesn't meet the rules defined for that field).
How do I validate the data before $entity->save()?
I have seen documentation saying that I simply need to do $entity->validate() and then count if there are any errors; but I have marked a few fields as required and then left them empty in my API function and $entity->validate()->count() is always 0.
What am I missing?

Looking the api it should be simple:
$violations = $entity->validate();
  if ($violations->count() > 0) {
    // Validation failed.
  }


Row templates in Views 3 I need to customize the markup for certain fields in my view. In D6/Views 2 This was possible using the templates specified in Views admin under "Theme information," "Row style output." In D7/Views 3, however, these templates in Theme information come up as .tpl.php, --news.tpl.php, --default.tpl.php, --default.tpl.php, --block.tpl.php, --news--block.tpl.php and adding those templates does not change anything.

I had found an old issue on drupal.org from a previous version, which had been necro'ed to cover this, but I can't find it now. Is this broken, or am I missing something?

In the leftmost column, Format > Show needs to be changed from Content to Fields. Hat tip to https://drupal.stackexchange.com/a/5413/4371


Where is the configuration file for my custom plugins? In my development environment, I create my first plugins that uses REST with a GET method. I use Rest UI to declare my plugins directly inside Drupal.

All is ok, the request sends me the json result as expected.

But, from here, my questions are :

Rest UI avoid to declare manually a config file. Great. But after using Rest UI I'm not able to find the config file, where is the configuration saved ?
In production, must I install Rest UI too, and re-configure my plugin ? Or is it possible to just copy/paste a configuration file ?

For configuration to be found as a file (yml) you have to manually invoke/export it with any of the following methods

from the Drupal admin interface visiting the url admin/config/development/configuration/single/export. For this to work the core Configuration Manager module must be enabled.
drush with drush config-export and than finding the appropriate file manually
drupal console drupal config:export:single
contrib modules such as config_single_export or config_partial_export

All those methods above have also an import mechanism which you can use to import or see more details here

Also note you will not need the REST UI module to be enabled in production


How to show a node but return HTTP 404 response I want to show an existing page(node) normally but return a HTTP404/410 etc instead of HTTP200.

How can I do it? Is there any simple way to do it?

Drupal's built in mechanisms

for delivering 404 pages are useless to you. We can read:

  Page callback functions wanting to report a "page not found" message should return MENU_NOT_FOUND instead of calling drupal_not_found(). However, functions that are invoked in contexts where that return value might not bubble up to menu_execute_active_handler() should call drupal_not_found().

Of course if page callback will return MENU_NOT_FOUND, it will not return any meaningful data. And while calling drupal_not_found() does not always prevent data delivery, comments under function clearly shows that it causes double display of error message more often than any other result - not what you want, either.

Drupal generic header functions

may help you. Especially drupal_add_http_header(). Let me emphasize one thing in it's description:

  $value: The HTTP header value; if equal to FALSE, the specified header is unset. If $name is 'Status', this is expected to be a status code followed by a reason phrase, e.g. "404 Not Found".

So you want to set status to 404:

drupal_add_http_header('Status', '404 Not Found');

It should be enough, after all that's what drupal_deliver_html_page() is doing when you use higher-level 404 calls from previous part of my answer.

Also, you might be interested in logging it like other 404 errors:

 watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);

Where to place it?

It depends on what you need to decide if page should be 404 or not. If all you need is the actual data in page, you can go for hook_page_delivery_callback_alter():

  This hook is intended for altering the delivery callback based on information unrelated to the path of the page accessed. For example, it can be used to set the delivery callback based on a HTTP request header (as shown in the code sample). To specify a delivery callback based on path information, use hook_menu() or hook_menu_alter().

emphasis mine.

Let's assume that you need it for nodes

and this means you need a node id. NID is part of the path, so, following suggestion quoted above, you want to use hook_menu_alter().

Let's take a look on how node's menu looks like. The part we want to alter is:

  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),

    // The page callback also invokes drupal_set_title() in case
    // the menu router's title is overridden by a menu link.
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );

What you need to do is to alter it to provide your own callback. In that callback:

Perform any logic needed
Set header as you need
Log to watchdog if you want to
Call original callback and return it's result. Render cascade does not explicitly set HTTP 200 later, so your status header should be delivered unaltered. Unless some modules will alter it, of course, but that's something we cannot know.

Last notes

thanks to Ayesh K and MPD:

Sending header might now work in any of the preprocess hooks or just about any tpl.php file. The fact that you could does not mean you should, especially not in tpl files, as it may interfere with caching, but it's worth to remember you are not limited to the ways I described above. For example hook_page_alter() can be a safe choice, too.
Make sure the page size is more than 512 bytes, otherwise some browsers (Howdy, IE) will ignore it.
Keep in mind that by RFC 2616

  User agents SHOULD display any included entity to the user.

As you may notice, this RFC uses MUST in some cases and this is not one of them, so if browser will refuse to display your page after you send 404, it's not exactly an error. Browsers are not forbidden to ignore your HTML when you send 404.


Display Custom User Profile Fields in a Block on All of Their Published Pages I have created a role, and have added additional fields to their profile using Profile 2. The fields are part of the location module, and are just basic contact info (address and phone number). They are also able to chose a name, which is used in the url for both their profile and content.

So, when a user creates their account, the url is site.com/their-name. When the user adds content the URL is site.com/their-name/content.

My goal is to display their contact info in a block on all pages they publish. I was able to do this for their profile page with the following view (see attached image). However, I would like this block to appear on all pieces of content that they author.

You should take a look at the Context module.

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

  Think of conditions as a set of rules that are checked during page
  load to see what context is active. Any reactions that are associated
  with active contexts are then fired.

Or a simpler solution might be to change your path from "their-name/content" to "user/their-name/content" and only show the block on "user/*/content".


How to make custom login URL accessible in maintenance mode I created a custom login page with custom path (www.example.com/customlogin) and blocked access to default login page via hook_menu_alter(). The requirement for default login page to return 403 is achieved.

Login page accessed via new path works great, but this page is inaccessible when the website is in maintenance mode.

Question: How to make a path accessible in maintenance mode?

I'd like to find a method that does not require the use of additional modules like Rename Admin Path

A viable solution for making the path/URL/page available while in maintenance mode is the use of hook_menu_site_status_alter().

This hook is called after checking whether the site is offline (in maintenance mode) but before the current router item is retrieved and executed.

Code below should be used in a custom module:

function CUSTOMMODULE_menu_site_status_alter(&$menu_site_status, $path) {
  // Allow access to my_module/authentication even if site is in offline mode.
  if ($menu_site_status == MENU_SITE_OFFLINE && user_is_anonymous() && $path == 'custom-path') {
    $menu_site_status = MENU_SITE_ONLINE;
  }
}


Why node object loses data after using workbench_moderation_moderate? I'm using Workbench Moderation module because it matches my needs. I have a front-end form that initiate the node with some fields. Editor should review the node and fill all the required fields remaining.

So, I need to make sure that all fields are now filled with data then the state should be changed to Needs Review.

I implemented hook_workbench_moderation_transition to trigger the state change. If the next state was Needs Review, then I would make sure that all required fields were filled with data otherwise I would change the state back to the previous one and redirect to the node edit form.

What I've done so far

    function workflow_handler_workbench_moderation_transition($node, $previous_state, $new_state){
        if ($new_state == 'needs review'){
          //check if node was not reviewed before , then redirect to form
          $instatnces = field_info_instances('node',$node->type);
          //should check first if conditional_fields module is existed
          $CFS = conditional_fields_load_dependencies('node',$node->type);
          foreach ($instatnces as $key => $field_options) {
            $field = field_get_items('node', $node, $key);
            if ($field_options['required'] && !$field && !array_key_exists($key, $CFS['dependents'])) {
               //set workbench state to previous one
               workbench_moderation_moderate($node, $previous_state);
               drupal_set_message(t('Please make sure that all required fields has been reviewed'),'error');
               $url = url("node/$node->nid/edit");
               header("Location:$url");
               drupal_exit();
            }
         }
      }
   }

Problem exists when using workbench_moderation_moderate in the context above. For some reason, when I got redirected to the form to edit, and after saving, my edits were not saved on the node object and so if I opened the edit form again, I couldn't find my edits. Any ideas?

The Problem was that workbench_moderation_moderate() calls internally hook_workbench_moderation_transition() so I decided to do it with another technique that should cover the two ways that workbench moderation uses to change the state

First way to be covered, the links that exist in workbench moderation back end views. I implemented hook_menu_alter to intercept the request from those links to add my custom logic.

function my_custom_logic($node, $state){
   //add your logic here
}

/**
* Implements hook_menu_alter()
*/
function workflow_handler_menu_alter(&$items){
  $items["node/%node/moderation/%/change-state/%"] = array(
    'page callback' => 'workflow_handler_moderate_callback',
    'title' => 'Change moderation state',
    'page arguments' => array(1, 5),
    'load arguments' => array(3),
    'access callback' => 'workflow_handler_moderate_access',
    'access arguments' => array(1, 5),
    'type' => MENU_CALLBACK,
  );
}

function ei_workflow_handler_moderate_access($node, $state){
  return _workbench_moderation_moderate_access($node, $state);
}

function workflow_handler_moderate_callback($node, $state){
  my_custom_logic($node, $state);
  workbench_moderation_moderate_callback($node, $state);
}

Second way to be handled, the form that workbench adds in every node details page. I implemented hook_form_alter to add my submit handler before workbench moderation one and I added my logic again there.

/**
* Implements hook_form_alter()
*/
function ei_workflow_handler_form_alter(&$form, &$form_state,$form_id){
    if($form_id == 'workbench_moderation_moderate_form'){
      $form['submit']['#submit'][] ='my_custom_logic_handler';
    }
}

function my_custom_logic_handler ($form, &$form_state) {
  my_custom_logic($form_state['values']['node'], $form_state['values']['state']);
}

Hopefully this helps anyone who encounter that issue in the future.


Loading fields of a node I have a simple content type, which contains the fields:

Title
Body

In my view the titles of the above content type are listed. When I click on a title, I want the body of the corresponding node to be loaded with AJAX and appended after the title.

Has anyone a hint for me, how to accomplish that?

Use built-in Drupal Ajax framework.. Steps:

implement hook_menu
build ajax callback
render links (titles) like /[menu callback menu item]/nojs/arguments and add class use-ajax

Here is a good tutorial: A little Ajax-driven article reader built with the Drupal Ajax framework


Show available languages in content-view in older-drupal-versions when content was translated to different languages, it was possible to indicate in which other languages that content is available and in which not.

Let's say I have en, de and fr as languages. Foo is translated to en and de and bar is translated to fr only.

In my contents index (/admin/content) I want to display that linked info as:

fooen, de, fr
baren, de, fr

Where clicking a non-striked text leads to the edit of the particular node and clicking the striked one will start a translation.

Is that, or something which gets close, possible in D8?

The content admin screen is now just a view.  AFAIK there is no view widget that will do that.

It probably would be possible to write a entity specific global widget for this.  Basically, you can get the list of installed languages from the language manager and then for each entity row use the getTranslations() method to find what has been translated.


Table locking again, am I doing it correct? I had a problem with table locking, solved in this question:

Table 'watchdog' was not locked with LOCK TABLES on custom module

I want to share my current code, because I'm still not sure if I am doing it correct.

I have two tables:

eventi_list, for storing users reservation for selected event if there are free places of this event
eventi_wait, for storing users reservation if there are no free places for selected event. If any user withdraw her/his reservation, the oldest reservation for current event (if exists) from this table move to eventi_list table.

function eventi_book($nid) {
    $nid = (int) $nid;
    if (_eventi_if_node($nid)) {
        global $user;
        $uid = (int) $user->uid;
        $is_booked = _eventi_is_booked($uid, $nid);
        if (! $is_booked) {
            $is_booked = _eventi_is_booked($uid, $nid, 'eventi_waits');
        }
        if (! $is_booked) {
            db_query('LOCK TABLES content_type_event WRITE, eventi_list WRITE, eventi_waits WRITE, watchdog WRITE');
            $amount =  _eventi_places_amount($nid);
            if ($amount > 0) {
                _eventi_add($uid, $nid);
                db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=$nid");
              //  cache_clear_all();
            } else {
                _eventi_add($uid, $nid, 'eventi_waits');
            }
            db_unlock_tables();
        }
    }
   // _eventi_redirect_to_prev();
}

function _eventi_if_node($nid) {
    $query = db_query("SELECT COUNT(nid) as count FROM {node} WHERE nid=$nid AND type='event'");
    $result = db_fetch_array($query);
    return $result['count'] > 0;
}

function _eventi_is_booked($uid, $nid, $tbl_name = 'eventi_list') {
    $tbl_name = '{'.$tbl_name.'}';
    $query = db_query("SELECT count(nid) AS count FROM $tbl_name WHERE nid=$nid AND uid=$uid");
    $result = db_fetch_array($query);
    return $result['count'] > 0;
}

function _eventi_places_amount($nid) {
    $query = db_query("SELECT field_event_places_amount_value AS amount FROM {content_type_event} WHERE nid=$nid");
    $result = db_fetch_array($query);
    return (int) $result['amount'];
}

function _eventi_add($uid, $nid, $tbl_name = 'eventi_list') {
    $tbl_name = '{'.$tbl_name.'}';
    $t = time();
    return db_query("INSERT INTO $tbl_name (uid, nid, created_at) VALUES($uid, $nid, $t)");
}

I want to make sure that I never end up with negative number of free places of selected event.
So I have to atomic access to places amount:

$amount =  _eventi_places_amount($nid);

and then I can update places amount, when I am sure that $amount is greater than 0:

db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=$nid");

I don't like this solution, because I must to lock many tables. Is there a better way of doing this in Drupal?

MyISAM performs a table-level lock to do any SQL on a MyISAM Table.

If you convert everything to InnoDB, row-level locking is implicitly done for you. Multiversioning Concurrency Control (MVCC) allows each user to lock only row(s) needed.

Additionally, you may want to perform all atomic writes in a BEGIN...COMMIT transaction to group together several table updates as one unit. That's what InnoDB will do for you. InnoDB is ACID complaint. The A stands for ATOMICITY, a transaction's ability to be atomic.


How do I rewrite the ID of an exposed filter field element? I am desperately trying to a way that I can rewrite the ID of an exposed filter field element.  I've gotten so far as to set up hook_form_alter where I can get the specific $form array that I need.  When I look at that array using dpm($form) I can see where other info for that input element is contained, but there is no ID element in the array that I can see.

This is the current output that I'm concerned about from my exposed filters form:

Location Type

            <input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-370" value="370"  /> Parks

            <input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-371" value="371"  /> Historic Sites

            <input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-372" value="372"  /> Marine Conservation Areas

            <input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-735" value="735"  /> Urban Parks

            <input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-736" value="736"  /> Other

Specifically, the markup I want to change is the following:

<input type="checkbox" name="field_location_type_tid[]" id="edit-field-location-type-tid-370" value="370"  />  Parks

I want to be able to rewrite the id of the input element and the for of the label element.

This I've got the following in my template.php file:

function parks_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-photo-gallery') {
    dpm($form);
  }
}

Looking at what dpm returns for the $form array I can see where in that array the info for these check boxes exist, but there is nothing in there that makes any sense in terms of rewriting the ID.  What I'm seeing is the following:

form
  field_location_type_id
    #type
    #multiple
    #options
      370
      371
      372
      735
      736
    #size
    #default_value
    #theme

I was hoping there would have been an obvious ID element in that array, likely as a child to the child elements of the #options element but no such luck.

I've been looking for a solution for this for a couple of days now and I'm just spinning my wheels.  Everything I can find is people customizing the wrapper classes and stuff, but no one getting this granular.  Any help is greatly appreciated.

EDIT:

I'm leaving the code below but just for kicks I went into my dev theme and did a hook_form_alter() to test another way of achieving what you want to do. What you are when you do the dpm() isn't the full output of what can possibly be changed in the HTML. You can do the following to change the ID.

<?php
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  dpm($form); // Print out before change.
  // The 'created' was my form element, yours would be which checkbox you wanted to change.
  $form['created']['#id'] = drupal_html_id('my-new-id');
  dpm($form); // Print out after change.
}
?>

The images below show the changes in the ID and the dpm() output. They are for a select box but it should work the same for any form element.

Before Change:

After Change:

The HTML Change:

Original Thought:

I think you have to use hook_theme_form_element() for this.

<?php
function <theme_name>_form_element($variables) {
  $element = $variables['element'];
  // Do something with checkbox
  if ($element['#type'] == 'checkbox' {
    // do something with element array like $variables['element']['#id'] = 'new value'
  }
  return theme_form_element($variables);
}
?>

The code above isn't tied to a certain form ID so you may have to do a little more processing to get to that piece but it should be a good starting point. Don't forget to make the ID's unique as they are originally.

Checkout the API docs for more information.

Or you can try preprocessing the form element as well, I have done this with other elements but not sure if I changed the ID's.

<?php
function MYTHEME_preprocess_form_element(&$vars) {
  $vars['attributes']['id'][] = 'another-id ';
}
?>


Did anyone have success in configuring Mod security? I am trying to set up Mod security (the Apache module) for my Drupal site, but it affects basic Drupal functionalities like node submission, module enable/disable and people permission submissions etc.

I am using:

Drupal 7.56
Mod Security 2.91
Owasp crs 3.0
Apache 2.4

Did anyone have success in configuring Mod security based on Drupal application?

Using OWASP CRS v3.0.2 (https://github.com/SpiderLabs/owasp-modsecurity-crs/releases/tag/v3.0.2) you should find no major issues here. Drupal has it's own set of exclusions out of the box because it does things that can be considered bad practice (passing tags via parameters, etc). As outlined in the docs you should uncomment rule 900130 and enable the Drupal exceptions. There is even an example of how to do so.

https://github.com/SpiderLabs/owasp-modsecurity-crs/blob/v3.0/master/crs-setup.conf.example#L302

Enjoy!


White screen error when migrating between servers I wish to migrate my site from one shared hosting server to another. Both servers are with the same company (Heart Internet). I moved the files to the new server, set up a new database on the server, replaced the old settings.php with the contents of default.settings.php to get a default draupal installation up and running.

Trying to migrate the database using either the backup and migrate module or importing the database via phpMyAdmin I get a white screen error on the site i am migrating to.

I have looked up some possible causes and based on what I have read I have:

Disabled Devel modules
Disabled Clean URLS

I found this helpful page on troubleshooting white screen on death in drupal which recommends adding code to the index.php to get information on the problem.

Following the instructions given there gave me the following error description:

Fatal error: Call to undefined function _date_api_element_info() in /home/sites/MY_DOMAINNAME.co.uk/public_html/sites/all/modules/date/date_api/date_api.module on line 2298

Based on this I assumed that the date module was causing the problem I disabled the date module on the original site and rolled the new site back to the basic Drupal install and imported the most recent databased backup. However I am still getting the same error message.

Both servers are set to execute scripts as PHP 5.3

I can appreciate that this is not an easily issue to reproduce. I would like suggestions as to sensible next steps to try to stop this error from occurring and complete the site migration successfully.

Issue solved.

I had not disabled all of the date sub-modules (Thanks Molot for making me double check this). I ensured they were all disabled, cleared caches and was then able to export the database and import it on the new server.

I did get some errors on the new install. Running update allowed me to see that workflow needed updating. Updating workflow and ensuring the right sub-modules were installed (You can't run Workflow Node and Workflow Field at the same time) fixed the other errors.

I was then able to re-enable the date module.


Where can I add core  elements with Views RSS I'm trying to set up a podcast feed with Views RSS. I think I've succesfully set up the module and the core <channel> elements.

I am now trying to set up the core <item> elements, as explained here. However, I have no idea if I'm looking in the correct place.

I go to admin/structure/views/view/gentle_podcast/edit/feed_1 and under Format I see:

Format: RSS Feed | Settings
Display: Fields | Settings

(I'm translating from Dutch, so labels may be off). When I click the Settings next to Display, I get a popup where I can set Title, Link, Description, Creator, Publication date and Guid.

How can I set all the other items that the documentation mentions?

Does it check the fields I've added to the view? Because I've added a field that has the URL of my podcast file (an mp3), but I don't see anywhere to set the <enclosure> item.

You can see the current result of my view here (as feed) and here (as page).

It sounds like you're missing a couple things. First, make sure that you have the Views RSS: Core Elements submodule enabled -- this is what allows you access to the many other fields. This may already be enabled and if so, the reason you're not seeing the fields is that you need to switch your format to RSS Feed - Fields, ex:

by clicking the 'RSS Feed' link in your Format Settings.

Now, when you adjust the settings for this, you'll see the options for the item elements you were looking for.

You'll need to add the appropriate fields from your content to have them appear in the select lists.


Views information not bolding used templates The templates used in my views are not bolded (template information). I do not know if this due to a module interaction.I have checked with different administration themes but does not show up anything.I would like to know how to get back this valuable information.

I have also tried an alternative solution that did not work. I have enabled the theme debug mode, and looked for the template used in the source code. It show the default template while i have a another (specific) one.

I have been looking around without any success!

I finally found out the issue. I was using Role theme switcher and i have selected a new theme to test it. It seems that this does not work well with my production theme, and this conflict between themes makes the views template bug.
I have disabled one of the themes and it works.
Thanks for your time


Complex Filter Criteria no Results I'm working on a views to show different events in a calendar. I want to be able to filter on terms (In my view the field is called 'Wat?' for terms like music, art, design, etc). For this I create a filter criteria with an exposed filter for these taxonomy terms.

When I filter on film, only the film items are shown, perfect!

But now I want to make a complex filter by using filter groups. In both groups I want to use this genre filter. So I add another one. But for some reason this doesn't work, when I select film on both dropdowns and click apply it doesn't work anymore, and no results are given. I created a simplified view to test this. Here are images of my filter, and the use of it.

This is my complex filter

Using one filter gives results

But when selecting the film in both I get no result

The problem of my above question is a core bug. I added it to the Drupal Core issues, hope it will be solved soon. https://www.drupal.org/project/drupal/issues/2935113

In the mean time I found a work around. I use two different filters in the two added groups. Both filter on the same thing.

So in group 2, I filter on my Wat? field.

In group 3, I filter with the 'Has taxonomy filter'.

Both filter on the same taxonomy term but because they are different filters it does work now.


How can I use entity save in drupal 8 I'm installed drupal 8 in local and created a content type named as  Project with minimal fields. And implemented form API to collect data in custom module.

Here how can I save the data as node content?
or How can I use entity save in drupal 8

if you only want save node type. You can use code example below

<?php

use Drupal\node\Entity\Node;
$node = Node::create([
  // The node entity bundle.
  'type' => 'article',
  'langcode' => 'en',
  'created' => REQUEST_TIME,
  'changed' => REQUEST_TIME,
  // The user ID.
  'uid' => 1,
  'title' => 'My test!',
  // An array with taxonomy terms.
  'field_tags' =>[2],
  'body' => [
    'summary' => '',
    'value' => '
The body of my node.
',
    'format' => 'full_html',
  ],
]);
$node->save();


How to process field input so b52 goes into database as B-52 Situation: D7 Text field on a content type.

User enters something like: b52

I want it stored in the database as: B-52

I have a function that does the regex. I just don't know where to process the input before it goes in the database.

Don't want to install Field Validation or do any validation forcing a User to "correctly" format their own data. I just want to catch their input, modify it, and save it in the database as so.

What hook do I use and can it be done in the theme?

OK figured it out.

hook_node_presave() is what I want and it can only be called from a module I think.

Found the answer here: node_presave doesn't work

function nodepresave_node_presave($node){
  drupal_set_message('nodepresave DEBUG: PRESAVE Called');
  if ($node->type === 'vehicle') {
    drupal_set_message('nodepresave DEBUG: node->type === vehicle');
    drupal_set_message($node->field_id_number['und'][0]['value']);
  }}


How to unlink the teaser title from the original content? I have a page having list of teasers populated using views for a certain content type. Now, I want the title of the teaser not to be a link to the original content/node. I want the title in same format but not to be a link. Please help if anybody know how to do it.
I am using Drupal 7.

On the view you are using, simply click  on the title field, and uncheck link field to original piece of content


Keeping unused elements? I keep a lot of unused elements that I don't bother to delete such as blocks, content types, views, taxonomies etc. Is there any speed benefit of deleting these unused elements? If so which ones?

It could help, yes. Your site will be faster, and easier to manage.

less elements means Drupal uses less memory
with less elements, it takes less time to read them all (unused elements are still active)


Create a link pointing to # I am trying to make a link pointing to # but am unable to find a method that works.

The output i would like to see is

Example

I have tried a few variations of the following without success.

$url = Url::fromUserInput('#');
$link_item = Link::fromTextAndUrl(t('Example'), $url);
return $link_item->toRenderable();

I have also tried using  ::fromUri etc and am unable to find a method that produces tehd esired output, please help.

It's probably not possible to attach an empty fragment. See this code in  UrlGenerator::generateFromRoute():

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

If the fragment is empty it is ignored and no '#' shows up. This doesn't change if you provide the fragment in Url::fromUserInput(), because the fragment is transfered to the options and later processed by the same or similar code.

So you have to provide an anchor in the fragment:

$url = Url::fromUserInput('#anchor1');

or

$url = Url::fromRoute('<current>', [], ['fragment' => 'anchor2']);

As alternative option you can place a link with an empty fragment

{{ examplevariable }}

either in a twig template or in an inline template in php.


How to list 5 most view nodes without using the Statistic module? I am trying to create a view/block of the most viewed node without using a module if possible.

If it's not possible, is it possible to do it without using the statistic module?

The simple and best solution which work with views is node view count. Which works with views and play around it.


is the a module similar to data_export_import that includes user roles? I am using the Data Export Import module to migrate data from my live site to my dev site.  It works fine in all cases except user roles.  For some reason, many (but sometimes not all) users lose the user roles that are assigned to them.  Is there a more advanced module that can handle an export-import of nodes and user (preserving node references and NIDs) which also migrates user roles?

If not, I am considering writing some rules to save and reset the roles as stated here:

Programmatically assign user role

I have never used Data Export Import, so I don't know whether it has special features or functions that you need for your use case.

For the use case of exporting everything (except file and media attachements) from my live site to my dev site, I use Backup and Migrate.

What it does is not in any way "advanced". It just mirrors the entire database, including content (nodes etc.), users and taxonomy terms. All references including NIDs are preserved, and user roles are also preserved.

There is nothing in your question that suggests that Backup and Migrate may not serve your use-case, but I may have overlooked something.


How to call a check for a product class in Ubercart In the Ubercart D7 uc attribute module I am trying to  run code on the fieldset attribute if the product is a specific product class in the module with an if statement.
This calls an  if  for payment received
      if ($op == 'update' && $order->order_status == 'payment_received' && $arg2 == 'completed') {
// ... your code goes here

}
How do I call it for a product class??
In uc_attributes module at
   function uc_attribute_uc_form_alter(&$form, &$form_state, $form_id) {
  //. other code of module's function...
    $element[$key]['#type'] = 'fieldset';
    //    if (product class . ..) {
  // ... your code goes here

So that only the validate code runs on the field set if the product is the same product class
I have rest of the code largely ready to go

The function to use is:
uc_product_is_product($node)

This returns a boolean variable indicating whether the node is a product type.


twig dump() creates WSOD error this is my first Drupal installation (I'm a symfony dev) and I've spent several hours trying to get dump() working. However it just causes a WSOD.
Maybe related: I'm unable to install kint, there's issues with it now being a sub-module of devel and I haven't been able to install it.
Settings:

Drupal version 8.9.1
memory limit set to 6,000mb
execution time set to 90 seconds
Windows
acquia dev desktop
php 7.3.15
Apache/2.4.33 (Win64) OpenSSL/1.1.0h mod_fcgid/2.3.9

If anyone has suggestions I'm keen to hear it! Drupal is quite interesting from what I've seen so far. It's been a bit frustrating as someone new to Drupal, trying to get basic things working.
== Update ==
I have corrected a config error I made while configuring the site. See here (for correct config).
Calls to dump() (in twig) for null variables work, but {{ dump(items) }} will hang and then result in a 500 error (see link above).

I've solved this.
In Drupal, modules also use composer (which I wasn't aware of). The vardumper module depends on the symfony/var-dumper package.
Running:
composer require --dev symfony/var-dumper
causes dependency conflicts, however using:
composer update
Will install the var-dumper package, fix the problem - now I can see very beautiful variable dumps.
Lesson learnt:

Always check composer for dependency errors.


How to output specific php depending on value of content type radio In my 'Basic page' content type I've added a yes/no radio field. Currently that is outputting as the value chosen. If yes is chosen I want to output a specific button, if no was chosen I don't want to output anything. How do I go about overriding the basic page template to achieve this?

--EDIT--
I don't want the radio option showing for the site visitor, only for the content editor. I want either the button or nothing showing to the site visitor.

By using @Neograph734's advice I did use conditional fields.
Within the content type structure I added a field a link field(the button I wanted to conditionally show). Then used the conditional field to show this link when needed.


How can I import fields into Drupal 8.4 user profile from a csv file that has identical values in the key row? I'm using Migrate Tools, Migrate Plus and Migrate Source CSV. My CSV file looks like that:

"Stg";"Color";"Fruit"
"user1";"red";"apple"
"user1";"blue";"pear"
"user2";"green";"banana"
"user2";"black";"rotten banana"

I'm using the Profile Module (https://www.drupal.org/project/profile)

I have a migration within my migration group that looks like this (migrate_plus.migration.user_vorlesungen.yml):

id: user_vorlesungen
langcode: de
status: true
dependencies:
    enforced:
        module:
            - user_migrate
migration_group: hoevwa
label: 'HoeVWA Vorlesungen Import'
source:
    plugin: csv
    track_changes: true
    path: /config/Vorlesungsverzeichnis.csv
    # Column delimiter. Comma (,) by default.
    delimiter: ';'
    # Field enclosure. Double quotation marks (") by default.
    enclosure: '"'
    header_row_count: 1
    keys:
        - Stg
destination:
    plugin: entity:profile
process:
    type:
        plugin: default_value
        default_value: 'vorlesungen'
    uid:
        plugin: migration_lookup
        no_stub: true
        # previous user migration
        migration: user__hoerer
        # property in the source data
        source: Stg
    # These field have multiple values in D8
    field_color: Color
    field_fruit: Fruit

migration_dependencies:
    required: {  }
    optional: {  }

In my YAML file the content is printed like that:

...

    {{ content.field_color }}
    {{ content.field_fruit }}

...

When I run drush mim --group=hoevwa only the last values of user1 (blue, pear) are imported. How can I get running a process plugin to loop through the CSV and get all values imported. And finally how can I loop through all values in my TWIG Template?

The solution will be to create a custom Migration Source Plugin and do some magic in the fetchNextRow() method. Depending on the source of your data, you might also use some other approach.


Understanding `file_managed` table I am trying to understand the Drupal database schema because I need to access the database via MySQL by another system and I do not have access to the original Drupal developer of the site nor do I know Drupal well at this point (I did work with it 8 years ago) and it will be much easier to access with MySQL than to set up a server to have to host a PHP-based API or similar.

file_managed

In the file_managed table there is a field uri where the data all appears to be in the same of two formats:

public://<filename>, OR
public://<directory>/<filename>

My two questions related to file_managed are:

What is public:// mean here?  Does it translate to some root URL like http://example.com/files or similar?
When there is a directory in the uri, what do they represent?

UPDATE: I do not have access to the working Drupal system, I only have access to the database.

I am just going to answer your first two questions (about file_managed).  Please ask a separate questions for the second set (about file_usage) and about the relation between the tables.

  What is public:// mean here? Does it translate to some root URL like http://example.com/files or similar?

Navigate to Administration » Configuration » Media » File system. Take a look at the value for "Public file system path" (default is sites/default/files).  this is the path to public:// from your site root.

  When there is a directory in the uri, what do they represent?

The path below the public file system root.

So, given the that the public path is the default, public://foobar/image.jpg, this expands to the path sites/default/files/foobar/image.jpg, or the URL  http://example.com/sites/default/files/foobar/image.jpg


Force redirect from HTTPS to HTTP in Drupal 7 Multitsite? I'm trying to serve a Kaltura video running on CentOS 6+ on one server, by plugging the Object code for embedded video inside a node body (or even using the Kaltura Drupal module), running on a Drupal 7 multisite on Ubuntu 10.04LTS.

Most browsers accept it but Chrome, which denies the request as being insecure content. We serve all our D7 sites on HTTPS, forced redirect. But now I want to only serve ONE of the multisite as HTTP so that it could show this Kaltura video, and not have Chrome hiccup.

Here's what I have in the .htaccess file of the D7 parent directory.

RewriteCond %{HTTPS} off
RewriteCond %{Request_URI} !^(/mysite/user)
RewriteRule ^(/.*) http://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301]

I've tried the Secure Login module, as well as the very close suggestions here - Redirect /user/login to HTTPS, all other requests to HTTP, to straight mode rewrite on apache - https://stackoverflow.com/questions/1816119/using-mod-rewrite-how-do-i-force-https-for-certain-paths-and-http-for-all-othe - and nothing makes sense.

Note: Not a mod-rewrite expert, but I now feel this is somehow attributed to not doing something correctly with Drupal. Currently, when you visit http://mydomain.com/mysite/user - I get this message:

You are accessing <mysite> using an unencrypted connection. For your
security, <mysite> only supports account logins using
a secure protocol such as HTTPS.

I believe this is a very popular question, but didn't really see anyone else trying to go from secure to insecure on multisite. Please advise. Thanks,!

Maybe you should try and and change the object embed code code to use a protocal-relative URL such as //YOURSITENAME.COM/some/path/to/video/file.mp4 you can do this easily with a WYSIWYG editor or like hook_node_view and regexing for your domain url and an object tag and removing the http:// or https:// as needed ...

Simply google for protocol-relative url and you'll find a bunch of information.


hook_update_n($sandbox) batch getting executed only once Following is the code where I'm willing to update the description of the field_meta_tags of all my products using the batch process.

It's getting executed & working as expected, but only for the first batch.

function mymodule_update_8001($sandbox) {
  if (!isset($sandbox['total'])) {
    $products = \Drupal::entityQuery('commerce_product')
      ->condition('type', 'default')
      ->execute();
    $sandbox['total'] = count($products);
    $sandbox['current'] = 0;
  }

  $products_per_batch = 25;

  $products = \Drupal::entityQuery('commerce_product')
    ->condition('type', 'default')
    ->range($sandbox['current'], $sandbox['current'] + $products_per_batch)
    ->execute();

  foreach ($products as $product_id) {
    $product = Drupal\commerce_product\Entity\Product::load($product_id);
    $product->set('field_meta_tags', serialize(['description' => '']));
    $product->save();
    $sandbox['current']++;
  }

  \Drupal::messenger()
    ->addMessage($sandbox['current'] . ' products processed.');

  $sandbox['#finished'] = empty($sandbox['total']) ? 1 : ($sandbox['current'] / $sandbox['total']);
}

Once the above hook_update_n($sandbox) is executed, getting the following output at the terminal:

 --------------- ----------- --------------- -------------
  Module          Update ID   Type            Description
 --------------- ----------- --------------- -------------
  mymodule        8001        hook_update_n   Updates.
 --------------- ----------- --------------- -------------

 // Do you wish to run the specified pending updates?: yes.

>  [notice] Update started: mymodule_update_8001
>  [notice] Update completed: mymodule_update_8001
>  [notice] Message: 25 products processed.
>
 [success] Finished performing updates.

Not sure how $sandbox['#finished'] is getting the value as 1, since that's how I remember we ask the batch to stop processing.

There is no need for batches if you intend to run all entries in one process.

This is something we had use to update around 30.000 entries i quickly adapted from your example :

/**
 * Query all commerce_product of type default
 *
 * *
 * @param array $sandbox
 *
 * @return string
 *  Number of updated rows
 */
function mymodule_post_update_0801(array $sandbox) {
  /** @var $connection Drupal\Core\Database\Connection */
  $connection = \Drupal::service('database');
  $query = $connection->select('commerce_product', 'p');
  $query->fields('p', ['id'])
    ->condition('type', 'default');
  $toUpdate = $query->execute()->fetchAll();

  $result = array_map( 'update_description_value', $toUpdate);

  return sprintf('Number of row updated: %s', count($result));
}

/**
 * Update a product description
 *
 * @param stdClass $defaultProduct
 *  ->id
 *
 * @return string
 *  product id
 */
function update_description_value($productQueried) {
  /** @var $connection Drupal\Core\Database\Connection */
  $connection = \Drupal::service('database');

  $updated = $connection->update('commerce_product')
    ->fields(['field_meta_tags' => serialize(['description' => ''])])
    ->condition('id', $productQueried->id, '=')
    ->execute();

  return $productQueried->id;
}

Let me know if there is typo somewhere.


How to add Colorbox to a field in a twig template? I have a site with various products on it. So I created node--product.html.twig. I then removed this from my twig template:

{{content}}

Because I want to display fields myself in a custom format, without relying on Drupal's built-in display. So for the most part this was easy, as I could do this:

<img src="{{ file_url( node.field_product_images.0.entity.uri.value | image_style('shop_thumb_400_x_400')  ) }}" alt="" />

This works perfectly. But my problem is that I want the user to be able to click on this image and see it in a modal view, but USING the Colorbox module.

Is there another way to output this field in the twig template so that it automatically loads colorbox and everything that is needed?

You really would want to use:

{{ content.field_product_image }}

The field display setting will pass the image style to it, and I assume colorbox has a field formatter or tie in here as well. Supply a field Twig template to strip extraneous markup divs.


How To Display YouTube Channel On Page I'm attempting my first Drupal site and would like to show a simple listing of the 5 most recent YouTube videos submitted (http://gdata.youtube.com/feeds/api/standardfeeds/most_recent?max-results=5).  I've been struggling with this for almost a week now and cannot get what I want.

I've tried Feeds and the YouTube parser and I've tried the Media Module as described here.  I can get the 5 most recent videos imported as separate nodes, but I want to just be able to list them, embedded, on the single page.

Any help would be greatly appreciated.  I'm new to Drupal and really looking for a walk-through at this point.  I'm using Drupal 7.19.

Thanks!

Did you try Aggregator? It's the first one listed on the modules page then on the configuration page it's call Feed Aggregator.

I then use Views to style my results.

Hope this helps!


When creating content with new term, show all term fields for input also Taxonomy terms are clubs and there are many in vocabulry, with fields to enter address, long/lat etc.

User adds content Concert and can pick a club (terms) from Simple Hierarchical select.
If club is not in vocabulary user can add new term. While doing this he should also be able to input fields for new term (address, long/lat) while creating content.

How can i achieve this ?

You can use combination of two modules. First is Entity Reference, where you have to create your taxonomy term reference field. Then install module Inline Entity Form and use widget Inline entity form - Multiple values (in number of values of this field select: 1).

In node create form you will have then field, where you can select from existing terms (autocomplete) and also you will be able to create new term, if term does no exists - this will create inline form, which would have all fields specified in taxonomy vocabulary structure (see image below).

If you select existing term, or create new, it will looks like this:


Multi-value form widget in a system settings form I'm building a form for a modules configuration page. The last line of the form callback is the following:

return system_settings_from($form);

I want to add a textfield to the form, but I want to be able to enter multiple entires into the field using the same widget you get when manually creating a field of this type (where cardinality > 1) where you get the text field with an "add another item" button.

How can I use that type of widget in a form for a module configuration page?

You won't be able to use the multi-value functionality used in the Field API in your custom forms.

However, with the Form API and Ajax you should be able to create dynamic form fields. See Ajax Example in the Examples for Developers project. What you want to achieve here is relatively similar to Generate textfields and Generate checkboxes examples, where fields are being added to the form on-the-fly.

<?php
/**
 * Form manipulation through AJAX.
 */
function ajax_example_autocheckboxes($form, &$form_state) {

  // Since the form builder is called after every AJAX request, we rebuild
  // the form based on $form_state.
  $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;

  $form['howmany_select'] = array(
    '#title' => t('How many checkboxes do you want?'),
    '#type' => 'select',
    '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
    '#default_value' => $num_checkboxes,
    '#ajax' => array(
      'callback' => 'ajax_example_autocheckboxes_callback',
      'wrapper' => 'checkboxes-div',
      'effect' => 'slide',
    ),
  );

  ...

  for ($i = 1; $i <= $num_checkboxes; $i++) {
    $form['checkboxes_fieldset']["checkbox$i"] = array(
      '#type' => 'checkbox',
      '#title' => "Checkbox $i",
    );
  }

  ...

  return $form;
}

/**
 * Callback for autocheckboxes.
 *
 * @return array
 *   Renderable array (the checkboxes fieldset)
 */
function ajax_example_autocheckboxes_callback($form, $form_state) {
  return $form['checkboxes_fieldset'];
}

Another, quick solution that may work (or not) for your case is using an entity (e.g. a single node of a new content type) to store that configuration.


How to get the media title and url to the media entity I have a media file field field_file where the data is saved like:

title: Media Entity 01
file: media_entity_01.pdf

Using twig, is it possible to output the title of the file and the path?

When rendering the full entity using the 'Render Entity' display mode, I can only get the display to output something like this:

media_entity_01.pdf
using twig like this:
{{ content.field_file }}

when i want it to output like this:

Media Entity 01
using something like this:
{{content.field_file.GET_THE_TITLE}}

Is this possible?

Cheers

Got it figured out. Steps:

In Structure > Media Types > File > Manage Display, set the format as Generic File, click the gear icon, and turn on Use description as link text.

Next, inside of Structure > Media Types > File > Manage Fields, edit the field_media_file field and make sure the checkbox for Enable description field is checked. Now, when creating a media file entity, there is a description field that can be filled and will display as the link text.


Drupal Content Access Control Exploring Drupal, so still lot of unknowns.

Drupal 7 out of the box can do the following :

Authenticated users can create/edit/delete "their own" article content. - works out of the box
Admin can create/edit/delete "any" article content - works out of the box.

Wondering if Drupal 7 out of the box can do the following?

Authenticated users can "only" view their "own" article content. I only see the option "View Content" but it seems to be for "any user". So when the "auth user A" creates an article it's available for "any" user. Is there a way to restrict view. This goes for both published and un-published article.
Does the access control extends to any content types as per above or custom code is required?

Thank you for your clarifications.

Out of the box, no it does not. For that you need to use an add-on module:

Content Access Control Modules

  All the modules that implement an access control system.

Information on Access Control Modules
A web search for 'drupal access control' will yield thousands of sites, tutorials, videos and other useful information.


How to make user profiles searchable and filterable by multiple fields in the context of a job site I'm currently in the process of developing a job search site hopefully with these abilities for users of the site:

Job seekers can search for and filter jobs. I'm on my way with this so no problem here.

However what I would like to do is create users searchable for employers. So users can sign up and fill in a number of fields, expertise, CV, skills or whatever else...

Then I want users with paid employer accounts to be able to search and filter employees by these fields.

I'm fairly new to Drupal and I was wondering how I would go about doing this?

I think you're going to need to use views here.

When you create your view, make sure you use Users and not Content. See screenshot. Once you do this you can set up and expose all the filters you need to allow searching, etc.


Sample Images not showing (Omega Kickstart theme) Sorry for this beginners question:
I made a fresh installation of Drupal 7 and then installed "Omega Kickstart" theme by copying the zip-isntallation-link under http://drupal.org/project/omega_kickstart

However, the file is only about 300 Kbit and indeed there is no sample images showing - in fact only one logo changed on my startpage and a slightly different formated text.

Is it possible to install the theme with all the sample-images and modules?

The Omega Kickstart is just a theme; it doesn't contain any module. You are probably interested in the Commerce Kickstart distribution, which contains the Drupal Commerce module, and any of its dependencies.

  Commerce Kickstart is the quickest way to get up and running with Drupal Commerce. It includes the latest versions of Drupal core, Drupal Commerce, and the other modules it depends on. It also gives you a set of options to create a fully-featured demo store out of the box complete with an attractive theme, catalog and search configuration, and a custom back office interface.


Redirecting after login for specific roles I want to redirect specific users after a succesful login but I can't make it work.
Here's my code:

function concessionaire_login_user_login(&$edit, $account) {
foreach ($account->roles as $role){
    if($role == "administrator"){
    } else if ($role=="concessionnaire"){
        global $language;
        unset($_REQUEST['destination']);
        unset($_REQUEST['edit']['destination']);
        $url = "http://www.my-site.com/myfile.php";
        $options = array(
        'query' => 'id_rub=14&lg='.$language->language
        );
        drupal_goto($url,$options)

    }
}

}

I tried also with header('location: $url'), but it doesn't work either. Login_destination module was my first guess but I can't use variables..

Also is it possible to redirect to an external URL and passing POST parameters at the same time ?

Thanks in advance.

Some things to look at:

'query' itself needs to be an array, not a string, eg...

array('id_rub' => '14', 'lg' => $language->language)

and if you want to call header() directly, you need some more parameters:

header('Location: ' . $url, TRUE, $http_response_code);
drupal_exit($url);

(and an exit for good measure...btw, that's all drupal_goto() is really doing anyway)


How to use checkbox under description of any webform field? I am using webform module where I have a text field named Mobile Phone Number.

I wanted to use checkbox under the text field as shown below:

The content can be written in the description of that text field. But how do I use the checkbox as I shown above.

Note: I tried to enter the html form tags in the description but didn't help.

You will create a check box component fields below mobile phone number fields after "yes|I am providing my express..." in OPTIONS .
   Create Check box -> Options -> "yes|I am providing my express..."

and align with CSS code


How do I programmatically switch theme? I want to switch theme on the basis of URLs and roles. I have used hook_custom_theme() but it's working only on the frontend.

Is there a way to switch theme basing on the URL for every page?

The reason it works only for the frontend pages is that:

The System module implements hook_custom_theme() using the following code

function system_custom_theme() {
  if (user_access('view the administration theme') && path_is_admin(current_path())) {
    return variable_get('admin_theme');
  }
}

The function that invokes that hook has the following code

$custom_themes = array_filter(module_invoke_all('custom_theme'), 'drupal_theme_access');
if (!empty($custom_themes)) {
  $custom_theme = array_pop($custom_themes);
}

In other words, the theme selected is the one returned from the last hook invoked, which in your case is system_custom_theme().
If you want that your module always sets its own custom theme, even for administrative pages, you need to tell Drupal to execute your hook implementation for last.

function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'custom_theme') {
    // Move mymodule_custom_theme() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

As side note, since the module would be override the theme set in admin/appearance, the module should give an indication of that in that page.

As for using the Themekey module, that module doesn't override the theme for the administrative pages, since its hook implementation (themekey_custom_theme()) contains the following code.

  // don't change theme when ...
  if ((in_array('system', variable_get('themekey_compat_modules_enabled', array())) || !(variable_get('admin_theme', '0') && path_is_admin($_GET['q']))) // ... admin area and admin theme set
     && strpos($_GET['q'], 'admin/structure/block/demo') !== 0 // ... blocks demo
     && strpos($_SERVER['SCRIPT_FILENAME'], 'cron.php') === FALSE // ... during cron run executed by cron.php
     && strpos($_SERVER['SCRIPT_FILENAME'], 'drush.php') === FALSE // ... during cron run executed by drush
     && (!defined('MAINTENANCE_MODE') || (MAINTENANCE_MODE != 'install' && MAINTENANCE_MODE != 'update')) // ... during drupal installation or update
    ) {
  // …
}

The comment reads as "don't change theme when admin area and admin theme set." I would rather do what the Themekey module does, but since you are trying to set the theme in any case, the Themekey module would not work for your case.


Current search block: edit (-) link I'm using search api and solr, with facet api.
If I display a "current search block", if I click on a facet the system add to the block a "(-) facet name", and if I click to "(-)" it removes the facet from the search.
Is there a way to theme this behaviour? I want to display it as an image.

Look at theme_facetapi_deactivate_widget function in facetapi.theme.inc. Of course, you can override it in your theme.


How to create custom rule event I'm working on integration of my D7 module with Rules. I have custom SQL table with 2 columns node_id and status. Status may have values 0, 1, 2, 3. How can I create event with hook_rules_event_info to react on status change? I.e. status changed from 0 to 1 -> send email to node owner.

If this is a formal drupal node you can use node update event , then check if the node->status is changed or not (you have 2 versions of node in this event one referring to unchanged and second refers to changed noge)


Create RenderArray of Field In my theme_preprocess_taxonomy_term function I am loading a node.
Then want to move its "body field" to the content array of my template.

    mytheme_preprocess_taxonomy_term(&$variables){
        $import_content_node_id = 32;
        //load node
        $import_content_node = $node = Node::load($import_content_node_id);
        variables['content']['body'] = $import_content_node->getFields()['body'];
}

This does not work because variables['content']['body'] is NOT a render array.

But from where I get the render array?
Or how do I create one from an by script loaded node?

You can use the method view() of the field.

Example, to get the render array of the body field as configured in the viewmode full:

$renderarray = $node->body->view('full');


How can I insert a comment form into my view? In Drupal 7, I'm building a module that has a view page that lists all nodes of a certain type. I want users to be able to comment on each node in the view from this view page.

I tried using hook_node_view but it only seems to apply to the full node page view. What kind of hook do I need to get the comment form of a node in a view?

What I know? That you can use the view.tpl.php file and add:

<?php
print drupal_render(drupal_get_form("comment_node_**content_type_machine_name**_form", (object) array('nid' => **$node->nid**)));
?>

Change the bold according to your node object and the content type machine readable name.

I think this link can help you too. and I suggest to check hook_views_pre_render Here which can do it but I didn't try it before.


Completing commerce order triggering other modules rules checkout complete i've coded a checkout complete but aint triggering other modules checkout complete rules, i'm assuming commerce_checkout_complete($order->order_id); will do this.

The most important thing for me is that, the items on the cart are files, hence i have commerce licence that grant license to each files which is not triggered by the code below. Any tips on how to do this please?

Thank you very much.

<?php
    function custom_module_complete_order($order_id) {

     $order = commerce_order_load($order_id);

     commerce_order_status_update($order, 'checkout_checkout');

      $payment_method = commerce_payment_method_instance_load('commerce_payment_example|commerce_payment_commerce_payment_example');

      $transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
      $transaction->instance_id = $payment_method['instance_id'];
      $transaction->amount = $order->commerce_order_total['und'][0]['amount'];
      $transaction->currency_code = $order->commerce_order_total['und'][0]['currency_code'];
      $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
      $transaction->message = 'Name: @name';
      $transaction->message_variables = array('@name' => 'Commerce Cartmaker Payment');

      commerce_payment_transaction_save($transaction);
      commerce_payment_commerce_payment_transaction_insert($transaction);

     commerce_order_save($order);
     commerce_checkout_complete($order->order_id);
}
?>

Updating to checkout_complete status, make the code works. Thanks.

+     $order = commerce_order_status_update($order, 'checkout_complete');
      commerce_order_save($order);
      commerce_checkout_complete($order->order_id);


How to get first submenu item path? I need to create a link to first submenu item from specific menu. The link will be placed in custom block.

To be more precise, I have a menu with following structure:

parent-menu
 item-1
 item-2
 item-3
 ..

I need that after clicking "parent-menu" user would end up in item-1 page. Also, there will be several links in some blocks, linking to "parent-menu" - they need to open 'item-1' item too.

My current approach is to create 'parent-menu' page template override which finds top child item from 'parent-menu'. That page will be linked from content and main menu.
Problem is that I need a way to find first menu sub item from code.

UPDATE:

Ended up on using query:

$link_path = db_select('menu_links', 'n')
->fields('n', array('link_path'))
->condition('n.plid', '269', '=')
->orderBy('weight', 'ASC')
->range(0, 1)
->execute()
->fetchField();

Is there any alternative way to do this, without querying database?

I found this module Menu Firstchild maybe it will do what you want it to do.


How to create a single slideshow combining several image fields? I have 3 image fields in a content type: img1,img2 and img3. img3 is multi valued while the rest are single valued, and I'd like to create a single slideshow containing img1, img2 and img3 to be showed on every node of that content type.

I tried using views slideshow with as block with contextual filters and managed to select images from a node correctly, but they weren't displayed properly as a slideshow.

The reason I'm not simply using one image field to make things easier is that I'm using the Custom Formatters module and I have problems with using just one field with that module:

Custom formatter for a multi-valued field

<?php if ( ($image_slide == 'true') ): ?>

                <?php while ($img_count < $counter) { ?>

                                <a class="bwWrapper single-image link-icon" href="<?php print $node_url; ?>">
                                    <img src="<?php echo file_create_url($node->field_image['und'][$img_count]['uri']); ?>" alt="" >

                  <?php $img_count++; } ?>

        <?php endif; ?>

Put something like above snippet in your node.tpl.php
This will create links of images and their links if any. Then apply normal css/js to make it in slideshow