How to change error-message displayed @ failed form-element validation to be different than the element's '#title" text? I'm writing a custom form module.

Using Drupal7's FormAPI, I create a checkbox, the label/text diplayed next to it is set as described here

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#checkbox

with the #title property,

    $form['test'] = array(
    '#type'     => 'checkbox',
    '#title'    => t('This is the text that gets displayed next to the checkbox'),
    '#required' => TRUE,
    );

which then displays in the browser,

[ ] This is the text that gets displayed next to the checkbox

Ih there's an error in submission that involves that checkbox, e.g. in the example above being required but not being checked, an error box is shown across the top content-area that says

"X  The This is the text that gets displayed next to the checkbox field is required"

I want to change that displayed error message to something other than the label/text.  For example, on error,

"X  Selecting the displayed checkbox is required."

or

"X  You forgot to check the required checkbox.  Please try again."

How do I set the error-message text to be different that the assigned label/text?

Using a basic form in a custom module:

    function customform_demo($form, $form_state) {
    $form['test'] = array(
        '#type' => 'checkbox',
        '#title'    => t('This is the text that gets displayed next to the checkbox'),
        '#required' => TRUE,
    );

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

    return $form;

}

You can set a custom error message in the form validation function. Here is a basic example with some comments:

    function customform_demo_validate($form, &$form_state) {

    // Test for existing form errors
    if (form_get_errors()) {

        // Save errors
        $form_errors = form_get_errors();
        $drupal_errors = drupal_get_messages('error');

        // Clear form errors
        form_clear_error();

        foreach($drupal_errors['error'] as $key => $error) {
            if (in_array($error, $form_errors)) {
                // Unset form errors
                unset($drupal_errors['error'][$key]);
            }
        }

        // Rebuild drupal errors
        foreach($drupal_errors['error'] as $key => $message) {
            drupal_set_message($message, 'error');
        }

        // Validate form field and set error message
        if ( $form_state['values']['test'] === 0 ) {
            form_set_error('test', t('You forgot to check the required checkbox. Please try again.'));
        }

                // Add more validation tests and error messages

    }
}


Have the '@domain.com' part of the email fixed I'm using the email registration module so that users can log in using their email address. The users are all from the same company, so I want to know if there's a way to have the '@company.com' part of the email as fixed text, like those grayed-out input fields. Someone knows if it's possible?

EDIT:
I'm hoping to have something like this.

You can achieve this using the hook_form_alter API. Alter the email field with something like $form['field_email']['#default_value'] = '' . '@company.com';

That will always append the @company.com to each email entered.


How to create custom menu link wrapper function in Drupal 7? As you know default wrapper for menu item in Drupal 7 can be modified via function theme_menu_link().

by overriding

theme_menu_link($variables) {}

function we can modify the rendered html output of menu link but it will change all of menu items that their #theme attribute is set to this function. for example in main menu, each item has menu_link__main_menu value in it's #theme attribute.

Now I want to create a custom wrapper function in my theme.

I searched and I found I must create a function with structure like

theme_menu_link($variables) {}

and also I must REGISTER the function name in my theme.

For registration, I used function theme_theme() {}

function theme_theme() {return array('custom_menu_item_wrapper' => array());}

** theme is replaced by name of theme
** custom_menu_item_wrapper is the name of my function for wrapping operation

But I don't know, how should I define parameters in theme function registration because when custom_menu_item_wrapper($variables) function is called $variables is NULL

Indeed, you need to register a new theme implementation. Looking about the specification of the hook_theme(), each information array must contain either a variables element or a render element. This is missing in your case and causes the empty $variables argument.

function YOURTHEME_theme()
{
    // define a custom theme implementation
    return array(
        'menu_link_custom' => array(
            'render element' => 'element',
        ),
    );
}

function YOURTHEME_menu_link_custom($variables)
{
    //Build and return custom HTML for your link
}


The node form will not submit,if the word 'exit' is put in the title field I am using Drupal7, if the word 'exit' is entered into the text field, and the user submits/saves/previews the page, then the data is not submitted, saved, or previewed. The node edit page reloads and all changes are lost.

Is the word 'exit' a blacklisted word in node add/edit form?How can i over ride this prob?

Thanks in advance, Prem

No, Drupal doesn't have any word blacklists.

That logic must be caused by a custom or contributed module that you have installed (or even a theme I suppose). Try methodically disabling modules/themes until you find the culprit.

Starting with modules that provide text filters or alter the content body in some way would be the obvious places to start.


Twig Filters and Text Format Filters I've implemented a custom Twig filter that wraps certain character sequences with a span. The span element didn't show up in the front end until I allowed it in the text format for the field in question (via Limit allowed HTML tags...), so it seems that Twig filters are applied before text format filters. For my current use case, it seems like it would make more sense to run Twig filters after text format filters. Assuming I'm understanding this correctly, is there a reason this is the intended behavior? And if so, is there a way to change when Twig filters are applied to a field/format?

I ended up solving this by running the field through the render filter first, then my custom filter. The text format filters are applied at the render stage, so now the custom filter runs after them. The finished order is:

{{ field | render | custom_filter }}


How to hide revisions tab in quiz module? I am using quiz module in one of my project.

The module seems to be excellent and it satisfies all my need.. thanks to the development team... http://drupal.org/project/quiz

In the mean time i need to do one additional task. And i am struggling  with it..

There is a tab called "Revisions" which will be enabled when some updates are done.

According to my criteria the "Revisions" tab should be hidden always... Is there any way to do this...

Thanks in advance..

It is provided by the Diff module: Disable the new check-box on workflow settings, "Enable revisions page."


Pass variable from function to template I want to pass a variable from a mymodule_preprocess_node(&$vars) to my template file.
Something as simple as the following:

function mymodule_preprocess_node(&$vars) {
  $vars['node_type'] = 'some_type';
}

I trying to pass this variable to a zone--content.tpl.php file.

PS: Cleared all the caches :)

To pass variables to the zone template, you need to preprocess the zone, not the node

function mymodule_preprocess_zone(&$vars) {
  $vars['node_type'] = 'some_type';
}


How do I hide the real filename? I managed to "hide" files using "private folders". The problem with this is that, when I upload an image called "cat.jpg", it will appear in the file system as "cat.jpg". If I then try to view it, the URL will be something like /system/files/styles/medium/private/cat.jpg?itok=fDHu1Q5k.

Is there a way to obfuscate the name, so that it will instead be something like /system/files/styles/medium/private/2342343534532122.jpg?itok=fDHu1Q5k?

To be clear, I want whoever uploads the file to be able to upload it as "cat.jpg". When it hits the file system, it must still be stored as cat.jpg. Only when it's opened displayed as URL, must the filename be changed. Yes, I know, changing the filename on upload would probably be easier, but there are just too many already uploaded files for me to consider this route, and I still want to be able to browse through the files on the filesystem using the original names.

You can use apache module mod-auth-token (https://code.google.com/p/mod-auth-token/) to generate a one-time url. Please refer to the documentation for more specific instructions (there is both apache configuration and php example how to use it).


Form won't submit properly on the front page I have placed a form on the front page of my Drupal 6 site using drupal_get_form('mymodule_form'). I have not done anything different than usual, and I have implemented a validation handler called mymodule_form_validate().

The form displays properly, and posts to '/', as it should. I have put a form_set_error() into the validation handler to test that it is working. The validation handler is never hit when the form is submitted.

However, if I use drupal_get_form() to put the form on an internal page, it works as it should.

What is going on here? Is there something that is preventing forms from being used on the front page of a Drupal site?

I have discovered that I needed to make sure the form did not submit to the front page. I needed to set up a custom path for #action on the form, and make sure there was a callback defined in a module.

When landing on that callback, the validation and submit handlers successfully fire. I can then redirect users back to <front> if they are successful. The downside is that on error, there needs to be a separate page where the form is displayed. I couldn't find a way to show the error on the front page itself.

This is good enough for what I need. Thanks for the suggestions in the comments.


Do I have to activate a parent theme when I activate its sub theme? A sub theme relies on its parent. Does that mean I always have to activate both of them?

No it doesn't. As long as the base theme is present, that's OK.
As an example, if you test the Sky theme on Simplytest.me and go to the admin/appearance page, you'll see that Sky is enabled, but the base theme (AdaptiveTheme) is not.


Logging into Drupal 7 site with headless browser: why would it fail? NOTE: I've heavily revised the wording of my question to focus more clearly on the problem.  There's a ton of really really useful information in the answers below, but not all of it applies to solving the problem of logging in with a headless browser.  (Feel free to view the edit history for more details, as well as a more verbose version of the same info.)

I'm using a headless WebKit browser (from CasperJS to log into my Drupal 7 site, and it is failing for unknown reasons.  I first used the Ruby version of the Mechanize library and got identical results: access denied even after filling out and submitting the log in form.  I'm pretty sure the problem has to do with Drupal, and some failure on my part to jump through some hoop (that is probably there to prevent spambots and such from submitting to Drupal-based sites).

Since my script loads the log-in form before submitting it, AFAIK it should work just like a normal user logging in.  I've looked through the methods mentioned in the answers that details Drupal's form-submission process, but I'm not seeing what would cause my problem.

This question seems to provide clues, though it is D6 and using curl.  That person is passing field_source, form_token, form_build_id, and form_id as fields.  In my form I only see form_build_id and form_id. Should I be passing all those fields, even though they don't seem to be present in the login form?  Drupal seems to look for form_token, but it's not present on my login form.  What's up with that?

NOTE: Someone will undoubtedly ask why I'm using these tools when there must be better ways with such-and-such a Drupal module, and the short answer is just that I chose to use tools I'm most familiar with.   If you have good module suggestions please leave comments (with implementation details if possible) as I'd love to hear the suggestions, but I'd still appreciate an answer to this question as it is asked.  Thanks.

Is there some security feature built into Drupal to prevent
  submissions by scripts?

Yes, there is.

In order to prevent automated form submission by bots etc.. During form build Drupal generates a token, based on session id, and a unique id, for form cache. These are used during form validation.

See:

drupal_prepare_form
drupal_get_token
drupal_validate_form
form_get_cache

In order to successfully submit the form, you would need to retrieve it and then submit it using the same token and form_build_id values.

However, there are other ways to submit forms programmatically, such as

drupal_form_submit

As well as purely code based methods to log a user in.

e.g, in a very simple form:

// Load a user account and assign to global $user
global $user;
$account = user_load(1, TRUE); // Root user
$user = $account; // This "logs" the user in
drupal_session_regenerate();
// Invoke login event
$edit = NULL;
user_module_invoke('login', $edit, $user);


Is there an easy way to have an image in a radio button label? I have a dynamic list of images, that I want to have a user select via associated radio button in a form. Is there an a way I can do this with the base form api, or is this the kind of thing I'd need to create a custom theme for?

You can do this using CSS.

Add appropriated class from $form then use CSS to add images as background-image.

For example:

$form['example'] = array(
  '#type' => 'radios',
  '#title' => t('example'),
  '#default_value' => 1,
  '#options' => array(0 => ('Value 0'), 1 => ('Value 1')),
);

CSS

.form-item-example > labela[for=edit-example-0]{
      background-image: url('/path/to/image-0.png');
}


How to load entity by UUID from url argument? Usually routes have the {entity_type} argument in their path and Drupal loads the entity by the ID that is the url argument. For example route defining /node/{node} would work with /node/5.

I need to load the entity not by it's ID but rather UUID. So the path would look like /node/0ff3b31b-5abb-4377-bb00-af71882e38a4

Is it possible to load the entity by UUID by defining some sort of mapping in the route definition or do I have to create my own ParamConverter for this?

Yes, you need your own param converter for this, the default implementation can only load by UUID.

Loading by UUID is less performant as long as the primary ID is still a serial ID, this means that it first needs to do an entity query to fetch the ID and then load that.


Can I add more blocks in a View page? I have a page that I created by View, I tried to create a template by creating node--view_page_machine_name.tpl.php, but it didn't work, the page did not change to this new template style.

How can I add more blocks/regions into a view page? Thanks.

In your view, under advanced there is a link called "Theme Information". If you open that up, there will be a list of all the different parts of the view that can be themed and a list of all the theme suggestions for each listed in order of broad to narrow.

You can create a theme file and naming it appropriately from the list of files in the theme information section. Once you've created the file, click on the "Rescan template files" button and the file you've created should be bold in the list.

Save the view and clear the cache.


How to pull twitter feed in content type? I need to create content type(twitter content ) where i can pull twitter feeds so that i can use that content type for entity reference and print the twitter feeds.

Can any one please help or assist me how pull twitter feeds in custom content type?

For this you have twitter block module in drupal 7 , but you want content type for this make node--twitterfeed.tpl.php  template  and put your api script like this

Tweets by @InstaSnapShop

also check https://www.drupal.org/project/twitter_block


Prevent Cross-site scripting One of the security principles is sanitizing strings and variables passed from client to server. In plain PHP there are some functions to prevent XSS (Cross-site Scripting) vulnerabilities:

htmlspecialchars()
strip_tags()

What is Drupal 8 strategy to prevent XSS  attacks? How can I clean up client data post to protect my site from XSS attacks?

I remember Drupal 7 has filter_xss() to prevent XSS vulnerabilities, but what is Drupal 8 strategy against XSS vulnerabilities?

Sanitizing on output to avoid Cross Site Scripting (XSS) attacks

  Use Twig templates The Twig theme engine now auto escapes everything by default. That means that every string printed from a
  Twig template (e.g. anything between {{ }}) gets automatically
  sanitized if no filters are used.

  See Filters - Modifying Variables In Twig Templates for the Twig
  filters available in Drupal.

  In order to take advantage of Twig’s automatic escaping (and avoid
  safe markup being escaped) ideally all HTML should be outputted from
  Twig templates.

  API functions Use t() and \Drupal::translation()->formatPlural()
  with @ or % placeholders to construct safe, translatable strings. See
  Code text translation API in Drupal 8 for more details.

  Use Html::escape() for plain text.
  Use Xss::filter() for text that should allow some HTML tags.
  Use Xss::filterAdmin() for text entered by a admin users that should allow most HTML.

  Strings sanitized by t(), Html::escape(), Xss::filter() or
  Xss::filterAdmin() are automatically marked safe, as are markup
  strings created from render arrays via Renderer.

  While it can also sanitize text, it's almost never correct to use
  check_markup in a theme or module except in the context of something
  like a text area with an associated text format.

Source: Drupal 8: Writing secure code by: Rade, Shyamala, Robert Castelo, and Pere Orga.


How to cache forms with a reverse proxy and deal with stale form tokens? When Form API generates a form, it also generates a token that is passed out with the form in a hidden field, and expected to be returned back. If it is, the form is processed.

If a rendered form where ever to be cached, say, by Varnish, this mechanism breaks. The first user submitting the form will consume the token, and following attempts to use the form will be rejected.

What strategies are available to keep forms working while caching their rendered form?

I use BOA for my sites, but by default BOA simply disables front end-caching on the fly for form submissions. Beyond my actual experience I came a cross a one year old artificial on how the New Zealand Post deals with Drupal & Varnish and the form token issue. Holy John Wayne, its a must read for Drupal caching -really. Focusing only on the the form issue:

  The final piece to our puzzle is the Cookie Cache Bypass Advanced
  module, which automatically sets a special NO_CACHE cookie whenever
  the user submits a POST form on the site, including things like the
  login form. Our Varnish is configured to bypass the page cache (but
  not the ESI cache) when it sees this cookie.

You can also disable form tokens when XSRF production is not reaquired with in form_alter (unset($form[‘#token’]);) or ($form[‘#token’] = FALSE;)

An Acquia Drupal performance article puts forth a Drupal Module Authcache, but reading the doc on Authcache, it works out the caching with a place holder for the form (not caching the form):

  Authcache attempts to intercept any customized content and set up a
  placeholder within the HTML. Then after the page is loaded, an Ajax
  callback is used to retrieve custom data and fill in the placeholders,
  dynamically updating the page HTML.

  Current Authcache placeholders: Form tokens (logged-in users only; required by > Drupal to prevent cross-site request forgery attacks)

The strategy is, cache everything but the form. So addressing everything else:
Maybe Varnish is not used at all, Memcache & Redis? My strategy would be to use what BOA offers because I use BOA and the wizards behind it (omega8.cc) know a ton more than I. I dont think there is an external cache that solves the problem. They all seem to bypass for the form.

Do partial caching with the aforementioned authcache and with finely tweaked Views and Panels as mentioned in the NZ Post article and described by the brain trust at Wunderkraut - its old, but addresses the issue.

Use Drupal ESI Module and Varnish is partially ESI compliant):

  ESI - or Edge Side Includes - is a high performance caching solution
  for Authenticated users but can be helpful for Anonymous users as
  well.

  Typically, pages which are personalised for authenticated users (even
  minor personalisations, such as a block which says "Logged in as
  manarth") will prevent reverse-proxies (which can easily perform 100
  times faster than Drupal) from caching the page, because messages
  intended for one user could then be seen by another.

Hope thats more helpful.


Block changes do not save in admin/structure/block/ page I have a large number of blocks in a Drupal website. Now I can not save changes in region and order of blocks in admin/structure/block/ page.

There is no message at the top of the page, no Javascript error in console and no error in the error log of my cpanel.

I have increased max_input_vars in php.ini file to 5000 or upper and checked the changes in admin/reports/status/php/ to be sure about it but still block changes does not save.

How can I get out of this problem?

From my experience, this happens when you disable the Main page content block and save the changes. After doing this, clicking save will not do anything.

The simple fix is to enable the Main page content block, you should put it back under the Content region.


After updating I got these error messages After updating my Drupal 8 test site from 8.3.7 to 8.4.0, I got these error messages:

  Mismatched entity and/or field definitions
  The following changes were detected in the entity type and field definitions.

  Webform submission

  The Sprache field needs to be updated.

  Absatz

  The Veröffentlicht field needs to be updated.
  The Behavior settings field needs to be updated.

What do I have to do? I don't know how and where I should update these fields. Should I update any database table, or is there another workaround?

Try on terminal this command

drush entity-updates

Or if you have Devel module installed, you can also use the "Execute PHP Code" page at http;//example.com/devel/php

try {
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}
catch (EntityStorageException $e) {
  print_r($e);
}


How to remove the "Close comment thread" button in Open Atrium? On my casetracker nodes in Open Atrium, the atrium.module inserts a "Close comment thread" / "Reopen comment thread" button.  What's the simplest way to remove this button, without having to modify atrium.module?

Keep it simple. Just throw a CSS "display:none;" on it.


reCaptcha is not display correctly in the Bootstrap Login Modal registration form I am using the Bootstrap Login Modal module release 7.x-3.2 to create a modal registration form. Unfortunately, the reCaptcha does not display on the registration form until the registration button is clicked. Afterwards the form will close. When you reopen it, reCaptcha will be displayed.
It looks like it is incorrectly added to the form.
If I switch to using default Math captcha it loads first time without problems.

Does someone know how to solve this problem?

reCaptcha doesn't display on the registration form

reopened form reCaptcha is dispayed

This helps me adding recaptcha in modal forms.

Check this patch.
https://www.drupal.org/node/1463768 in thread number 21.


Get link address of a file I have a page A that has an inline entity form that is referencing to page B, it's possible programmatically or in another way to get the link address of a file that page A is referencing to?

Yes it is possible, but that's a quite broad question. And it depends a little bit what exactly want to achieve and where.

Basically when you have the node object of page B you also have the field value of the reference field, which will be a node ID. The node ID of page A. You can take this node ID to load node A – node_load($nid).

Then you have the node object of node A. And from there you'll get the field value of the file field which most likely is a file ID. This file ID now can be taken to build the path to the file – file_load($fid).


Why does Drupal 7 prefer CSS @import rules to  tags? "Don’t use @import," lots of guys say.

There are lots of shortcomings of using @import.

Using @import within a stylesheet adds one more roundtrip to the overall download time of the page.
Using @import in IE causes the download order to be altered. This may cause stylesheets to take longer to download, which hinders progress rendering making the page feel slower.

Why does Drupal 7 use it?

I want to change the @import rules to <link> tags. How can I do this?

Don't use @import to import css files:

  @import is used only in non-CSS aggregation mode. This is done to workaround IE limitation with the number of  tags.

This should explain the reason and how to get rid of it. Any production site should use CSS aggregation, and not have @import.


Cannot use fields as product attributes if they are within a field collection I am building a commerce marketplace, and have several field that I am reusing on multiple product types. It's getting tedious adding them over and over, so I'd like to include them in a field collection.

The issue is that fields within a field collection cannot be marked as (and I'm paraphrasing) "should be used as a product attribute." I'm assuming this is because the fields do not know that they will be used on a commerce product, so the option isn't available.

Does anybody know of a way to implement this functionality? I'm open to coding, I just don't know what I'd work on.

By default Drupal Commerce supports list type fields (list, term reference - list, etc.) as Product attributes, not sure but may be because pre-defined list of values.

It would be difficult to get the field collection as your product attribute, because attributes make the product Unique and using the field collection won't give you much feasibility to use every field value to differentiate between product. Instead you can re-use fields in every product type and get it working easily.

If you still would like to give field collection module a try, you can check Drupal Commerce module in detail for attributes implementation or refer Commerce Attributes Date module which allows date field to be used as Product Attributes (Drupal Commerce doesn't support Date type field as attribute by default).


Converting existing autocomplete field to custom Drupal field I have an existing autocomplete field outside of Drupal that uses jQuery UI's autocomplete functionality and makes a call to a custom PHP script to parse the input and return formatted data as JSONP. I need to migrate this field to Drupal.

I've created a custom field module, but I can't figure out how to bind the JS functions if the field allows multiple values. At the moment, I have the IDs of the HTML elements I need to use set with the name-'.$delta.' to append the delta to the ID name. Is there a way to bind JS functionality to a field in Drupal like a custom field behavior call or will I need to create a function in my JS to manipulate the ID and extract the delta that way?

I need one function to run when the field is presented as a widget (node/edit), and a different function to run when the field is presented as a formatter (node/view).

Also, is there a hook to tell Drupal about my JSON service PHP file, or do I just drop it in an includes folder in my module and link to it from my JS file?

I ended up solving this by using hook_menu() to create an AJAX tie-in with a custom callback function and then tied the form field to the AJAX path with 'autocomplete path' => '/...' in the field parameters. No need for any custom JS to make it work.


How do I tell Twig not to print any form field? I am trying to theme a form in Drupal 8.

This is the template that I am using which is basically from form.html.twig

<form{{ attributes }}>
{{ element.app_theme_settings }}
{{ element.a2 }}
{{ element.a3 }}

 {% print remaining required form fields. %}
 {{ children }}
</form>

My problem is I want to print children variable but without app_theme_settings, a2 and a3 children. In Drupal 7 we could use unset function, but in twig I am not sure what to use. I know I can use without filter, but it does not accept the array argument so I have to write name of each element already printed.

 {{ children|without('app_theme_settings','a2','a3' }}

How can I print children without specifying the name of each field one by one?

Loop through the keys

{% for key in element|keys %}
    {{ children|without(key) }}
{% endfor %}


Creating a loop condition in Rules for Commerce Line items Certain products on the site can't be shipped using a certain shipping service as they are classified as dangerous goods.

So I need to be able to loop through all the items in the cart, check to see if the product has is marked as dangerous (field_dangerous_goods on the commerce_product entity), if any of the products in the order are marked as dangerous goods then that shipping service shouldn't be shown to the user.

I've tried with various different rule components to try and create what I need with not even a glimmer of hope.

Figured it out.

Firstly, you'll need Conditional Rules.

Create a new rule component.

For the variables, add Commerce Line Item as a Parameter and add a Integer as Provided.

Under Conditions, add Entity has field, select commerce_product. Then add another Entity has field and select your field_dangerous_goods field from line-item:commerce-product. Lastly add a data comparison to check the status of the dangerous goods field. In my case I just had a checkbox, so I used Data value is empty and checked the Negate box.

This makes the condition return TRUE if the current line item is a dangerous item.

Under Actions, choose Add action and select the Set a data value option. For this set the parameter to the variable you created when you set up the component. Set the value to 1.

{ "rules_dangerous_goods" : {
    "LABEL" : "Dangerous goods",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "line_item" : { "label" : "Line Item", "type" : "commerce_line_item" },
      "dangerous_goods" : { "label" : "Dangerous Goods", "type" : "integer", "parameter" : false }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "line-item" ], "field" : "commerce_product" } },
      { "entity_has_field" : {
          "entity" : [ "line-item:commerce-product" ],
          "field" : "field_dangerous_goods"
        }
      },
      { "NOT data_is_empty" : { "data" : [ "line-item:commerce-product:field-dangerous-goods" ] } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "dangerous-goods" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "dangerous_goods" ]
  }
}

Then for your shipping service rule, under Actions, choose Add action. Select Add a variable, I called mine Contains Dangerous Goods (contains_dangerous_goods). Set the value to 0.

Add a loop.

Then Add action to the loop. Select your component. You'll need to set the variable name, this has to be different to the Contains Dangerous Goods variable from before, I just called mine Dangerous Good (dangerous_good).

Now choose Add conditional to the loop. Then for the conditional, choose Add if. Select the *dangerous_good* which we just set in the loop in the component action. Set the value to 1.

Within the If, choose Add action. Select Set a data value. For the field, choose the contains_dangerous_goods value. This is the initial variable we set for the shipping service rule. Set the value to 1.

Now outside of the loop, Add conditional. Then Add if. Choose the *contains_dangerous_goods* field and set the value to 0.

Then within the If, add your shipping rate.

{ "commerce_shipping_service_standard_up_to_0_5kg" : {
    "LABEL" : "Rate Standard - Up to 0.5kg",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "commerce_order",
      "commerce_physical",
      "rules",
      "rules_conditional",
      "commerce_shipping"
    ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
    "IF" : [],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "contains_dangerous_goods" : "Contains Dangerous Goods" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_dangerous_goods" : {
                "USING" : { "line_item" : [ "list-item" ] },
                "PROVIDE" : { "dangerous_good" : { "dangerous_good" : "Dangerous Goods" } }
              }
            },
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : { "data" : [ "dangerous-good" ], "value" : "1" } },
                  "DO" : [
                    { "data_set" : { "data" : [ "contains-dangerous-goods" ], "value" : "1" } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "contains-dangerous-goods" ], "value" : "0" } },
            "DO" : [
              { "commerce_shipping_service_rate_order" : {
                  "shipping_service_name" : "standard_up_to_0_5kg",
                  "commerce_order" : [ "commerce-order" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}


redirect index.php?var1=aaa&var2=bbb I just moved a website to drupal 7 and I have problems with the redirects.

The old website had all urls like this:
www.example.com/index.php?var1=aaa&var2=bbb
(where aaa and bbb changed for the different pages)

In the new Drupal website I use alias, so for example the page:
www.example.com/index.php?var1=aaa&var2=bbb
now it is replaced by
www.example.com/content/something

I tried to redirect the old url to the new one with two different methods, but both failed. They redirect the users to the homepage.

I create an alias
I added a rewrite rule in the .htaccess file
RewriteRule /index.php?var1=aaa&var2=bbb /content/something

As I said, both of them redirect to the homepage.

Any idea?
thanks!

Redirect  is the drupal 7 version of path redirect. Path redirect This module allows you to specify a redirect from one path to another path or an external URL, using any HTTP redirect status. and GlobalRedirect is a simple module which…
Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
Checks if the current URL is the same as the site_frontpage and redirects to the frontpage if there is a match.
Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.
Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's.
Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case.
Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect_admin module. In Drupal 6, the settings page is bundled into the module.


Display add to cart form / +product from node template I have a custom node template based on a custom content type and I want to display products with their "Add to Cart" buttons from this custom node template.

In the content type (actually a field collection), I added the Product reference. In the template (node--{content type}.tpl.php) I do this type of thing:

$wrapper = entity_metadata_wrapper('node', $node);
// Since it's a field collection, I loop these:
foreach ($wrapper->field_content_group as $group) {

  //Now each "$group" has the fields I want to display

  //I permit N products (not just 1), so I can get product information,
  //like price for example, like this:

  if($group->field_featured_product) {
    $product_references = $group->field_featured_product->value();
    foreach($product_references as $product_reference) {
      $product = commerce_product_load(intval($product_reference->product_id));
      $price = entity_metadata_wrapper('commerce_product',
                                       $product)->commerce_price->value();
      print $price_display = commerce_currency_format($price['amount'],
                                                    $price['currency_code'], $product);
    }
  }

}

I don't need to alter the display, I'm happy with that. I'd like to just call something that prints the product, price, etc., along with the "Add to Cart" button. I'm thinking I call commerce_product_load and then some method(s) that gives me the completed form. Is there such a thing that I can call?

NOTE: Yes, I know about separation of concerns and that code is best placed outside of the template file.

Since views seem to be the easiest way to display product offerings, the way I solved this was to create views for the products. The views are configured as blocks. Then I use:

$block = module_invoke('views', 'block_view', $block_name);
print render($block['content']);

to display the block.

I used content type fields to specify the block names I want to display within certain areas so it isn't hard-coded. It isn't terribly elegant, but sometimes programming is that way since there isn't an infinite amount of time to solve problems!


How to use different value from select options vs what's displayed? Name vs Realname For adding multiple members to a group (course in opigno), I implemented the chosen module for better UX on the select options but instead of displaying usernames I want to display realnames.

Using $account-realname in the user loading loop displays them but after submission it breaks, as I think it expects to receive name instead.

  $form['massadd']['#options'][$account->uid] = $account->realname

$gid = current($form['group_ids']['#value']);
$node = node_load($gid);

$form['massadd'] = array(
'#type' => 'select',
'#title' => t('Select students to add to the group'),
'#required' => TRUE,
'#multiple' => TRUE,
);

$users = entity_load('user');
 foreach ($users as $uid => $account) {
  if ($uid && !in_array($uid, $exclude)) {
    $form['massadd']['#options'][$account->uid] = $account->name; // tried realname instead
  }
}

...

 $form['submit']['#weight'] = 0;
  // We validate our own way.
  unset($form['#validate']);
  $form['#submit'][] = 'opigno_simple_ui_form_og_massadd_massadd_form_add_roles';
  $form['#submit'][] = 'opigno_simple_ui_form_og_massadd_massadd_form_add_state';
  $form['#submit'] = array_merge(array('opigno_simple_ui_form_og_massadd_massadd_form_prepare'), $form['#submit']);

Having changed it to $account->name I managed to find out what's going using devel command dpr($variable) which contained the users uid.

Then I just needed to replace the user lookup query accordingly to cross check from realname table with that of the users based on uid.

$query = db_select('realname','rn');
$query->join('users','usr','usr.uid=rn.uid');
$query->fields('rn', array('uid'));
$query->condition('rn.realname',$mail,'=');
$result =$query->execute()->fetchAll();

if (!empty($result)) {
$uids =array($result[0]->uid);
$account = user_load_multiple($uids);
$account = array_shift($account);
}


ftp uploaded files are not in the library of Media module I installed media module in Drupal 7 to browse the uploaded files on the server. I created a new field called media3 and this is its configuration.

This is the next page :

The problem is when I'm trying to add new content to this content type and select them in the library tab from media module, only the image files that are already uploaded through http protocol are displayed.

If I check the Allowed URI schemes checkbox, nothing will be displayed in the library tab.
 how do I can browse the ftp uploaded files? where they should be to be visible to media module?

The media module, like pretty much all of the file related modules on Drupal, relies on the managed files system which involves adding data to the db for files that are uploaded, simply using ftp to place them in the appropriate directory bypasses the "drupal way" and doesn't create these database rows, so the media module doesn't know about the files. I have used this method with other modules but not media:

::I do not claim that this is the best way to handle it, but it has worked for my use cases::

The following are the contents of a custom module I through together and assume a few things, first that your node type is "picture", second that you are just using the default "file" field that comes with drupal, and lastly that only files you are aware of exist in the directory "/sites/default/files/importer":

function MYMODULE_menu(){
    $info['db_pics']=array(
        'title' => 'NCD Callbacks',
        'page callback' => 'db_pics_callback',
        'access callback' => 'pics_is_admin',
    );
    return $info;
}
function pics_is_admin(){
    global $user;
    return ($user->uid==1);
}
function db_pics_callback(){
    $url='./sites/default/files/importer';
    $files=traverse($url);
    foreach($files as $source){
        $node=new stdClass();
        $node->type='picture';
        $node->uid=1;
        $node->status=1;

        //This part is optional and just allowed me to create a node using metadata from the image file
        //Get file info
        $fn=exif_read_data($source);
        if(!isset($fn['DateTime'])){
            $fn['DateTime']=$last_dt;
        }else{
            $last_dt=$fn['DateTime'];
        }

        $node->title=$fn['FileName'];
        $names[]=$node->title;
        $node->created=strtotime($fn['DateTime']);

        //Fetch the actual data from the image file
        $image = file_get_contents($source);

        // Returns the new file object after saving the image to the appropriate Drupal File schema
        $file = file_save_data($image, 'public://'.$fn['FileName'], FILE_EXISTS_RENAME);
        $node->field_image['und'][0]=(array) $file;
        node_save($node);
    }
    return '

'.implode('

',$names).'

';
}

//quick and dirty utility function assumes only files you want are in the specified directories
function traverse($url){
    $entries=array();
    $dir=scandir($url);
    foreach($dir as $entry){
        if(in_array($entry,array('.','..'))) continue;
        elseif(is_dir($url.'/'.$entry)){
            $entries=$entries+traverse($url.'/'.$entry);
        }else{
            $entries[]=$url.'/'.$entry;
        }
    }
    return $entries;
}

This is a little different than what you asked for, but I see people asking for this functionality frequently so I wanted to give a complete answer about importing files as nodes, for your specific use case the callback function can be significantly shortened to:

function db_pics_callback(){
    $url='./sites/default/files/importer';
    $files=traverse($url);
    $saved_files=db_query('SELECT filename FROM file_managed')->fetchAll(PDO::FETCH_COLUMN);
    foreach($files as $source){
        $image = file_get_contents($source);
        $fn=substr($source,strrpos($source,'/')+1);
        if(!in_array($fn,$saved_files)){
            file_save_data($image, 'public://'.$fn, FILE_EXISTS_RENAME);
        }
    }
    return 'Finished';
}

That should add all of your files to the managed files database table and allow you to view them in the "Library" tab. Good luck!


Big Views query and PHP memory limits I have a custom table, from which I create a paged table using views and data module.
When I get somewhere over 15000 rows, PHP runs out of memory. Is there any way to avoid this?
Thanks

Sounds like your memory limit on your server is too low.

Have a look under Reports >> Status report what it is.
Default on most servers are 32M. This is too low.

If you do not manage your own server then go beg your server admin to increase it. I can't give you a number, best to increase in 32Mb steps until you are happy.
I normally set mine to 256Mb during development and drop it to 128Mb on fairly large sites (this is just a guideline what I do).

If your server admin does not want to change it then first answer would be to get a new provider, which I know is not always the correct route. But read here how you might be able to set it yourself. Increase PHP settings


Auto add image to node listing from node body field Hi I have news content type, where are fields Title(textbox), Body(text with CKeditor) and Summary Image(multimedia asset). Is it possible to auto add first image from Body to summary image field?

Install the Token Filter module. That'll tell you what tokens available and from them choose the field that you want to display in the node body. So when you save the node the token will replace with the field value you want.


How to add a checkbox for contact page in drupal? I added a checkbox in my register form in drupal name
"do you want a contact form?"

If the user checked it then in profile page a menu for contact is shown but if it says no then in the same page "Contact:Not Reachable " is shown.

You can do this with Drupal core Contact module and with small custom code. As Drupal 7 contact module provide personal contact form and site wide contact form. See here Working with the Contact Form. You can enable Personal contact form by default for each user and hide the Contact Settings under /user/[uid]/edit which will be enabled for all users. Then with custom code you can show and hide Contact form Based on the Checkbox you added.

The setting shown in below screenshot will be enabled for all users by default then you will hide this setting with custom code. Because there is no configuration to show this setting on user registration form.

Steps:

Enable Drupal core Contact module.
Then Goto admin/config/people/accounts and enable Enable the personal contact form by default for new users. setting.

Give the following permission to Authenticated Users

View user profiles
Use users' personal contact forms

Add the checkbox field in User profile and enable that on registration form. Assuming the field name is field_do_you_want_contact_form.
Then in custom module with hook_form_alter hide the personal contact form setting and show/hide the contact form based on the value of checkbox.

//custom.module
function custom_form_alter(&$form, &$form_state, $form_id){

  // Hide the personal contact form setting under /user/[uid]/edit

  if ($form_id == 'user_profile_form') {
   $form['contact']['#access'] = FALSE;
  }

 // Show the Contact form Or custom message under contact tab based on checkbox value.
  if ($form_id == 'contact_personal_form') {
    $user = $form['recipient']['#value'];
    $wrapper = entity_metadata_wrapper('user', $user);
    $do_you_want_contact_form = $wrapper->field_do_you_want_contact_form->value();

    if (!$do_you_want_contact_form) {
    // hide all the contact form element.
        $form['name']['#access'] = FALSE;
        $form['mail']['#access'] = FALSE;
        $form['to']['#access'] = FALSE;
        $form['subject']['#access'] = FALSE;
        $form['message']['#access'] = FALSE;
        $form['copy']['#access'] = FALSE;
        $form['actions']['#access'] = FALSE;

    // Add custom message
        $form['not_rechable']['#markup'] = t('Contact: not rechable');
    }
  }
}


How do I change my site time to test my recurring payments? I am testing the recurring framework in Drupal commerce on my local mamp environment and I want to test the recurring payments. How to I trick my Drupal site into thinking it's a day later so it will trigger the recurring payment?

If you are working with 5.3+ you can do a trick with namespaces: implementing a new time() function inside your current namespace and create a shared resource where you set the return value in your tests.

You can found a complete description in this blog post:

PHP: “Mocking” built-in functions like time() in Unit Tests


Drupal (or perhaps Apache) delivers wrong page Made a website in drupal 8, and using webforms to save some webform submissions.

Made a custom url to show the submission data the way I want, for the sake of the example let's say:
/submissiondata/[submission_id]/[submission_token]

anonymous users can see that page, and made sure that the page is not cached- by adding options: no_cache: 'true' in the routing.yml file and also when returning data, returning it like this:

return array('#markup' => $html, '#cache' => ['max-age' => 0,]);

Some extra info:
When showing this info, the user has only 5 min. to see this page, because I compare CREATED to CURRENT_TIME - and deliver some other HTML if more than 5 min. passed.

the apache server is setup with some reverse proxy...

Here is the issue:
Sometimes, a person sees another persons submission data, just by surfing around the website. Like clicking the logo and going to the front page, they don't see the front page, but see submission data of another person!

How the heck is that possible?? It's happens very rarely, but it happens!
It should not be possible! Is this a Drupal issue?

"The apache server is setup with some reverse proxy..." then you have to provide the correct response headers in an event subscribers, see How to embed drupal content in other sites (remove X-Frame-Options: SAMEORIGIN)? how to set response headers.

Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

And uninstall the module Internal Page Cache, because this built in reverse proxy doesn't respect Cache-Control headers and you don't need it, because you already cache outside of Drupal, see PageCache caching uncacheable responses (violating HTTP/1.0 spec) + D8 intentionally disabling HTTP/1.0 proxies = WTF


How do I filter a menu to only show menu items translated into current language? In my Drupal 8 project I have a menu containing menu items in english. Some of the items have a german translation. How do I filter the menu to only show the german items when viewing the site in german?

I'm currently using MenuLinkTree to fetch my menu and I have created my own MenuLinkTreeManipulator transform where I try to filter out MenuLinkContent items that does not have a translation in the current language. But the method for getting an entity from a MenuLinkContent object is protected, so I cannot access the language property of the underlying entity!

Is there some other way of finding out the language of a MenuLinkContent object? Or another way of filtering a menu by current language?

Edit:

Here is the method I'm currently using (as a transform) when getting the menu via the MenuLinkTree service:

public function currentLanguage($tree) {
  $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();

  return array_filter($tree, function($item) use($lang) {
    return $item->link->getEntity()->language()->getId() === $lang;
  });
}

$item->link above is an instance of \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent. The above code does not work since $item->link->getEntity() is a protected method. If make it public the code above works. I see no way of accessing the underlying entity here without hacking core. Is it possible in any way? Is it possible to "swap" out this class for my own implementation in a custom module?

I managed to hide non translated menu items with the following code:

use Drupal\Core\Menu\MenuLinkInterface;
use Drupal\menu_link_content\Plugin\Menu\MenuLinkContent;

/**
* Implements hook_preprocess_menu().
*/
function MY_MODULE_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
   $language = Drupal::languageManager()->getCurrentLanguage()->getId();

    foreach ($variables['items'] as $key => &$item) {
      $menuLinkEntity = MY_MODULE_load_link_entity_by_link($item['original_link']);

      if ($menuLinkEntity != NULL) {
        $languages = $menuLinkEntity->getTranslationLanguages();
        // Remove links which is not translated to current language.
        if (!array_key_exists($language, $languages)) {
          unset($variables['items'][$key]);
        }
      }
    }
  }
}

function MY_MODULE_load_link_entity_by_link(MenuLinkInterface $menuLinkContentPlugin) {
  $entity = NULL;

  if ($menuLinkContentPlugin instanceof MenuLinkContent) {
    list($entity_type, $uuid) = explode(':', $menuLinkContentPlugin->getPluginId(), 2);
    $entity = \Drupal::entityManager()->loadEntityByUuid($entity_type, $uuid);
  }
  return $entity;
}

There is probably a better way but this worked for me.
Got the inspiration from here: http://www.agoradesign.at/blog/add-custom-menu-item-attributes-drupal-8


captcha.module error I've just installed recaptcha module and it works fine but I get this error only at the sign up screen (registration screen).

Does anyone know what can I do to fix it??

The error:

Notice: Undefined index: form_id in _captcha_get_posted_captcha_info() (line 604 of /var/www/drupal/sites/all/modules/captcha/captcha.module).
Notice: Undefined index: captcha_info in _captcha_get_posted_captcha_info() (line 607 of /var/www/drupal/sites/all/modules/captcha/captcha.module).

Screenshot:

https://image.ibb.co/eYQdhn/Captcha.jpg

check if you have installed the latest module(7.x-2.2) and selected the reCaptchas challenge type dropdowns(for the required pages).. I too had error in displaying reCaptchas..Later i figured that i installed old versions.


hook_menu_alter with Organic Groups I want to change the menu button on my main nav bar depending if the user is or isn't a member of a group.

I need one button to 'register' if the user isn't part of a group and that same button changes to 'add post' if he/she is.

I do not know what to put in the array. Do I put an IF statement similar to "Correct way to use hook_menu_alter"?

   function change_menu_menu_alter(&$items) {
     $items['/node/[nid]'] = array(
       'access callback' => 'change_menu_custom_menu_access_callback',
       'access arguments' => array(1),
       // **I don't know what goes here!!!**
     );
       return $items;
   }
   function change_menu_custom_menu_access_callback($gid) {
     return og_is_member('node', $gid);
   }

EDIT: I do not have gid in my url as I am using pathauto to use [node:content-type]/[node:title] on my URL which is why I don't think the current answer works on my website.

This is how I solved a similar problem with the hook_menu() and the use of 'title callback' and 'page callback'

function YOUR_MODULE_menu() {
    $items = array();

    $items['link'] = array(
        'title' => 'test',
        'description' => t('Just a test'),
        'title callback' => 'change_title_link',
        'title arguments' => array(1),
        'page callback' => 'go_to_place',
        'page arguments' => array(1),
        'access callback' => 'user_is_logged_in',
        'expanded' => TRUE,
        'weight' => 100,
        'menu_name' => 'main-menu',
        'options' => array('attributes' => array('class' => array('perfil-usuario'))),
        );

    return $items;
}

In this function you can change the link title

function change_title_link($gid) {
  if(og_is_member('node', $gid)) {
    return 'Post';
  }
  else {
    return 'Register';
  }
}

Here you can redirect to the desire url

function go_to_place($gid) {
  if(og_is_member('node', $gid)) {
    drupal_goto('/someplace/post');
  }
  else {
    drupal_goto('/someplace/register');
  }
}


Create a rule based on specific URL being visited I have set up a rule on my website so that when a content writer creates an article, it sends me an email notification and also the body content of the node so I can review it. Only after I have reviewed it and changed a field on the node to mark it as reviewed will it be published.
I often get the email on my smartphone and want a quick way to email back the site so automatically publish the article. Does anyone know what rule would do this for me?

Publish content

  Exposes publish/unpublish links to your views, making it easy to
  streamline workflows for reviewers, editors and publishers.


Selecting the taxonomy terms to use using a textfield to search them My Drupal 7 site has almost thousand of taxonomy terms. So it is a hard work for my users to pick their desired category from thousand of taxonomy terms.

Is there any way to select a taxonomy term by using a small search box to choose the exact category and sub-category?

You can try using Views to build a custom search with exposed forms. And the use the fields to display terms the way you need it. That is probably the easiest.


How to pass variable from module to other theme I would like to pass variables from my custom module to some of my custom themes.
The most tutorials are concerning using hook_theme function but as I understand, it works only for creating new theme functions (new tpl files) inside module, where the hook_theme is defined. But I would need to alter theme definition of some custom theme in
/sites/all/themes folder from my custom module
/sites/all/modules

In particular, I need to add a variable into thems's html.tpl.php file. I would like to use custom module to define variable, because I need to make database queries to fill variable with value, and db queries should not be done in theme.

I have tried implementing hook_theme_registry_alter.
I have tried to add variable like this:

function mymodule_theme_registry_alter(&$theme_registry) {
$theme_registry['html']['variables']['test'] = 'test value';
}

but I got error "Undefined index: #children in template_process_html"

Can anybody help?

For your needs, you'll need to create a custom module and implement hook_preprocess_html:

function hook_preprocess_html(&$vars) {
  // This is where you do the db query
  $myvar = _get_my_var();

  // After this $myvar will be available in html.tpl.php
  // where you need to print it out
  $vars['myvar'] = $myvar;
}


How to display a author picture in comment form? As the title, I try to display a user picture IN comment form. But I'm not familiar with Form function. Below is my code and I don't know how to do next?

function btmentry_form_comment_form_alter(&$form, &$form_state) {
global $user;
$user_picture = user_load($user->picture);

//What should I do next?

}

My purpose is style my comment form as Facebook.
Thanks.

I don't think you need to do coding for your requirement. You can take help from this documentation for same - https://drupal.org/node/22271. It says for D7 :

Enable user pictures for Drupal 7

Navigate to Configuration > People > Account settings.
In the Personalization settings, select Enable user pictures.
For Picture directory type pictures
Under Picture display style, select thumbnail (you can change the size settings
Click "Save configuration".

Next, ensure your user pictures display in your theme. These are enabled by default in Bartik, the default theme of Drupal 7 , so you may have to check this with any new theme you add.

Go to Appearance and click "Settings" for the theme you have enabled as default.
In the Toggle display settings, select User pictures in posts and/or User pictures in comments.
Click "Save configuration".

If your theme doesn't support user pictures, then you should look for bartik & apply same structure for TPL.


How to render author custom fields info on comment and node twig template? I am trying to render the author Full Name and other authors customs fields information in comment.html.twig and node.html.twig. But not any of the fields that I made for users such as "First Name", "Last Name", and Auther UID etc. render in comments.

I tried with the following code for comment author

{{ comments.author.field-first_name.entity.value }}
{{ comment.author.user_picture.0.entity.uri.value }}
{{ comments.author.uid.entity.value }}

And, I tryed following code for node author:

{{ node.author.field-first_name.entity.value }}
{{ node.author.user_picture.0.entity.uri.value }}
{{ node.author.uid.entity.value }}

Any ideas, how do I render this info in comment template?

For Node:

{{ node.getOwner.field_first_name.value }}
{{ file_url(node.getOwner.user_picture.entity.fileuri) }}
{{ node.getOwner.uid.value }}

For Comment:

{{ comment.getOwner.field_first_name.value }}
{{ file_url(comment.getOwner.user_picture.entity.fileuri) }}
{{ comment.getOwner.uid.value }}


Why does the page callback have two arguments? function menufun_menu() {
  $items['menufun/%/bar/baz'] = array(
    'title' => 'Hi',
    'page callback' => 'menufun_hello',
    'page arguments' => array(1), // The matched wildcard.
    'access callback' => TRUE,
  );

  return $items;
}

/**
* Page callback.
*/
function menufun_hello($a = NULL, $b = NULL) {
  return t('Hello. $a is @a and $b is @b', array('@a' => $a, '@b' => $b));
}

In the menufun_menu() function, the page argument for the menufun_hello callback is only one. Why does menufun_hello() have two parameters?

Menu callbacks are passed first the arguments defined in page arguments then excess arguments from the url.

So in the above example:

menufun/1/bar/baz

Will provide these vars:

$a = 1;
$b = NULL;

If you however provide an extra argument in the url:

menufun/1/bar/baz/2

You will transfer it to the menu callback:

$a = 1;
$b = 2;

The other advantedge is like tim writes, that it allows reuse of the same code for various cases, making the module more maintainable.


Why can html.twig files be placed outside the templates folder? In Drupal theme folder structure, there is written:

Templates provide HTML markup and some presentation logic. Contrary to Drupal 7, in Drupal 8 template files (*.html.twig files) must be stored in the 'templates' subfolder.

In my theme, I have a styleguide folder at the root. Drupal 9 finds template files, such as mytheme/styleguide/components/10-atoms/form/input.html.twig, in this folder.
Drupal 9 will use this input.html.twig file despite it's not in the mytheme/templates folder.

Ok, I have found a solution, I just need to add in my settings.php the "styleguide" folder in the ignore directories
$settings['file_scan_ignore_directories'] = [
  'node_modules',
  'bower_components',
  'styleguide'
];


Redirect only after inserting a new node? I had a rule of 'After saving new content' of type, redirect to url. I need to add second submit button to the content type so I decided to add the redirect to a custom module so I can have different actions depending on the button. The redirect works on the submit button but I only want this to happen when adding/inserting a new node. Right now it redirects every time the submit button is clicked.

In mymodule_form_alter:

$form['actions']['submit']['#submit'][] = 'submission_form_submit';

Then:

function mymodule_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'info-received';
}

Code suggestions needed. But if there is a way to have rules perform different actions based on which button is clicked I can use that advice also.

ETA: the code used for the second button

$form['actions']['submit_another'] = array(
  '#type' => 'submit',
  '#name' => 'save_another',
  '#value' => t('Save, and Add Another.'),
  '#submit' => array('node_form_submit','submission_form_create_duplicate_form_submit'),
  '#weight' => 40,
);

ETA2: Trying is_new

function mymodule_form_submit($form, &$form_state) {
  $node = $form_state['node'];

  if(isset($node->type) && $node->type == 'submission') {
    dsm('Reached Node Type Check!'); // <- this works

    if (isset($node->is_new)) {
    dsm('Reached New Node Check!'); // <- this does not work
    $form_state['redirect'] = 'info-received';
    }
  }
}

Changed the if statement checking for new node to

if ($node->is_new) {

Results in 'Notice: Undefined property: stdClass::$is_new in mymodule_form_submit()'

It seems the value for is_new is not set.

You could use hook_node_insert() under this hook should use drupal_goto() for redirect. The hook_node_insert() only trigger when a new node inserted. If you also want to update. You could use hook_node_update().


Drupal 6 - theme the standard nodequeue admin view I have a site where a client needs a 'visual' way of re-ordering their content. Is there a way to basically add more cck content to the nodequeue admin interface? so that it is not just showing a list of titles but instead maybe some cck content that the user can drag around?

I am thinking that I need to hack the module, which is fine, but wanted to know if there was some sort of recommended approach to this.

Thanks!

You can use views to prepare you listing according to your need. You can add as many CCK fields in column & expose filters too to use it further.

You can add your prepared views block at the dashboard which your admin can use.


User-Profile-Form.tpl.php not working. Help! I am not rendering any results. This is my template.php:

function fueldeluxe_theme($existing, $type, $theme, $path) {
  $items = array();

  /**
   *  Account edit Forms
   */

  $items['user_profile_form'] = array(
    'render element' => 'form',
    'template' => 'user-profile-form',
    'path' => drupal_get_path('theme', 'fueldeluxe') . '/templates'
  );

  return $items;
}

function fueldeluxe_preprocess_user_profile_form(&$variables) {
  $variables['account'] = drupal_render($variables['form']['account']);
  $variables['picture'] = drupal_render($variables['form']['picture']);
}

This is my user-profile-form.tpl.php:

    <?php echo $picture; ?>

    <?php echo $account; ?>

As you can see I'm trying to load the user profile field forms. However I'm not able to render any results. The page loads okay when I add dummy text but no account field forms.

Do I need a module for this to work?

Also what would the variable look like for calling the custom field added to a user?

I'm struggling with what you're asking in the first portion of your question, but looking into the previous Stack Exchange page you referenced you can use the Panels module to quickly accomplish two column layouts for these forms.  You can also use template overrides to change the layout of the registration pages.

If you're specifically looking to quickly implement a tabbed UI for the user profile, I believe the Profile2 module may offer a built-in solution.

  "Also what would the variable look like for calling the custom field
  added to a user?"

You may need to use load_user() first to get a complete user object to access custom profile fields.

$account = user_load(<USER-ID>); //$node->uid or $user->uid


How to display a customized button on a single form only? I have created a reset button by adding a customized module (Reset) for webform. But this button gets displayed all over the site. I just want to display this button on a single webform.

Below is my Reset module code:

<?php
/*
 *
 *  creating  hook_form_alter()
 *
 */
function custom_example_form_alter(&$form,&$form_state,$form_id) {
            $form['webform_client_form_34'] = array(
            '#weight' => 1001,
            '#markup' =>'<input class="form-button" type="reset" value="Reset"/>',
            );
            return $form;
}

How should the if condition look like that I should be adding to it ?

Find the form id first.

Assume your form id is 50 than,

function <module>_form_alter(&$form, $form_state, $form_id) {
  if (strpos($form_id, 'webform_client_form_50') === 0) {
    $form['actions']['reset'] = array(
      '#type' => 'button',
      '#value' => t('Reset'),
      '#weight' => 100,
      '#validate' => array(),
      '#attributes' => array('onclick' => 'this.form.reset(); return false;'),
    );
  }
}

OR

 if ($form_id == 'my_webform_client_form_id') {

Your code

}

Another method :-

In Drupal 7, you can either use hook_form_alter() or hook_form__alter(), which ever you prefer. Just make sure you get the naming and parameters right. Drupal 6 only supports hook_form_alter() however.

When you create these functions, also remember that Drupal may not always pick up on them until you've flushed the cache.

function mymodule_form_webform_client_form_44_alter(&$form, &$form_state) {
// code here;
}

Please remember to clear your cache also and try to disable/enable your module also


How to order search results based on author field content I am using Drupal 8 search views, I would like to order the search result so that the content that's author has field "X" filled out should be ordered first and all other content where the author has field "X" empty shows up after. How can I achieve this with views
I made a relationship between the content and the author. I can access field "x" in the fields part of views, but it does not show up in the "filter" or "order by" parts.

You are almost have done it.

I made a relationship between the content and the author. I can access field "x" in the fields part of views, but it does not show up in the "filter" or "order by" parts.

add that fix "X" in sort section and sort it as Descending. when you make it descending contents with null values appear after those that have value.


db_fetch_array() fetches only one row from data table, even though I am expecting multiple results I'm trying to create an array with all the group node' IDs, and from outside group context.
I currently have two group nodes defined, and I can see them in my OG table.

However I only get back one result, using the following code. I've tried using only db_query() without db_fetch_array() and I still get a single result.

$group_node_nids = db_fetch_array(db_query("SELECT nid from {og}"));

What am I missing here?

Every time I have to take results outs of a database query result resource I'm scratching my head wondering why we don't have a way to return all rows without having to iterate over the object.  Perhaps there's a method out there in cTools or Drupal 7 but until a better answer is presented:

$results = db_query("SELECT nid from {og}");
while($row = db_fetch_array($results)) {
  $group_node_nids[] = $row['nid'];
}


How to prevent user from viewing profile I go into Administration>People>Permissions>User>View user profiles and see that only admin has this permission, however while logged in as non-admin I can still see his profile when I go to  /user

There'd be a few ways you could do it, the fastest might be to create a user-profile.tpl.php and do a check for the user's group.


How to create new type element to form API? Drupal form API provides some built in type of element to build a form. But I want to create other type such as:

$form['mail']['#type'] = 'email';

And the output I want it to be:

<input class="input-1" type="email" id="edit-mail" name="mail" maxlength="128">

So, how can i do that?

You need to implement hook_element_info(). See the
form_example_elements.inc file from the Example: Form API module, and the Creating Custom Elements documentation guide.

Note that the Elements module already provides a form element type for HTML5 mail inputs.


Force node render with a template (giving template url not suggestion) I need to change

$render_array = entity_view($entity_type, $entities, $view_mode, NULL, TRUE);
render($render_array);

in order to force drupal to use a specific template.tpl.php (giving a specific template url).

How can I achieve this?

I will skip theme suggestions since your title specifically say to.  There are several ways to use the menu router system to send the same node as an argument to different callback functions that handle the render process.

Most commonly used methods are Panels and Display Suite.

With Panels, you can have the panel sit at any url you want, take the node as an argument from context or url, and display parts of it or views related to it in a layout controlled by the panel manager.
yousite.com/display1/nid and  yousite.com/display2/nid

With Display Suite you have a similar display management, but the default (at least last time I used it) is to have the different custom displays as final tags in the url.
yousite.com/normal-node-path/display1  and   yousite.com/normal-node-path/display2

If you want to do it all by yourself with custom code, you can use hook_menu to register your own page callback(s) for your own url(s).  You can pass as many pieces of the url as you wish as arguments to your custom function, as long as they do not include the first word.  yousite.com/this-one  Menu_router does not like urls to start with variables.
Then, with the information that your callback preps, you can guide your node through a custom hook_theme to use your specific template


How can I add a link to the main menu from a custom module? I've seen numerous questions on how to address this, but I've not quite found the answer. I'd like to add an additional link to the main menu. I've attempted this in my_module.links.menu.yml and run drush cr. This doesn't seem to limited impact.

This item will show up under the Tools menu, but not main.

my_module.list:
  title: 'List All Computers'
  description: 'Show all known computers'
  route_name: my_module.listAllComputers
  parent: main

Is there something wrong with the above? Is PHP a better way to add a link to the main menu? If so, where? Do I use a Drupal 8 hook?

You are missing the key menu_name that will permit the addition of your new menu item into your main menu.

my_module.list:
  title: 'List All Computers'
  description: 'Show all known computers'
  route_name: my_module.listAllComputers
  parent: main
  menu_name: main

The parent key is not mandatory, so if you want your link to be shown on the first level of your main_menu, you don't need it.


Drush 9.2 - not working well / not installing with Composer I am using Ubuntu 17.10 running Apache 2.4 on a Vultr instance. Using virtual host for my.example.com website. Installed Drupal 8.5.1 per recommended Drupal-Composer/Drupal-Project. Apache docroot points to the "web" folder containing Drupal core (ie, where Drupal's update.php lives, among other things). The project root folder is one level up, containing the composer.json file.

File permissions: the project root folder itself is owned by user:www-data; same for Drupal root (web, and below). Drupal status is fine. It looks like Composer installed the /vendor folder [in the project root] as user:user.

I have seen so many errors, it's hard to know where to start. So far I have not discovered any underlying logic to them. The goal is simple: to get Drush working on my install, which is nothing special. Even on Windows, I can get Drush half-working.

After the install, Drush was at least recognizing its own existence. (At one point, I had the drush.phar helper globally installed, per the instructions from that website.) But "drush status" was claiming that it couldn't find Drupal -- even with the -uri flag, and even with the alias set up in example.site.yml contained in /project-root/drush/sites.

Drush status was looking at something that pointed to a deleted docroot folder, but I couldn't find the relevant config, and the only possibility was a path entry in that section of the composer.json file. Which I fixed, but that didn't help Drush.

Per the Drush docs, I tried running the drush command from Drupal root, pointing to /vendor/bin; and also in the /vendor/drush/drush folder. Getting permission denied in all cases. [Why? I'm the user running the command, in folders that I own as the user! Does Drush need www-data group permission?]

Adding a path command to ~/.profile [the Ubuntu file for .bash_profile] didn't help.

The permission denied error was in addition to the error re "command not found" -- when I'm in the very folder where I know the command file is located. I tried "chmod +x" on both the /vendor/bin version of drush, and the vendor/drush/drush/ version [just the "drush" single word file, not the "drush.php" file], but that didn't solve the problem. I reverted those back.

[And why is the folder structure so convoluted? Why the middle /drush?]

So, then, I thought that maybe it was a Drupal-Composer issue. So composer did allow for removal of drush/drush. And I deleted all the left-behind drush folders in my user home and in the project folder.
Went to re-install Drush using Composer, per the Drush install docs: "composer require drush/drush"

Which fails for me. The main culprit seems to be a symfony/var-dumper conflict [many versions] with symfony/http-kernel [many versions] -- it's several screens full of the attempted reconciliation, with this conclusion:

Can only install one of: symfony/var-dumper[v3.4.8, v4.0.8].
Installation request for symfony/var-dumper (locked at v4.0.8) -> satisfiable by symfony/var-dumper[v4.0.8].

updating for symfony/http-kernel (with dependencies): nothing to update

updating for symfony/var-dumper (with dependencies): nothing to update

In composer.lock, the entry for SHK does have a "conflict" parameter that mentions SVD. But I don't know how to fix that [if that is in fact the source of the "lock" statement above].

I run a simple website, so probably don't need Drush to move to D8 -- except that others seem to get it working and find it helpful -- and I'd like to join that club.

Thanks for the replies. Managed to get things working:

I created a new folder (drushtest), and ran composer init to create a drush-only project (myname/drush). Init runs an interactive series of question to create a valid composer.json (with only require: drush/drush [and a version constraint]).
Ran Composer to install, and it pulled down Drush and its dependencies.
Then went to remote server, and copied to /vendor/bin, the two drush files, and to /vendor, the various folders that were in my Drush-only install versus what was already on the remote folder.
Deleted the existing composer.lock. In require section of composer.json, added drush/drush: ^9.2 [with appropriate quote marks], and ran composer update. Which worked fine. [I still don't understand the effect of .lock on .json, but I guess we're all learning in the new Drupal 8 way.]
To keep things still simple, went to my Drupal folder (web), and (per Drush docs) ran Drush: "../vendor/bin/drush" -- the first time this generated a shell error re no permission. So ran that again under sudo, and got a no command error. Third time lucky, applied "chmod u+x" to that path-file, and Drush sprang to life, and even identified the correct Drupal installation (with all associated info that one expects when Drush is working) without an alias file. Hurrah!
More on file permissions: for ../vendor/bin/drush, added the x flag to the group (permissions are now 754), and can run that command without sudo (under my user name). Which I still find odd, in that my user is the owner (with rwx), and the user:group info is: user:user. But I'm quite new to Linux.
File permissions, again: With the above, commands like drush status worked, but running (as the user) drush cc (or cr) gave an error that pointed to another file permissions issue. (Sudo could run those commands OK, but it would be weird to use sudo for some drush commands and not for others -- and who could remember.) Which traced to: in the /home/user folder, there is a hidden .drush folder [with a factory subfolder containing a bunch of php command files]. The install process had set ownership of that to root:root. There is more than one way to handle this, but for now I changed ownership (chown) to user:user, and that at least allows drush cr to work.


Secure Pages module is not redirecting I installed Secure Pages on a site, where I need to secure admin and user login pages. In general, it does its job, but when the user first tries to log in, and goes to the /user page, that page is not redirected to the secure page. The form action attribute is rewritten to the corresponding https link though.

Do you have any ideas why this could be happening?

In Secure Pages config, I use 'Make secure only the listed pages' option, and tried 'user', 'user*', and 'user/*'. Base urls are blank, but I tried filling them in. There are entries in 'ignore pages', but I tried removing them.

Another thing I noticed is that it works when the user is logged in. Could be a permission issue, but I did not see any relevant permission.

I just did a fresh Drupal 6 install with the latest Secure Pages module. Only modules enabled are default core + Secure pages. I did not modify permissions in any way.

Using the default Secure Pages settings, including

user
user/*

in the "Pages:" textarea, navigating to /user while logged out presents me with the user login form on a secure page, and logging in sends me back to the home page (where I started).

How are you redirecting your users to their /user profile upon login? Logintoboggan or some such? Let me know and I'll dig further.


Why are available updates of CKeditor not visible in the update report in Drupal 7? /admin/reports/updates lists a few updates, but the ckeditor module is missing here. It runs in version 1.9, since then a few security updates have been released, but it does not matter how often I run the cron or update the list manually, the updates for ckeditor wont be listed here.

The module itself works perfectly fine. How come?

Drupal only check for drupal modules. The CKEditor module is https://www.drupal.org/project/ckeditor and the latest version is 7.x-1.16. This information should appear in admin/reports/updates.

I suppose you are talking about the CKEditor library which is not handled by the page admin/reports/updates.


hook_init() is not working in my custom module In my custom Drupal 7 module I am using CUSTOM_MODULE_NAME_init() function. But it is not triggered while page execution. Any suggestions?

Hook implementations are cached in Drupal 7. After implementing a new hook, you need to clear the cache. See What method is used to clear caches in the Drupal? for ways to do that.


Sorting Content easily - wish to avoid a "weight" integer As the title describes, I want to create a mechanism with which a bunch of Content Types can be sorted 'easily' so they can be presented with a View according to that sorting.

Adding an Integer that would act as 'weight' should work but can end up being confusing if the number of nodes get's too high.

Ideally some sort of 'tablesorting' would be sweet.

Is there a way to accomplish such a thing?

Thanks in advance.

Here is a "Comparison of Node Ordering Modules".

I have tested most of these modules and decided to go with the Weight module because it was easier to implement and slightly faster then all the other module because it does not add any table joins to your queries since it is re-using the node's sticky field. It includes a very easy to setup Views plugin for drag-n-drop sorting. The Weight module is designed to 'sort nodes', while DraggableViews is designed to 'sort anything'.


Alter and set a id attribute for a field in drupal 7 Can anyone help me how to alter a field attribute  in drupal 7. Let say i have created a field name hello_test with label as hello.Now I need to alter the label and set a attribute for the filed in template.php file in my theme.Can anyone help me

You will want to implement template_preprocess_field() in your theme's template.php

Also helpful to you will be the drupal.org documentation on Overriding Themable Output.


Multiple forms on one page - gather values I am using the hook_form to create 2 different forms in a module file. Now it depends on what the URL parameters are, it can either display, one or the other or both.

Is there a function that picks up all form_states so i can gather values?

You can nest form elements, so there is effectively only one form. That case you'll only need one validation and submit handler. In the end all results will be in $form_state['values'].

function form_a($form, &$form_states) {
  ..
  return $form;
}

function form_b($form, &$form_states) {
  ..
  return $form;
}

function my_form($form, &$form_states) {
  if ($need_a) {
    $form += form_a($form, &$form_states);
  }
  if ($need_b) {
    $form += form_a($form, &$form_states);
  }

  // Add the buttons.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#weight' => 5,
  );

  return $form;
}

function my_form_submit($form, &$form_states) {
  drupal_set_message(print_r($form_state['values'], TRUE));
}


How to add a colspan in a table header? I need to create a table that will have a header with 4 columns and then all the rows will have 5 columns, so I need to add a colspan in the header.

This is an example of what I trying to do:

// The table header.
$header = [
  $this->t('Name'),
  $this->t('Description'),
  $this->t('Weight'),
  $this->t('Package'),
];

// The table.
$form['modules'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => [[1, 2, 3, 4, 5]],
  '#sticky' => TRUE,
];

This code just give something like this:

But I trying to obtain something like this:

I tried the last example in Add a class to a Drupal table cell containing ['data'] but just give some errors.

If you go to see the class Table you will see an example using the colspan in the '#wrapper_attributes' but it seems not works for the '#header'

I can obtain a similar output just adding an empty header column like this:

// The table header.
$header = [
  $this->t('Name'),
  $this->t('Description'),
  $this->t('Weight'),
  '',
  $this->t('Package'),
];

This will give something like this:

But I think that the correct way is adding the colspan property to the header.

Maybe I'm missing something or we just need to wait for Multi level (multirow) header for table FAPI element to use the colspan in the table header?

I just found the solution looking a bit in the Multi level (multirow) header for table FAPI element and doing some test.

This is the way that I found:

// The table header.
$header = [
  $this->t('Name'),
  $this->t('Description'),
  [
    'data' => $this->t('Weight'),
    'colspan' => 2,
  ],
  $this->t('Package'),
];

// The table.
$form['modules'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => [[1, 2, 3, 4, 5]],
  '#sticky' => TRUE,
];


Parsing the 'q' in drupal to get the current URL So I am attempting to parse out the URL, so that I can get a specific page template to be used for a specific URL; if the URL is example.com/team, then use page-team.tpl.php.

However, when I do this, the URL I am getting (via $_GET['q']) always seems to be the URL from where I was, not the one where I am currently at. If I directly navigate to example.com/team/surf, it gives me "team/surf"; if I go to example.com/team it gives
"team/surf." If I refresh the page, it will then give me the desired one.

I dropped this code into my template.php file.

function theme_preprocess(&$vars, $hook) {
  switch ($hook) {
    case 'page':
      $normal_path = trim($_GET['q'], '/');
      $path_alias = drupal_get_path_alias($normal_path);
      $alias_parts = explode('/', $path_alias);

      if (($alias_parts[0] === 'team') && (count($alias_parts)) == 1) {
       $vars['template_file'] = 'page-team';
      }
      break;
    }

Do you have any idea on what is going on here?

I'm not sure why your code happens to fail in some cases, and in some cases not. But what I would try is replacing that code with the provided by Drupal arg function.

On "team/surf", arg(0) will return "team", and arg(1) "surf". This is what I use myself, and hopefully that will solve the problem for you.


How to apply CSS to "views-exposed-form--view-name.tpl.php" I am theming a views exposed form which is a block. The views filters are displayed in a block and I am theming this using "views-exposed-form--view-name.tpl.php". I want to apply CSS to this template file.

How to do this.

You could add the CSS in <style> tags on top of your template. Most browsers will probably understand what you want, it does result in ugly HTML though.

You could also add the CSS in your main CSS file and use .view-id-viewname .div (etc.) to target elements specificaaly in that view


How do I create a custom Drupal 7 login? On my site there are 3 types of users:

Public users who do not need to log in
Public users who need to log in in order to access documents (pdfs, excel, etc)
Users who maintain the web site (add, edit, delete content, etc)

I need to have a login form on my web site for the public users to log in to access what are otherwise "hidden" documents. These users will be public users so they will not have the ability to access anything related to the Drupal administration, such as adding content. I don't see how I can use Drupal's built-in Users system by adding a new role and modifying its permissions, especially since permissions are inherited from the authenticated user role.

What's the best way to go about this?

Drupal's administrative permissions are not necessarily linked to any specific role, and individual permissions can define access to anything from viewing individual content types to administrative functions like creating and editing--they aren't all tied to administrative features.

While it is true that all authenticated users will inherit permissions from Authenticated User, you can organize your permissions like so:

Anonymous User: (Permissions for users that don't need to log in.)
Authenticated User: (Remove all permissions except those needed to view documents)
Administrator (new role): (Permissions necessary to administer the site)

Then, give the Administrator role only to the accounts used to administer the site. Nothing says you have to give that role to every Authenticated User. Administrators will be able to view documents (as with any other authenticated user), though this sounds perfectly reasonable if I understand your use case.

Additional contributed modules allow for more fine-tuning over access control. For instance, the Field Permissions module may be useful if the files you're looking to distribute have been attached to nodes via File fields; this will allow you to determine access control at the field level if necessary.


Custom error for user registration page in D7 not working I can't seem to figure out why this custom module refuses to execute for user registration validation. I've made sure I'm using the correct form id using firebug, verified the module is installed properly, but this module just refuses to show an error when the username is left blank during registration.

I thought the issue might have to do with the theme I'm currently using (Venture Theme), but I'm not really sure how to check the theme to verify the id's weren't changed. Anyone have an idea why this code won't run properly?

<?php
/**
* Implements hook_form_alter().
*/
function validation_form_user_register_form_alter(&$form, &$form_state) {
    $form['#validate'][] = 'validation_user_register_validate';
}

function validation_user_register_validate($form, &$form_state) {
  if (empty($form_state['values']['name'])){
        form_set_error('name', t('username is empty!'));
    }
}

The reason why it's not displayed are:

Since the field is required, Drupal handles that already so your user-defined validation wouldn't run since Drupal make's sure the field passes "required" validation and when it reaches your trapping, it's never empty.

  First ensures required fields are completed, #maxlength is not exceeded, and selected options were in the list of options given to the user. Then calls user-defined validations.

Reference: function _form_validate

Here is an example that your functions are right.

if ($form_state['values']['name'] == 'asdasd'){
    form_set_error('name', t('username is asdasd!'));
}

That will trigger your validation since it passes the "required" validation and checked the username for something aside from being empty which conforms to the description of the _form_validate.


Changing the sender of email I am using the Printer, email and PDF versions module, together with the PHPMailer module to send emails. It works perfectly, but only from the email in admin/config/system/site-information. How could I use hook_mail_alter() or similar hook in order to send from different accounts of the site depending on the situation?

Do I need to install another module, or can it be achieved by using a hook? hook_mail_alter() just have "from" but that is a dummy email address which can be even simulated.

After many unsuccesful tests, I have finally found the solution through
Set the "from" header in the email to be in the format "Full Name" <email@address.com>.

In your module, you must use the following code, which can be customized via the ID of the email or other parameters which are contained in the variable $message (which is passed by reference, so can be modified by the hook):

function my_module_mail_alter(&$message){

    $from = "user-account@domain.name" ;

    $message['from'] = $from;
    $message['headers']['From'] = $from;
    $message['headers']['Sender'] = $from;
    $message['headers']['Return-Path'] = $from;

} // function


How to detect a mobile browser using PHP in content? Using Drupal 7.14 with the PHP filter on I have the following in a Basic Page content type:

<?php if ($is_mobile == TRUE):?>

<?php else: ?>

<?php endif; ?>

I get the error message:

Notice: Undefined variable: is_mobile in eval() (line 1 of D:\websites\modules\php\php.module(80) : eval()'d code).

I sort of understand - I'm trying to grab a variable from the Drupal system but is there any way to do this? Maybe using Tokens?

Mobile detection isn't built into Drupal or most popular themes (I think Adaptive Theme does, though).  You need to install a contrib module to do this.  Three options are Browscap, Mobile Tools, and Mobile Detect.  Where you go from here depends on which module you are using.


How translate a static block in drupal 6? Does a variable exist that I can use to translate a static piece of text in a block?
For example:

<?php if($language==english): ?>
   do something...
<?php endif; ?>

try this:

if ($user->language == 'ru') print 'Привет чувак!';
if ($user->language == 'en') print 'Hey Dude!';


Add field to DFP module I need to add a <div> wrapper with a specific ID to a DFP AD tag within the block.

The DFP Module appears to create AD tags as entities. I cannot determine where the AD tags are stored or how to create another field to the AD tag entity that I can pull out in a preprocess function to send to my template.

I am hacking the DFP module.

Does anyone have a pointer on where to start?

If you look in the source code of the module you find that tag is a configuration entity (http://cgit.drupalcode.org/dfp/tree/src/Entity/Tag.php). This type of entities are not fieldable like content entities. But you can add custom fields by altering the config form and store the added fields in your module configuration.

Here is a how-to for this:

https://www.webomelette.com/drupal-8-custom-data-configuration-entities-using-thirdpartysettingsinterface


Migrate content based on publish date content i use d2d migrate module to migrate content between D6 and D7 websites.Actually my migration class do partially the job for all content of a type (some issue on mapping custom fields), but i would to add an argument about specifying to migrate content publish after a specific date, this to add content to current website, or ask to migrate to ignore content created yet on system..how can i do this ?

thanks

Have you had a look at the "Highwater mark" part of the migration documentation? this may be what you are looking for.
http://drupal.org/node/1223936


How do I get all the menu items below a certain parent? I am currently working on a module that finds out the parent menu item by path, then displays the current tree structure of that related menu by finding the top parent and most important only displaying that menu item and submenus from within that menu.

path = "/system/menu/submenu";
parent = 'system';
output = parent + parent submenus. (other menu items excluded)

All menu items in "Custom menu":

- System
   - Menu wrapper
     - SubMenu 1A
     - SubMenu 2A
     - SubMenu 3A
- Main
  - SubMenu 1B
  - SubMenu 2B
  - SubChildMenu 3B

PHP code should return this:

- System
   - Menu wrapper
     - SubMenu 1A
     - SubMenu 2A
     - SubMenu 3A

My code (currently not working) is the following.

 $menu = 'custom_menu';
 $title = 'System';
 $tree = menu_tree_all_data($menu);
    foreach ($tree as $branch){
      if ($branch['link']['title'] == $title){
        $childtree = $branch['below'];
        break;
      }
    }
 return $childtree;

Notice: This needs to be PHP code only; all other modules don't support this only through manual selection.

People have asked this before but i've tried their solutions and no success.

Your help is very much appreciated.

https://stackoverflow.com/questions/5218861/restrict-menu-tree-to-first-level

https://stackoverflow.com/questions/2716787/how-to-get-all-the-menu-items-below-a-certain-parent-in-drupal

How do I display submenus separately from their menu tree?

I am using this function in my code for D7 to do this exact thing. Your code looks like it should work, but it is slightly different than what I have. Honestly I haven't visited this part of my code in a while. Hope this helps.

/**
* Returns an array of all menu items under a parent.
* @param string $title Menu item title.
* @param string $menu Menu name.
* @return array
*/
function MODULE_submenu_tree_all_data($title, $menu = 'main-menu') {
  $tree = menu_tree_all_data($menu);
  foreach ($tree as $branch) {
    if ($branch['link']['title'] == $title) {
      return $branch['below'];
    }
  }
  return array();
}


Views entity reference field I am trying to create a news content type which can display related content.

In the news content type I have an Entity Reference field with unlimited values, which is used to select the nodes which should be "Related" to the current node.

I have created a view and managed to get it to display all content which is "related" to ANY node with a content type of news using the relationship setting, but i can't manage to get it to display content related to a specific node.

What am I doing wrong? I can provide more info if I have missed anything.

I recommend you to use eva module. visit this link (comment 3), I tested this solution and it works.