Why am I getting this error for the schema I define in my module? I'm building a module for Drupal 7, but I have troubles with my schema, and I don't understand why.

This is my schema.

$schema['table_name'] = array(
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'nid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'oid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'start_time' => array(
                'type' => 'datetime',
                'not null' => false
            ),
            'end_time' => array(
                'type' => 'datetime',
                'not null' => false
            ),
            'duration' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            )
        ),
        'primary key' => array('id'),
        'unique keys' => array('id')
    );

I get this error.

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
  You have an error in your SQL syntax; check the manual that
  corresponds to  your MySQL server version for the right syntax to use
  near 'NULL DEFAULT NULL,  end_time NULL DEFAULT NULL, duration INT
  unsigned NOT ' at line 5: CREATE  TABLE {table_name} ( id INT
  unsigned NOT NULL auto_increment, nid INT  unsigned NOT NULL, oid
  INT unsigned NOT NULL, start_time NULL DEFAULT  NULL, end_time
  NULL DEFAULT NULL, duration INT unsigned NOT NULL, PRIMARY  KEY
  (id), UNIQUE KEY 0 () ) ENGINE = InnoDB DEFAULT CHARACTER SET
  utf8;  Array ( ) in db_create_table() (line 2717 of
  /Applications/MAMP/htdocs/project/www/includes/database/database.inc).

How can I fix this error?

I've managed to fix it. I've altered 2 things from my original schema, the first issue was that Drupal 7 no longer supports 'type' => 'datetime', instead use 'mysql_type' => 'datetime'. The second was 'unique keys' => array('id'), I removed this and everything works correctly.
Solution...
$schema['table_name'] = array(
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'nid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'oid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'start_time' => array(
                'type' => 'int',
                'mysql_type' => 'datetime',
                'size' => 'normal',
                'not null' => false
            ),
            'end_time' => array(
                'type' => 'int',
                'mysql_type' => 'datetime',
                'size' => 'normal',
                'not null' => false
            ),
            'duration' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            )
        ),
        'primary key' => array('id'),
        'mysql_engine' => 'InnoDB'
    );

Try this for Drupal7,

'pubblish_date' => array(
  'description' => t('The pubblish date for the single news'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),
'unpublish_date' => array(
  'description' => t('The unpublish date for the single news'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),


Encrypting db password stored in settings.php The db password in settings.php is stored as plain text.
Is there any way to encrypt that password?

My client says its a security risk even though the file permissions is as should.

This is not a Drupal question specifically. Depending on the OWASP security standards you're following keeping the password in plain in settings.php could be considered a risk (in a normal, usual Drupal environment it won't be the case)

This thread on Information Security Stack Exchange discusses the topic, but in my opinion is a little paranoid and most of the options will slow down your site.

Create a new file somewhere on the webserver (mypsswrdfile.php) to which only web admins should have rwx rights to.

In it have them create a variable that holds the password.

$pass = "dbpass";

Include that file in your settings.php and use the variable for the password key.

"password" => $pass,


Set select list default value I have select list with options:

$options = array(0 => '0', 500 => '500', 1000 => '1000');

I'm trying to set it's default value to 500:

$form['price']['min']['#options'] = $options;
$form['price']['min']['#default_value'] = 500;

But this don't work.

I've never seen this problem. That default value should work. I would say try making the key a string and set #default_value as a string. The #options array may be being passed through array_merge  somewhere, thus rekeying integer keys. If keys are strings then that shouldn't happen.
Currently, your array looks like this:

$options = array(
  0 => '0',
  500 => '500',
  1000 => '1000',
);

But passing that array through array_merge can reorganize those integer keys to be in sequential order:

$options = array(
  0 => '0',
  1 => '500',
  2 => '1000',
);

If that happens then the 500 key simply doesn't exist. This is because array_merge does not like to preserve integer keys, but you can use strings to prevent it.
So, I think your array should look more like this:

$options = array(
  '0' => '0',
  '500' => '500',
  '1000' => '1000',
);

Then you can set your #default_value:

$form['price']['min']['#default_value'] = '500';

Otherwise, is there anywhere else where the default_value may be being overridden?

SOLUTION: Figure out that form_select_options doesn't handle #default_value at all. So I used #value property:

$form['price']['min']['#value'] = isset($_REQUEST['price']['min']) ? $_REQUEST['price']['min'] : $my_default_value;


How to teach PhpStorm to recognise drupal {table} SQL syntax? I'm dealing with some really old drupal project full of SQL queries. PhpStorm's understanding of SQL is very handy however I have problems with drupalism like {table_name}. IDE complains that <reference> expected, got '{'.

How can i set up PhpStorm so that it will understand that the string inside curly braces is just a table name? Or at least make it ignore the curly braces?

In PhpStorm Preferences > Tools > Database > User Parameters:

Check "Enable in string literals with SQL injection"
Add \{\w+\} to Parameter Patterns.

You may also want to modify the line with %\w+ to be allowed for language php for placeholders like %d. See screenshot and also JetBrain's PhpStorm blog post: Database Language Injection Configuration.

I don't know of any way to make PHPStorm recognize the Drupal SQL syntax.

But if you just want to debug a query that was created by Drupal, then you can remove the curly braces from the query after copying it to the PHPStorm query console.


Browsing private and public files in IMCE I have set up a public and a private file location (/admin/config/media/file-system).
The private file location is not under the Drupal directory ( it's /opt/private_files ).
I have set the "Default download method" to "Private local files served by Drupal."

I have configured a profile for IMCE ( /admin/config/media/imce ) called "User-1"
with a "Directory Path" of {root}/. "Including subdirectories".

I have assigned this profile to the role "administrator" under "Role-profile assignments" for both "PUBLIC FILES" as well as "PRIVATE FILES".

But when I access IMCE directly using mydomain.com/imce I only see the private files.

How can I switch or access the public files ?

While writing this question I found it:

You can access the public files like this:
mydomain.com/imce/public

and the private files:
mydomain.com/imce/private


Cant show Commerce Products in View on Taxonomy Term page My Commerce Products (not Product Displays) have a term reference field. On a taxonomy term page I want to show all the products tagged with that term.

If I create a view to show prodcuts (which I would attach as a block), I cant seem to use the term ID from the contextual filters to limit the results.

If I create a view of terms, then I cant find the relationship and fields to show the products.

Am I missing something or is this how Commerce Products work? Are they not available in Views the same way that nodes with the same term field would be?

This isn't an official source, but it might help you.

Don't attach a block on your taxonomy page. Instead, create the View as a page and set the URL (under path) to override the the taxonomy term page (e.g. taxonomy/term/%).

Under contextual filter use : Content: Has taxonomy term ID

For the filters, use the settings in the screen shot (in the screenshot, my taxonomy terms belong to a vocabulary called Shop Categories).

Hope that helps!

The taxonomy of the products are usually product attributes that need to be used in the reference of the product display. Otherwise you might need to add the same attribute to the product display


Add html to a node's title I have a Drupal 7 site and I'd like to be able to add an HTML link to part of the title of a node. By default Drupal has this as plain text. Is there any way that I can allow HMTL?

Example:

This is a title

That happens because template_process_page() contains the following code.

if (!isset($variables['title'])) {
  $variables['title'] = drupal_get_title();
}

drupal_get_title() calls check_plain().

// During a bootstrap, menu.inc is not included and thus we cannot provide a title.
if (!isset($title) && function_exists('menu_get_active_title')) {
  $title = check_plain(menu_get_active_title());
}

The only way you have to add HTML to the title is using hook_preprocess_page() and set $variables['title'].

Keep in mind that $variables['title'] is also used as value for the <title> tag, and browsers should not expect HTML tags inside that tag.

  Titles may contain character entities (for accented characters, special characters, etc.), but may not contain other markup (including comments).

To change just the node title, you should implement hook_preprocess_node() and set $variables['title']. By default, template_preprocess_node() sets it using $variables['title'] = check_plain($node->title);.
As side note, for the node title, Drupal 8 uses $variables['label'], not $variables['title'].

I had the same question and I found a great and simple module HTML Title. You can enter HTML markups inside your node title and it's done. At least, it was OK for me for italic terms.

EDIT : Indeed my answer deserves a -1, the module is now obsolete and creates strange things on node titles, forget it!


How do I sort or filter a View by proximity using Search API location? I am trying to set up a Solr Search View with Search API Solr and Search API location, witch is sorted by proximity an can be filtered by proximity.
To achieve that,

I created an search index, which indexes a geofield as latitude/longitude (under admin/config/search/search_api/index/INDEX_NAME/fields):
I created a View for the mentioned Search index and was able to add a proximity filter as contextual filter:

It is also possible to add the indexed Lat/Lon field to the field section of the View and set up a formatter showing the distance to a certain geolocation:

But there wasn't any field I could add to the sort section or the filter section of the View, that filters or sorts by proximity.
What do I have to do, to filter and sort a Search API Solr View by proximity?

If you want to filter based on some user selection, you can have PHP code which gets the value and filters result based on that.

Please check this http://murtuza88.blogspot.in/2014/11/use-drupal-location-module-to-filter.html for detail steps on how to filter view based on user selection.

You're wanting to sort the results by an arbitrary (unique values not stored in the database) values (distance). As said above, the most straightforward way to do that would be with php. The Views API is documented here and leads me to think that hook_views_post_execute() is the function you would need.

<?php
function hook_views_post_execute(&$view) {
  // If there are more than 100 results, show a message that encourages the user
  // to change the filter settings.
  // (This action could be performed later in the execution process, but not
  // earlier.)
  if ($view->total_rows > 100) {
    drupal_set_message(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }

  if ($view->name == 'job_distribution') {
    foreach ($view->result as $result) {
      // figure out the distance value
      // save it to the result array
    }
    // sort the result based on that value
    // maybe use http://php.net/manual/en/function.array-multisort.php
  }
}
?>

Good luck!


How to grant userpoints to users who perform a login 5 days consecutively? I need to know if a user has performed a login, for example, 5 days consecutively. The reason for this is I want to award User points to them.

For example:

User A performs a login on Monday, Tuesday, Wednesday, Thursday and Friday. (granted 10 points)
User B performs a login on Monday, Tuesday, Thursday, Friday and Saturday. (no points)

I'm trying to do this with Rules but failed miserably. Any ideas?

Note: I'm trying to use Rules condition to compare my_last_login values against today's date with an offset of -1 days but it always return False.

Statistics module in the core would work in this case.

Rule has to be triggered when a user is logging in and
you need to write Custom PHP Code in the Do Action part of Rule.
Like

if(check_user_logins($uid)){
  db_query("UPDATE <table> set points = points + 5 WHERE uid = %d", $uid);
}

function check_user_logins($uid){
  // Code to check consecutive user logins goes here
  if($logins >= 5){
    return TRUE;
  }else{
    return FALSE;
  }
}


How to display IMCE file browser in overlay or popup window? When users access the IMCE file browser from their user profile it gets integrated in the websites main content. I want it to be displayed in the administrative overlay or even as a popup. Does anyone know how to do that?

I have checked the configuration settings, but it doesn't seem to be that easy, or I overlooked something. I also checked the module ThemeKey, but I think that would be a little overkill.

Any help would be appreciated!

Using the Media module instead of IMCE provides a powerful popup media asset browser that integrates with WYSIWYG.

You can use an iframe with src=yoursite.com/imce. The iframe can be displayed anywhere in the page including the popups.


Drupal 7 Custom Search Result Page I am trying to create a custom page that display my resuslts which I receive after I search for a post.

I am having no luck, I am a total begginer in drupal 7, I googled and looked around here but I did not quite understood what I have to do.

What I tried:

function **themename**_preprocess_search_results(&$variables) {
  $variables['search_results'] = '';
  if (!empty($variables['module'])) {
    $variables['module'] = check_plain($variables['module']);
  }
  foreach ($variables['results'] as $result) {
    $variables['search_results'] .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
  }
  $variables['pager'] = theme('pager', array('tags' => NULL));
  $variables['theme_hook_suggestions'][] = 'search_results__' . $variables['module'];
}

Creating a search-results.tpl.php ( did not work )
The only module I have installed for search is the default search module.

Nothing seems to work. Thanks in advance

You are just processing the search results in your function but haven;t handled the output. Change the tpl.php to display the variables from your function rather than from the default search function.


Adding rel=canonical meta tag in comment paginated node pages I posted this question: Google showing pages with ?page=2 urls and also read this post from Google: http://googlewebmastercentral.blogspot.in/2013/04/5-common-mistakes-with-relcanonical.html

I understand that node comments whether paginated or not are of low importance with respect to the node content itself. So all the paginated node pages reached by clicking links in the bottom just above "Post New Comment"( as in attachment) should have rel=canonical pointing to the main node page.

So these pages:

example.com/node?page=1
example.com/node?page=2 and so on

should have "rel=canonical" in the head section of html page pointing to example.com/node.

Though as mentioned in the Google's blog, even "rel=prev" or "rel=next" may also be desirable in case of such urls.

So I need help how to add rel=canonical in those paginated node page. How can I do it?

It can be done using Nodewords module as described here:

  Nodewords project allows you to add meta tags to Drupal pages, both
  manually and automatically based on various settings. Paying attention
  to meta tags, such as keywords, description and canonical URL, may
  help obtain better search engine positioning.


INPUT query for cache_menu returns mysql #2006 error in MAMP This actually happens when I want to import a db from a live site to a local site in MAMP.

Running mac osx 10.6.8 and MAMP 2.0.5.

I googled this mysql error and most people seem to have this solved by increasing the memory_limit value in /Applications/MAMP/bin/php5.3.6/conf/php.ini. I set it to 512M. And yes I made sure MAMP is running php 5.3.6.

...anyway increasing the memory size didn't solve the issue obviously

then I went looking at the error logs under Applications/MAMP/logs/php_error.log and Applications/MAMP/logs/mysql_error_log.err but both don't have any recent log information at all actually which is quite bizarre as well.

What I can also tell you is that the last VALUE which the query wants to INSERT INTO 'cache_menu' is very very large.

Here's the query that gives the #2006 error:

INSERT INTO `cache_menu` (`cid`, `data`, `expire`, `created`, `headers`, `serialized`) VALUES ('links:admin_menu:tree-data:9942fb041052f49f910af3e0190b9115', 0x613a323a7b733a343a2274726565223b613a31303a7b693a333635313b613a323a7b733a343a226c696e6b223b613a33373a7b733a31343a226c6f61645f66756e6374696f6e73223b4e3b733a31363a22746f5f6172675f66756e6374696f6e73223b4e3b733a31353a226163636573735f63616c6c6261636b223b4e3b733a31363a226163636573735f617267756d656e7473223b4e3b733a31333a22706167655f63616c6c6261636b223b4e3b733a31343a22706167655f617267756d656e7473223b4e3b733a353a227469746c65223b4e3b733a31343a227469746c655f63616c6c6261636b223b4e3b733a31353a227469746c655f617267756d656e7473223b4e3b733a343a2274797065223b4e3b733a31313a226465736372697074696f6e223b4e3b733a393a226d656e755f6e616d65223b733a31303a2261646d696e5f6d656e75223b733a343a226d6c6964223b733a343a2233363531223b733a343a22706c6964223b733a313a2230223b733a393a226c696e6b5f70617468223b733a373a223c66726f6e743e223b733a31313a22726f757465725f70617468223[...]

Backup and migrate exports the database automatically without (large) values in the cache_menu table. Thus, re-exporting the database using the backup and migrate module solved the issue.


How do I place the registration form in the front page? I am using Drupal 7.

I clicked on Structure > Block > Add Block; I filled in the block title and block description. In the block body, I put in this code.

<?php
  $_GET['q'] = 'user/register';
  print drupal_get_form('user_register');
?>

I set the text format to PHP (PHP wasn't in the drop down options of text formatting so I added PHP to it), and I clicked on save block.

The block is now created but it's just empty. I can't see any sign up form.

Can someone please put me through? I'm new to Drupal.

I just discovered that I had to activate PHP Filter in core modules (administration > modules). So when I activated PHP Filter module, the registration block I created now shows the word "Array", and also some error in the log.

  Notice: Undefined index: user_register in drupal_retrieve_form() (line 764 of C:\xampp\apps\drupal\htdocs\includes\form.inc).
  Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'user_register' not found or invalid function name in drupal_retrieve_form() (line 799 of C:\xampp\apps\drupal\htdocs\includes\form.inc).

  Notice: Array to string conversion in eval() (line 3 of C:\xampp\apps\drupal\htdocs\modules\php\php.module(80) : eval()'d code).

However, the "create new account and login" menu is now showing; it is only not showing in the block I created for it. What is showing in the block is "Array"; when I click on either "register" or "log in," it takes me away from the front page (to the register page).

The user register form id is user_register_form. Please try it like:

$form = drupal_get_form('user_register_form');
print render($form);

Use the following code.

print(drupal_render(drupal_get_form('user_register_form')));


Other modules like the Devel module? I've just started learning Drupal, and the devel module is great and everything but I had a couple of questions about it:

Is it possible to change the output text when generating article or basic page content? For example, instead of using Latin Lorem Ipsum filler text, I'd like to be able to use something that puts out actual English words, like Candy Ipsum.
I noticed that when generating article content, it will also generate a small image to go with it, but the images are not of a uniform size. Is there any way to set it to use a fixed resolution?
This is more of a personal preference, but the user names it generates are a little hard to work around. Back when I worked with Django, I had whipped up a script that put together random user names using common first and last names I had compiled into a text file. Is it possible to do something like that here?

Any suggestions on how I could go about doing these things? Is there perhaps another module(s) I could use to get these functions?

I believe devel generate uses a pattern like [FIELD_NAME]_devel_generate() when deciding who/what to ask for generated data, and then devel implements those functions itself for the core fields.

Unfortunately I don't really see a way to alter this behaviour as there is no Factory pattern or similar that one could use to instantiate derivative/overridden functionality.

What my team usually does is creating content more to our liking in the install profile. This allows us to gradually build in some basic content that the client will want anyway into the development process, and we use a variable to tag nids that won't be useful one we go live, so that we can easily remove the junk content.

If we stick with using devel, here's what I would do:

Hack the module. The code you are looking for is in devel/devel_generate, and then split up into many files, mostly one for each type of content it creates.
Make the functionality generally useful.
Post a patch in the issue queue saying. "I wanted to use devel like this instead, is there a way to incorporate this into Devel?".

Drupal is Open-Source. Just dive in the source code my friend, and mash it up to your taste.

I would probably copy the devel module and rename it devel2, implement custom modifications  in there, but it`s just a matter of preference.


How do I make my site with pre-loaded content and pre-loaded config available to others without creating a distribution? I want to be able to provide a simple way for users to install a Drupal website that contains a certain set of content, contributed modules and custom content types. I also want to keep the process of developing this scenario as simple as possible for the developer.

I know that the standard way to do this would be to create a Distribution such as those that are listed at https://www.drupal.org/project/project_distribution. Another example is the Umami content available in a standard Drupal distribution. However, building a distribution seems to be quite a bit of work and should require a commitment to maintain that distribution if it is listed on the Drupal website. So, my question is whether there is a simpler way to allow users to install a website with some given content without my having to make the effort of building a distribution, since whatever I build will not be listed on the Drupal website.

The thought that there may be an easier way was prompted by my experience with some theme vendors. With some theme vendors, the process of installation involves only creating a database from an included SQL script and then starting the installation wizard and only having to input the database credentials. No other answers need to be answered in the installation wizard. It is almost as easy for the user as installing a distribution, and I am wondering if it may be easier for me as a developer to implement.

When I examine some of these theme installations that use this approach (e.g., News+ lite at https://www.drupal.org/project/newsplus_lite) there is no code in the docroot/profile sub-directory, so this approach cannot be using a standard install profile or distribution because that is where extra content or code would be stored for an install profile or distribution. From my investigations so far about creating Distributions or Installation Profiles, I have not yet read how such an approach would work or be implemented. So, I am asking if anyone knows how such an approach (as utilized in the News+ Lite and other similar installations) works and how I might duplicate it.

One of the support staff at MoreThanThemes was kind enough to provide some direction on how they do this. You can see the result in the structure of their free or paid themes. In short, the steps are pretty simple for what might be termed a cloned installation. The steps are basically the following.

Create a clone of the site that you want to install (https://www.youtube.com/watch?v=9NMRwkTzrCM describes that pretty well)
In the clone, overwrite/replace the /docroot/default/settings.php file with the docroot/default/default.settings.php file
Make a clone of the original database (e.g., using MySQLDump, PhpMyAdmin copy or drush sql-dump) and install it in a new database instance that you will use for the cloned site.

If you also have removed the Umami distribution and the minimal distribution from core, then the installation wizard will automatically bypass the choice for which install profile to use. In that case, the installation wizard only asks for the database information, where you will use the information for the cloned database. That will be all you need, and you will have a installed clone of your original website.

From my testing, it looks like the UUID of both sites are the same, just as if you had cloned the original site. So, the main use case from what I can see for this scenario would be if you wanted to share a copy of your site with other people, including the content (like the theme companies do). The only difference from a regular distribution like Umami or OpenAtrium from the user's standpoint is that they have to load the database file on their own before they do the installation. But from a developer's standpoint, this seems to be a much easier approach to sharing a website with the content and should be adequate for many users who want to test out your site.

I am surprised that this is not more widely documented and perhaps I have missed something here. But in my tests so far, this seems to be all that is needed. Hopefully this will help someone else who may need this simpler approach.


Drupal Form Button + "Are you sure"-Button I am trying to add an own JS function to a Drupal Core Form - think Config, Development, Clean Cache. This function basically just asks if the user is sure. Here is what I have so far:

Drupal.behaviors.confirm_delete = {

    attach: function (context, settings) {

         jQuery("#field-module-subsections-values input[id$='-remove-button']", context).bind('mousedown', function (ev) {

            ev.stopImmediatePropagation();
            ev.preventDefault();

            var followLink = window.confirm(question);

            if (followLink) {
                jQuery(this).click();
            }

            return false;

        });
    }
}

The problem I have is, that the function gets called before the click-event (thanks to mousedown), but the Ajax action on the button still fires. Maybe someone has a hint as to why?

Using hook_form_alter you can implement simple popups like this using #attributes.

 $form['submit']['#attributes'] => array(
  'onclick' => 'if(!confirm("Are you sure?")){return false;}',
 );

or

$form['submit']['#attributes']['onclick'] = 'if(!confirm("Are you sure?")){return false;}';


How to add a custom attribute to the script tag via drupal_add_js? As part of API implementation of Queue-it framework, I need to add extra custom attribute data-queueit-c into script tag, e.g.

<script
    data-queueit-c="MyClientID"
    type="text/javascript"
    src="//static.queue-it.net/script/queueconfigloader.min.js">
</script>

I'm aware you can add other attributes such as defer, however this one is custom.

I've tried the following code using drupal_add_js, but without luck:

drupal_add_js('//static.queue-it.net/script/queueconfigloader.min.js',
  [
    'type' => 'external',
    'data-queueit-c' => 'MyClientID',
  ]);

How this can be achieved?

It's old but I have the same problem (adding "crossorigin" attribute) and this is my answer :

There is an issue about it here : https://www.drupal.org/project/drupal/issues/1664602
@kenorb solution can't work because "drupal_add_js" add "script" tag automatically.
But... you can try this workaround (a little dirty) :
close the script tag and open yours without closing

.

drupal_add_js('//--><!]]></script><script src="//static.queue-it.net/script/queueconfigloader.min.js" data-queueit-c="MyClientID"><!--//--><![CDATA[//><!--', 'inline');

As for workaround, inline syntax can be used, e.g.

$js_code = "<script data-queueit-c='MyClientID' type='text/javascript' src='//static.queue-it.net/script/queueconfigloader.min.js'></script>";
drupal_add_js($js_code, 'inline');


How to add JavaScript code to a webform? I want to add JavaScript code to a webform. For example, to add things like onclick, onchange, mouseover function to webform's textbox, textarea, select, email, etc.

How do I do so?

The recommended way to add a JS to any form in Drupal is using #attached to the $form element.

In order to add the JS to a webform, you would have to implement hook_form_alter or hook_form_FORM_ID_alter, and add the #attached

function MODULE_form_webform_client_form_3_alter(&$form, &$form_state) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'MODULE') . '/MODULE.js',
  );
}

Then create the MODULE.js file inside the module directory, and write your JS there.

Refer to The Drupal JavaScript API, to see how to work with JS in Drupal way.

To load a script on a specific form , follow the following steps:

Copy webform-form.tpl.php to your sub-theme's root directory.
Rename it webform-form-NID.tpl.php, where NID is the node ID of your
webform.
Add the following code in above created theme file:

  drupal_add_js(path_to_theme() .'/scripts/SCRIPT_NAME.js');


HTML is being printed in the output The output from the below code is printing HTML. How can I make the "p" tags disappear?

answer 1

{% block paragraph %}

    {% block content %}

{{ content.field_accordion_title.0}}

      {% for grid_item in paragraph.field_accordion %}
        <button class="accordion">{{ grid_item.entity.field_accordion_list_item_headin.value }}</button>

        {{ grid_item.entity.field_accordion_list_item_text.value }}

      {% endfor %}
    {% endblock %}

{% endblock paragraph %}

Note:  I don't want to trim the HTML tags but actually render them. Perhaps drupal_entity() will help to render the output of {{ grid_item.entity.field_accordion_list_item_text.value }}. How can this be done?
Note: I don't want to trim the HTML tags but actually render them. Perhaps drupal_entity() will help to render the output of {{ grid_item.entity.field_accordion_list_item_text.value }}. How can this be done?

Try
{{ grid_item.entity.field_accordion_list_item_text.processed }} instead of {{ grid_item.entity.field_accordion_list_item_text.value }}
i.e. replace value with processed

I assume the string
answer 1
 is escaped and printed but you want to actually render the HTML tags.
In that case {{ grid_item.entity.field_accordion_list_item_text.value | raw }} should do the trick, assuming the variable is safe. If the value was entered by a user, take a look at this: How to safely render node body on a custom variable?.


Obfuscating email addresses displayed by Views? I'm working on a View that displays a user's email field as a mailto. Given this is a recipe for spam, I'm wanting some way of obfuscating it.

I thought I'd go with Invisimail, but it (and seemingly ever other similar project) relies on a text filter. Given that the User email field doesn't use input formats, this makes it useless for my particular application.

I suppose I could create a separate email field, but I'd really like to not have to.

In short -- How do I obfuscate a user email field displayed via Views?

Thanks!

Spamspan module will help you. It can obfuscate email addresses from email fields along with emails provided inline in text.

For email field - chooses Spamspan formatter in display settings.

We use custom tpl.php file for the user account email field. In this field we have the following code:

<?php
if (function_exists('spamspan')) {
  print spamspan($output);
} else {
  print $output;
}
?>


Is it better to use module_invoke_all(), or  module_invoke() and module_implements()? Using module_invoke_all('some_hook') is easy, but is this better for performance?

foreach (module_implements('some_hook') as $module) {
  $data = module_invoke($module, 'some_hook');
}

There is little difference; module_invoke_all() runs the following code:

function module_invoke_all() {
  $args = func_get_args();
  $hook = $args[0];
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

  return $return;
}

The only difference is that with module_invoke_all(), for example, func_get_args() is invoked only once, while when using module_invoke() func_get_args() is called each time module_invoke() is called; that is a marginal difference, though.
There are a few cases where module_implementing() and module_invoke() are used, normally when a module needs to know which module is invoked, such as in the case of search_get_info() that builds an array of information about the modules implementing search functions.

function search_get_info($all = FALSE) {
  $search_hooks = &drupal_static(__FUNCTION__);

  if (!isset($search_hooks)) {
    foreach (module_implements('search_info') as $module) {
      $search_hooks[$module] = call_user_func($module . '_search_info');
      // Use module name as the default value.
      $search_hooks[$module] += array(
        'title' => $module,
        'path' => $module,
      );
      // Include the module name itself in the array.
      $search_hooks[$module]['module'] = $module;
    }
  }

  if ($all) {
    return $search_hooks;
  }

  $active = variable_get('search_active_modules', array('node', 'user'));
  return array_intersect_key($search_hooks, array_flip($active));
}

Another example is image_styles(), which gets the list of all the image styles implemented by the modules, and that uses the following code:

  foreach (module_implements('image_default_styles') as $module) {
    $module_styles = module_invoke($module, 'image_default_styles');
    foreach ($module_styles as $style_name => $style) {
      $style['name'] = $style_name;
      $style['module'] = $module;
      $style['storage'] = IMAGE_STORAGE_DEFAULT;
      foreach ($style['effects'] as $key => $effect) {
        $definition = image_effect_definition_load($effect['name']);
        $effect = array_merge($definition, $effect);
        $style['effects'][$key] = $effect;
      }
      $styles[$style_name] = $style;
    }
  }

In both the cases, the retrieved information is put in an array where the index is the short name of the module.

It's probably better to use neither, and instead use drupal_alter().

As stated in the module_invoke_all() documentation,

  All arguments are passed by value. Use drupal_alter() if you need to
  pass arguments by reference.


convert a cck field from integer to string (text) How do I convert an existing integer field to text without having to copy paste manualy each value on each node and then delete the old integer field
I´m using Drupal 7.9

I tried altering the database.. on the definition of the field and the value type
I'm still getting errors

Notice: Undefined property: stdClass::$field_ubi_gps_x_format en field_sql_storage_field_storage_load() (línea 360 de /modules/field/modules/field_sql_storage/field_sql_storage.module).

Notice: Undefined variable: regexp en number_field_widget_validate() (línea 389 de /modules/field/modules/number/number.module).
Warning: preg_replace() [function.preg-replace]: Empty regular expression en number_field_widget_validate() (línea 389 de /modules/field/modules/number/number.module)

that is because the validation and presentation of the field has remained as integer..
I can't find in the DB where it stores that to copy if from another text field

I've so far altered field_data_field_FIELDNAME_THAT_WAS_INT changing field_FIELDNAME_value
from int to varchar and paradores_field_config . copying the blob data field from a text to ID of the FIELDNAME and using text on type and module fields

You would have to change the type in field data and field revision tables and add the FIELD_NAME_format column in both the tables.
Change the type and module columns in field_config to 'text'. And change the data column in field_config and field_config_instance tables.

For more info on this you can visit this link.


multiple (two at least) user registration forms I have built a registration form with a few custom fields, works fine. Now I need to another registration form, but with a dozen or so more fields. Both need to force drupal into its user registration/validation process.

it has to be done this way, I cannot just redirect a user to register first then fill out a survey.

Alex

You can achieve this using Profile 2 and Profile2 Registration Path module.

Profile 2

  Multiple profile types may be created via the UI (e.g. a general
  profile + a customer profile), whereas the module provides separated
  permissions for those

Profile2 Registration Path

  This module enables administrators to set unique registration paths
  per Profile2 profile type

if you want to add data to the user, add fields here (admin/config/people/accounts). see here

webform is a very nice module, where you can create forms via the UI, also offers stats etc.


get images URL in a twig template I have two content types, the first is Homepage and the second is SLider.
The Slider content type has multiple fields like title, ink, and image.
In the homepage content type, I have an entity reference field referring to the slider content type with multiple selections. I've created a template in my custom theme as node--home-page.html and want to get the sliders fields values, All is okay with me except the image. I cannot get the image URL.
My code:-

{% for slide in node.field_hoeme_slideshows %}
        {{ kint(slide.entity.field_home_slide_cta.uri) }} {# This is working #}
        {{ kint(slide.entity.title.value) }} {# This is working #}
        {{ kint(slide.entity.field_home_slide_snippet.value) }} {# This is working #}
        {{ kint(slide.entity.field_home_slide_image) }} {# ****** This is not working *****#}
{% endfor %}

As an alternative configuration using Field Collections. Instead of using two content types and a field reference...

{% for item in content.field_slide %}

{{ item.getFieldCollectionItem().field_h2.0.value }}

{{ item.getFieldCollectionItem().field_p.0.value }}

{% endfor %}

This is off the top of my head so double check the code.

Then you just create a field collection field on the home page content type called slide. Go to field collections, select "slide" and add the fields: link, slide_image, h2, and p.

{{ file_url(content.field_image['#items'].entity.uri.value }}

{{ file_url(content.field_image['#items'].entity.uri.value | image_style('1440px')) }}

Im not sure of your current setup.... but you might need to try something like "item in node.field_home_slideshows['#items']"

(note: you spelled home, hoeme)

inside do...

file_url(item.entity.uri.value)

This is twig valid:

{% for item in content.field_image['#items'] %}
 {{ file_url(item.entity.uri.value }},
{% endfor %}


How to make get for drupal behaviors to run only once? Drupal.behaviors.js_mod = {
attach: function (context, settings) {
     //$('body', context).append(chart);
    // $( '#drupal-myradar', context ).once
     $.get( "/web/js/mod", function( data ) {
        console.log(data);
      });
}

    }
})(jQuery, Drupal, drupalSettings);

Essentially this code is running multiple times while grabbing information from my controller code. I only want this to print out once to the console when the page is loaded.

If your script is high-level, which is most likely, then only run it when the context is equal to the document.
I found this trick in the autologout module and use it almost everywhere now:
Drupal.behaviors.dosomething = {
  attach: function attach(context, settings) {
    if (context !== document) {
        return;
    }
    // Do stuff here but still use .once when attaching behaviors.
  ...

That would do :
(function($, Drupal, drupalSettings) {
    let onlyOnce;
    Drupal.behaviors.js_mod = {
      attach: function (context, settings) {
          if (!onlyOnce) {
            onlyOnce = true;
            //$('body', context).append(chart);
            // $( '#drupal-myradar', context ).once
            $.get( "/web/js/mod", function( data ) {
              console.log(data);
            });
          }
       }
     }
})(jQuery, Drupal, drupalSettings);


How to add Jquery plugin to Drupal? Should I just paste the code in the main template file, or is there any other recommended way of attaching new Jquery plugins in Drupal 7?

The easiest way is just to add it on your theme's .info file:

scripts[] = js/my_jquery_plugin.js

The only exception is if you are adding an external resource (CDN/hosted script), in which case you should use drupal_add_js(), as explained by Jamie Hollern

another way is to add the following code to the page.tpl.php file
drupal_add_js(drupal_get_path('theme', 'path/to/your/plugin') . '/plugin.js', 'file');


The site crash when add a server I'm trying to use Search_api_solr and search-api.
I install the required modules and run the solr server and create a core.
But when I'm trying to add a server to my drupal 8 site, an error appears
Solarium\Exception\UnexpectedValueException: Neither collection nor core set. in Solarium\Core\Client\Endpoint->getBaseUri() (line 299 of /var/www/html/vendor/solarium/solarium/src/Core/Client/Endpoint.php).

I try to change the following block in Endpoint.php file to my data but it's not working.

protected $options = [
        'scheme' => 'http',
        'host' => 'xx.xx.xx.x',
        'port' => 8983,
        'path' => '/solr/',
        'collection' => null,
        'core' => 'my_core',
        'timeout' => 5,
        'leader' => false,
    ];

also, should the host include the http:// or only the ip address?
However, I try all above with no luck.
Any advice. Thanks in advance.

Collection is required in solr configuration. You'll need to create a collection you want to use for your site. Create using below command or by user interface of solr, then use the same name for the collection.

  sudo su - solr -c "/opt/solr/bin/solr create -c COLLECTION_NAME -n
  data_driven_schema_configs" // Only for ubuntu

Replace COLLECTION_NAME with the name of your collection you want.


Owl carousel doesn't work I can't understand how to install Owl Carousel module for Drupal 7.

I installed module from here - https://www.drupal.org/project/owlcarousel
And downloaded additional files from here - https://owlcarousel2.github.io/OwlCarousel2/

Put this folder in "sites/all/libraries" and managed fields for my content type. I can see few images on my page, but carousel doesn't work.

Here is the error from chrome console - "Uncaught TypeError: o.owlCarousel is not a function"
"GET https://mysite/owl.carousel.min.js?p44xlt net::ERR_ABORTED"

Bit old, but for module version 1, you have to use OwlCarousel 1
https://github.com/InchoonPark/meteor-owl-carousel-1/

Please check that you have installed jquery_update module.


How to add and condition in Query I have to fetch nodes where it doesn't have both roles(6,7) in it,at the same time  exactly.

I don't want to show role 7 nodes, but it some times have role 6 attached to it also ,at that time i want to omit those nodes.

This is the query which i wrote for that

$nids_result = db_select('node', 'n');
$nids_result->join('users','u','n.uid = u.uid');
$nids_result->join('users_roles','ur','u.uid = ur.uid');
$nids_result->fields('n', array('nid'));
$nids_result->condition('ur.rid', 7, '<>');
$nids_result = $nids_result->execute()->fetchAll();

But this is fetching me all nodes including role 7 also,because role 6 is also some times available in the nodes.

How do I write and condition where it checks for both 6 and 7 roles are available and omit those nodes.Thanks in advance.

By default it is and condition

$nids_result = db_select('node', 'n');
$nids_result->join('users','u','n.uid = u.uid');
$nids_result->join('users_roles','ur','u.uid = ur.uid');
$nids_result->fields('n', array('nid'));
$nids_result->condition('ur.rid', 7, '<>');
$nids_result->condition('ur.rid', 6, '<>');

// if you have devel installed check this.
dpq($nids_result);
$nids_result = $nids_result->execute()->fetchAll();

debugging the query with dpq will tell yuo the exact query that you can run on phpmyadmin and can see what you are missing.

Updated:

if you need query like

SELECT n.nid AS nid
FROM
{node} n
INNER JOIN {users} u ON n.uid = u.uid
INNER JOIN {users_roles} ur ON u.uid = ur.uid
WHERE ( (ur.rid <> :db_condition_placeholder_0) OR( (ur.rid <> :db_condition_placeholder_1) AND (ur.rid <> :db_condition_placeholder_2) ))

Code will be :

   $nids_result = db_select('node', 'n');
   $nids_result->join('users','u','n.uid = u.uid');
   $nids_result->join('users_roles','ur','u.uid = ur.uid');
   $nids_result->fields('n', array('nid'));
   $db_or = db_or();
   $db_or->condition('ur.rid', 7, '<>');
   $db_or->condition(db_and()->condition('ur.rid', 7, '<>')->condition('ur.rid', 6, '<>'));
   $nids_result->condition($db_or);
   $src = $nids_result->__toString();
   dpm($src);

Another approach is to use db_and(). Example:

$nids_result = db_select('node', 'n');
$nids_result->join('users','u','n.uid = u.uid');
$nids_result->join('users_roles','ur','u.uid = ur.uid');
$nids_result->fields('n', array('nid'));
$nids_result->condition(
              db_and()
                ->condition('ur.rid', 7, '<>')
                ->condition('ur.rid', 6, '<>')
);
$nids_result = $nids_result->execute()->fetchAll();


how to get correct user id on page I've added two custom fields to my user form - field_license and field_download_date. In my preprocess_page function, I'm doing this:

if(isset($vars['user'])) {
   $user_data = user_load($vars['user']->uid);
   error_log("userdata");
   error_log(print_r($user_data, 1));
}

I'm not trying to get the current user info, but a specific user. When I look at the error log, though, $user_data is printing out the info of the user I'm logged in as, not the user that's displaying on the page based on the URL (mysite.com/user/2). How do I get the data for the user based on the url?

For getting user based on current page, you can try to use $account = menu_get_object('user') code.
Var $account will contain user object.
Read more about this function here: https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_get_object/7

you can use
global $user;
$user_id = $ser->uid;


Theme Suggestion for overridding page-title.html.twig file? Is there a way to override the default page-title template using the theme suggestion. Like we can override node for article type as below,

For all nodes:    node.html.twig

For nodes of article type:    node--article.html.twig

same way,

for all page title: page-title.html.twig

for page title on article content type: ???

I tried many things like page-title--article.twig, field--page-title--article.html.twig, field--bartik-page-title--article.html.twig, node--article--page-title.html.twig etc.. these are not working. OR it is not possibel to do this with page-title file?

You can do this by adding your own suggestion. In your theme's ThemeName.theme file add a hook_theme_suggestions_HOOK_alter() for the page title:

// Add content type suggestions, e.g. page--node--article.html.twig.
function ThemeName_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {
  // Are we looking at a node?
  $node = \Drupal::routeMatch()->getParameter('node');
  // Object check required, sometimes it's a string, yes, really. Who knew?
  if (!empty($node) && is_object($node)) {
    array_splice($suggestions, 1, 0, 'page_title__' . $node->getType());
  }
}

Then create templates per node type, e.g. page-title--article.html.twig, page-title--custom-content-type.html.twig etc.

Edit: rather than the array_splice you can just push suggestions onto the array, e.g.:

  if (!empty($node) && is_object($node)) {
    $suggestions[] = 'page_title__node';
    $suggestions[] = 'page_title__node_' . $node->getType();
  }

array_splice() is just a trick I commonly use to position suggestions in the $suggestions array so I can control when they are picked up and used.

Yes. Turn on Twig debugging and view source.

It'll give the name of template suggestion to use.

Twig templates go down to the field level.


Admin Landing Page - How to create? Ok, I know there is a tutorial out there somewhere for this, I used it once before. Now, no matter how I search, I can't find it. Basically, I want to create this:

In other words, an admin landing page with sub menu items.

I have Panels and Page Manager installed and can create the admin page to the point where it shows on the path, but the sub-menu items don't appear. Instead I get this:

I've cleared the caches, made sure that sub-menu item is under this page, made sure that all the proper permissions are set . . . You know all the stuff that good Drupal developers are supposed to do.

So my two questions are this:

What am I doing wrong?
Can any one give me the step by step for creating what's on the first image with my own custom menu items? Or at least point me in the direction of some tutorials?

Thank you in advance for any help you can provide.

The reliable way to add and see menu options on admin pages is through [PHP] code, using hook_menu(). Be sure each URL is prefixed with admin/... (for example, admin/sub-section/page-1, admin/sub-section/page-2).

Here's a quick snippet paraphrased from the hook_menu() Drupal API docs:

  function mymodule_menu() {
    $items['admin/sub-section/page-1'] = array(
      'page callback' => 'mymodule_page1_view',
    );
    return $items;
  }

  function mymodule_page1_view() {
    // ...
  }

I haven't tried tricking the admin screen by adding custom links with "admin/*" at the front, which may or may not work - but the code option will definitely work, I've used that hook more than a thousand times.

in admin/config/system/site-information set the front page to admin/structure

or

go to admin/structure/menus. create a menu with all the links you want on your page. go to admin/structure/blocks - find your menu and configure it to show on the page you want.


menu block or view that shows only siblings and parents It seems like this function was removed in drupal 8 so I am trying to find a solution that doesn't involve created a large amount of blocks or hard coding something. (Best would be a block or a view)

I have menu structure like this:

Parent 1
- Child 1.1
-- Grandchild 1.1.1
-- Grandchild 1.1.2
- Child 1.2
-- Grandchild 1.2.1
-- Grandchild 1.2.2
Parent 2
- Child 2.2
-- Grandchild 2.2.1
-- Grandchild 2.2.2

When I am on Grandchild 1.1.1 I want to see only the entire tree of Parent 1 (that means parent 1 plus all of its child and grandchild items), nothing from Parent 2 and below.

It seems this question has an ongoing patch at https://www.drupal.org/node/2811337 (which i found just after offering the bounty! :)

You can do this with css if there is no quick fix available by drupal


Removing the upload button in managed files I want to save a image file  into my custom content type using forms api and node_save().

The below code works fine but I also get the upload button as it default in managed_file .

I don't want the upload button. So I tried type=file but it did not work. How can I remove the upload button ?

Also if you just select the file and submit the form it works so I really need to just find a way to remove the upload button.

$form['image'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#upload_location' => 'public://my-files/'
);

The work to separate out the managed_file element is done in file_managed_file_process(), which is the default #process function for that type of element.

To hide the upload button you need to implement your own simple #process function for the element:

function MYMODULE_my_form($form, &$form_state) {
  $form['image'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#upload_location' => 'public://my-files/',
    '#process' => array('MYMODULE_my_file_element_process')
  );

  return $form;
}

function MYMODULE_my_file_element_process($element, &$form_state, $form) {
  $element = file_managed_file_process($element, $form_state, $form);
  $element['upload_button']['#access'] = FALSE;
  return $element;
}

Adding a element process hook works but seems like overkill to me.  in situations like this where its just an visual thing, CSS is the best way to go IMO since every upload button has its own id anyway.

#edit-image-upload-button{
  display:none;
}


logging into development instance of Drupal Ive rsynced the directory structure from mywebsite.com to mywebsite.local ( on my LAN)
and copied the DB .
the website mywebsite.local displays the website, but i cant log with the admin user/pw from the production site .
The DB tables look the same to me.  Its a single site and in sites/default/settings.php it points to DB host is 'localhost'
Tailing apache access.log and I can see the .local site is served from localhost

Do I need to change anything else  ?

You can try login with https://drushcommands.com/drush-8x/user/user-login/

drush uli admin

Which will give you a login link for user admin

If you invoke it without a username it gives you a login link for user 1

drush uli


What is the correct way of logging in through services from android? I currently have an app in development where I use services 3 on drupal 7 to login to my site. I do this by simply passing in the username and password parameters to a json object and use httppost to post them to service endpoint. Using the response I grab the cookie and store it in sharedpreferences on android which is used in all the following requests. I have this cookie set to be used for several days so the user wont require login again. Do I have any reason to be concerned about the security of this (I dont store any passwords) and if so what are the extra steps I can take and how to beef up the security but still allow for users to remain logged in? I have played around with the oauth module a bit but it seems rather complicated to implement on both drupal side and android. If oauth is my best option what are the steps to take to implement it with drupal and android?

You can use Android AccountManager over https to be more secure.
Like this Drupal 8 Android app at https://github.com/onedrupal/One-Drupal-Android.

You should definitely be doing some sort of encrypted key exchange, otherwise someone could post the login info to their own server and respond with a positive result!

I've never used the module you're referring to, but Drupal bootstrap is VERY easy to set up.


How can I rename a menu machine name in drupal 8 I ve migrated my D6 site to D8. And now I'd like to rename my menu machine names(not the system menus my custom menus) to a different ones. I'd want to do this either on database or from code.

Any ideas??

I also faced the problem when I needed to rename the machine name of my custom menus. In my case, I needed to remove hyphens in the machine name (this is a known issue https://www.drupal.org/project/drupal/issues/1353064), because some modules don't support hyphens. How I fixed it:

First of all you need to update already existing menu items (bundle, name, parent and etc.) I did it directly in a database through hook_update in your_custom_module:

function your_custom_module_update_8008() {
  $database = \Drupal::database();

  $menus = [
    'example-menu-machine-name-1' => 'examplemenumachinename1',
    'example-menu-machine-name-2' => 'examplemenumachinename2',
  ];

  foreach ($menus as $old_machine_name => $new_machine_name) {
    $database->update('menu_link_content')
      ->expression('bundle', "REPLACE(bundle, :old_value, :new_value)", [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->execute();
    $database->update('menu_link_content_data')
      ->expression('menu_name', "REPLACE(menu_name, :old_value, :new_value)", [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->expression('bundle', "REPLACE(bundle, :old_value, :new_value)", [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->execute();

    $database->update('menu_tree')
      ->expression('menu_name', 'REPLACE(menu_name, :old_value, :new_value)', [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->expression('id', 'REPLACE(id, :old_value, :new_value)', [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->expression('parent', 'REPLACE(parent, :old_value, :new_value)', [
        ':old_value' => $old_machine_name,
        ':new_value' => $new_machine_name,
      ])
      ->execute();
  }
}

Rename these names in configs. Your IDE should help with this. Don't forget also about renaming files for configs. For example:
system.menu.example-menu-machine-name-1.yml to system.menu.examplemenumachinename1.yml

If you have custom templates for menus also rename them:
menu--example-menu-machine-name-1.html.twig to menu--examplemenumachinename1.html.twig

Adjust classes in CSS|SCSS files, because they will be changed after renaming. Use IDE for this, it will save time :)

Run your build process locally and check results.

Take the dump of the database from the production and run a build with this database locally. Please compare menus between the local version and the production on the frontend.

I'm not sure but you can try node clone and then clone a menu after that you can set the machine name.


How to create an extra field in the profile module to only accept the numeric values? I am creating extra fields in the user registration form. for this I am using the profile module.

In this module there is no option form creating a text field which should only accept the numeric values just like in drupal 7.

So how will I create such field in the user registration form?

Any idea?

Install CCK module. Enable the number module that comes with CCK module. Once you enable the module you can able to add integer field to the Profile Content type if you are using content_profile module to add fields to registration.

See the screenshow below that i just got to do it using CCK, Number, Content Profile module in Drupal 6.

You can add a custom numeric validation to profile form using form alter. First Add single line text box to profile form then with form alter define custom validation function.

function module_name_form_alter(&$form, $form_state, $form_id){
  if ($form_id == 'profile_form_profile') {
      $form['#validate'][]='numeric_validation';
  }
}

function numeric_validation($form_state){
   //the form state variable will contain your text box value,
   //do your custom validation
   //if not numeric add error
      form_set_error("validate",'You must enter numeric value');
}


How do you change the email recipient of drupal 7 webform based on checkbox value using hook form alter? How do you change the email recipient of drupal 7 webform based on checkbox value using hook form alter?
I have a group of checkboxes (Texas, DC, Maryland, Virginia). I would like to change the recipient if Texas is checked and use the default for the other options. I do not want to change the key of the checkbox component to the Texas email address because I need to state which location was selected in the email template.

You do not need to use hook_form_alter for this, you can set this up in Webform on admin, here is how:

Go to the Edit interface of your webform
Go to E-mails
At the bottom, choose 'Component value' and choose your checkbox field, click Add http://cl.ly/image/1K3V2N3k3q30
At 'Component e-mail options' you can specify an email address for each option http://cl.ly/image/1g3c1r15060r

Description below says:

"You may enter an e-mail address for each choice. When that choice is selected, an e-mail will be sent to the corresponding address. If a field is left blank, no e-mail will be sent for that option."

This is one solution that works but I'm sure there is a more Drupal friendly way to do it.

I basically created a hidden input field called email recipient with the default value as the default email address. Then used jquery to change it's value depending on if the checkbox is checked or not.

    $('#checkbox').click(function() {
  $("input[name='submitted[email_recipient]']").val($(this).is(':checked') ? 'email1' : 'email2');
});

Then in Drupal admin under webform emails, set 'Email to' as the hidden input field. Also unchecked the field from the list of available fields in the email template so it doesn't get printed in the emails that get sent out.


Date Module / Date Repeat: Hourly or Minutely Recurrence? I'm setting up a Drupal 7 based calendaring system ,and the Date module has been super amazing; it does pretty much everything I need out of the box. However, correct me if I'm wrong, but it doesn't look like there's a way to set an event to reoccur, say, once every hour.

Do you have any idea for the best way to accomplish this?
I know PHP fairly well, so I'm game for writing code, but I have no idea where to start. Do I need to create a custom module that implements the Date Repeat API? What form would take, and how would it integrate with the existing Date module? Is this an unreasonably huge undertaking for a Drupal newbie?

Recurring events are handled in good old unix cron, see (http://drupal.org/cron). But there is a more, Php way .. Poor Man's Cron, see http://drupal.org/project/poormanscron (in D6, part of core in D7).

Basically, since some hosts didn't allow cron jobs Poor Man's Cron simply "hooked" a bit of code into each page using Ajax. If an amount of time had past it would run cron.php (which in turn calls drupal_run_cron()).

Either way ... you need to put your task into the cron queue, make sure your site is set up correctly and let the core system execute it. If your going to use a custom module see

http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_cron_queue_info/7


Node Access table goes empty I currently have a project where I am inserting mulitple records into Drupal using node_save. Its usually a couple of hundred at a time. For some reason, sometimes the node_access table ends up empty, resulting in the data "appearing" deleted to the users.

Does anyone know what could possible be happening?

I have reviewed the node_save code and notice is does run a call to rebuild the node_access table via node_access_acquire_grants($node). Currently I have no modules implementing node_access hooks.

My one thought was to just call node_access_rebuild() once I've finished inserting. I also run the process a few times every hour.

Side Note: Drupal may not be the right system for the bulk inserts and volume, but that is not the discussion I wish to have on this question.

The only moment where the node access table could be empty is when node_access_write_grants() (or node_access_rebuild()) deletes the content of the table before to repopulate it.
In the case of node_access_write_grants(), the table could become empty only if the table contained the access data for a node; in the case of node_access_rebuild(), the table becomes empty in any cases.

Sometimes the all entry can vanish, as node_access_acquire_grants() adds that entry only if no modules returned access records for the node passed as argument to the function, and node_access_rebuild() adds that entry if no module returned access records.

To notice also that, in the case the $realm passed to node_access_write_grants() doesn't match with the value contained in $grant['realm'] (for all the grants passed to the function), then node_access_write_grants() will delete the access records for the node passed as argument, but it will not save any access records.

// Only perform work when node_access modules are active.
if (count(module_implements('node_grants'))) {
  foreach ($grants as $grant) {
    if ($realm && $realm != $grant['realm']) {
      continue;
    }
    // Only write grants; denies are implicit.
    if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
      db_query("INSERT INTO {node_access} (nid, realm, gid, grant_view, grant_update, grant_delete) VALUES (%d, '%s', %d, %d, %d, %d)", $node->nid, $grant['realm'], $grant['gid'], $grant['grant_view'], $grant['grant_update'], $grant['grant_delete']);
    }
  }
}

The same can happen if a module calls node_access_write_grants() using the default value for $delete, and there aren't modules implementing hook_node_grants().
In these cases, the node access table can become empty if the table contained data only for the node passed as argument to node_access_write_grants().

The node_access table is only populated if you use a node access module.

Some examples are Content Access, Taxonomy Access Control Lite, or Node Access.


Spam filter in signatures? Since otherwise great spam module does not check user signatures for spam, I have hard times fighting spammers who just put their spam links in their signatures in the forum so basically they rendered my custom spam filters useless.

I appreciate if you have some suggestions to resolve this problem.

OK, a better answer in the context of forum signatures only ( assuming D6 forum_signature module ) could be

Preprocess the signature.tpl.php template file and add the spam check

in template.php, function sig might be THEME_preprocess_signature, so try both, if first doesn't work.

function THEME_preprocess_signature_forum(&$variables){
  $content = $variables['signature'];
  $test = spam_content_is_spam($content, 'signature_forum');
  if (!empty($test['is_spam']) && $test['is_spam']){
   $variables['signature'] = t('This signature has been removed by our spam filter, please contact the site administrator for assistance');
  }

}

Then clear theme registry cache.

I don't use those modules myself, but such an approach, with a little tweaking, could work.

Ban any spammers by IP address, either:

One at a time from Admin > Config > People > IP Blocking
Block the range at the webserver config level ( firewall, virtualhost or .htaccess )

You may also want to add reCaptcha to user registration, if suitable.


Views fields as Columns in table I have a content type called Pets, which only has title and description. In Pets there are only 3 data (set by Admin) Cats, Dogs and Mouse. User can select only from these data and cannot add more Pets.

After the Girls register in the site they can hit the checkbox to select the pets they have in their profile.

However, I want to have a Views table where I want to list the Girls' profile like: (that's the table I wanted to make)

Name ------ Age -------- Dogs ---------- Cats ----------- Mouse
Tina ----------- 21 ------------ Yes ---------------- No ----------------- No
Lita ----------- 27 ------------- No ---------------- Yes ----------------- Yes

When I add Pets title in the views it just shows as:

Title
Dogs
Cats
Mouse

but I want to change the fields(dogs, cats, mouse) as Columns and have Yes or No in the rows. I just tried Views Flipped Tables Module but wasn't able to do with it. any suggestions please ?

You could try to use Views aggregation.

Define the relationships of the fields.
Under Advanced > Other enable aggregation
Add fields of the animal nodes and define the grouping as "count" in the field's aggregation settings.
Define no results bahaviour as "No" and rewrite the result as "Yes". Define 0 as "no result". All in the field settings.

Hope that helps!

cheers,
j

In View -> "HEADER" section is available know.. Write HTML as separate table.

Name	Age	Dogs	Cats	Mouse

and for field settings make it as grid.. and also you require above Views Flipped Table module. It's my small suggestion.


Image field, how add title field? Here drupal have a field for set a description for each images:

How I can add a custom field for each image please ?
By example a "Title" or "Author" field ?
Thanks.

Have you tried "ImageField Extended"? Alternatively, you could create a new content type which consists of an image and any number of fields that you want.


How to convert an existing field from Text to Link in Drupal 7 If I have a field in Drupal which of type Text, how do I convert it to to allow a link if the field is already being used on the site without losing data?

Install the Link module in order to allow link fields.
In your database, run:

UPDATE field_config set type='link_field', module='link' WHERE field_name='YOUR_FIELD_ID'
Then run the following query:

UPDATE field_config_instance SET data='a:7:{s:5:"label";s:LENGTH_OF_YOUR_FIELD_NAME:"YOUR_FIELD_NAME";s:6:"widget";a:5:{s:6:"weight";s:1:"9";s:4:"type";s:10:"link_field";s:6:"module";s:4:"link";s:6:"active";i:0;s:8:"settings";a:0:{}}s:8:"settings";a:10:{s:12:"validate_url";i:1;s:3:"url";i:0;s:5:"title";s:8:"optional";s:11:"title_value";s:0:"";s:15:"title_maxlength";s:3:"128";s:13:"enable_tokens";i:1;s:7:"display";a:1:{s:10:"url_cutoff";s:2:"80";}s:10:"attributes";a:5:{s:6:"target";s:6:"_blank";s:3:"rel";s:0:"";s:5:"class";s:0:"";s:18:"configurable_title";i:0;s:5:"title";s:0:"";}s:10:"rel_remove";s:7:"default";s:18:"user_register_form";b:0;}s:7:"display";a:1:{s:7:"default";a:5:{s:5:"label";s:5:"above";s:4:"type";s:12:"link_default";s:8:"settings";a:0:{}s:6:"module";s:4:"link";s:6:"weight";i:16;}}s:8:"required";i:0;s:11:"description";s:0:"";s:13:"default_value";N;}' WHERE field_name='YOUR_FIELD_ID'
(optional) Go into the table for your field name (field_data_field_YOUR_FIELD_NAME) and remove the column field_YOUR_FIELD_NAME_format
In the same table as #4 above, change the column field_YOUR_FIELD_NAME_value to field_YOUR_FIELD_NAME_title. This will make the previous values for these text fields now become the title of any links placed in the new Link field.
In the same table as #4 above, add the columns field_YOUR_FIELD_NAME_url VARCHAR(2048) ALLOW NULL, and field_YOUR_FIELD_NAME_attributes MEDIUMTEXT ALLOW NULL

This solution worked well for me.

https://drupal.org/project/node_convert is another option - create a new template, add an action and use views bulk operation to convert them all..


Multilingual "labels" in views fields? Is there any way to setup multilingual labels in views' fields.

Let´s say I have the ´title´ field and it shows the label ´My Title:´. Then as my site is bilingual (english-spanish) I need to have that label to ´Mi Titulo´ depending on user language.

How can I solve this?
Any module to expand views module?

You want to look into Internationalization Views, which allows you to translate labels and such in a view.

I used this method which is probably bad practice, but I couldn't find another solution.

With your file manager/FTP go to core language file: Example is for the installed German language
[mysite]\profiles\standard\translations\drupal-7.0.de.po

Open in a utf-8 reader.
You will be able to see a list of all English strings and their German counterparts: Example
msgid "Countries"
msgstr "Lände"

Add your labels (strings) and their translations and save.
[-all good but this library must now be reread in-]

Using your web interface go to www.mysite.com/admin/config/regional/language
Delete the language you are editing. This will clear the DB of the translations but the edited file will remain untouched.
Now select "Add Language" and select your language again. The system will now read-in your updated list.


How do I migrate CCK filefield? I'm migrating a Drupal 6 site with CCK filefields to Drupal 7. I installed the Drupal 7 CCK module, and I'm ready to do the migration except for a filefield field.

Migrate fields states:

  Missing field module: 'filefield'. This field cannot be migrated.

The filefield module isn't available for Drupal 7. Is there an other module, or any other way of migrating a Drupal 6 CCK filefield to Drupal 7 fields?

Update

I just realized it's an audiofield. Basically it's a filefield with an audio widget.

Not sure whether I should call this a solution or a workaround. Anyway:

In D6 I removed audio representation of the filefield. This makes it an ordinary filefield. Then migrated to D7 using the CCK migration kit and then added the audio representation again. Done.

Please read Migrating D6 Content Construction Kit (CCK) to D7 Fields.

Basically you've to download CCK module for 7.x and it has the functionality to migrate these fields.


Multiple Field , same ajax callback I created a custom field. The hook_field_widget_form has an submit element with an ajax callback:

  //Add more
  $element['add_zone'] = array(
    '#type' => 'submit',
    '#name' => $field_name . '-add_more-' .'name',
    '#value' => t('+'),
    '#limit_validation_errors' => array(),
    '#submit' => array('dms_polygone_add_more_add_one'),
    '#ajax' => array(
      'callback' => 'dms_polygone_add_more_callback',
      'wrapper' => 'zones-fieldset-wrapper-'. $field_name,
    ),
  );

I add 2 fields of my custom field type to a node. Ex: field_polygone (field type: polygone) and field_polygone_2 (field type: polygone).
When i press the 'add_more' button of my first field_polygone, my callback function 'dms_polygone_add_more_add_one' thinks the trigger element is field_polygone_2.

Callback function:

function dms_polygone_add_more_callback($form, $form_state) {
  //@todo: $i gebruiken voor veld als er meerdere waardes zijn toegestaan.
  $parents = $form_state['triggering_element']['#parents'];
  return $form[$parents[0]][$parents[1]][$parents[2]]['zones'];
}

$parents[0] is the field_name => When i press 'add_more' , the $parents[0] variable in the callback function should be 'field_polygone', but its field 'field_polygone_2'.

How can is solve this problem? Why does the callback function think the trigger element is field_polygone_2 instead of field_polygone.

I had a similar issue in Drupal 8. I had one form with multiple entities (not drupal entities) that had an identical subset of fields and each had their own button. My $form_state->getTriggeringElement() would always show the last of these buttons, no matter which I clicked. My issue was that I was not setting #name on the buttons and they were both defaulting to op (they had the same #name value). Explicitly setting a unique #name for each button resolved my issue.

The following link helped me to change 2 elements from a form through AJAX callback, whitout having to return the whole $form :

Is it possible to replace more than one form element (wrappers) triggered by only one #ajax trigger element?


Using Page Title with Node Tags I'm using the following modules

Meta Tags
Page Title

I need to be able to make the sites title work like this:

Use the title set in Meta Tags for each Node first of all, if this isn't set then default to the Page Title module.

If this isn't set, just use the pages title.

How do I set a precedence for the titles?  Do I have to hook into html_head_alter?

Any help is greatly appreciated,

Cheers

Have you checked the auto nodetitle module with the token Module. Then you can create the node Titles with tokens.
Check also the Automatic Entity Label i think its better for your Usecase

Er, just checking, think I was actually referring to the master metatags settings page when using the word 'global' there.

Whilst debugging I changed my settings on the node itself, but also in admin/config/search/metatags
I thought I would need to set the rule 'globally' in admin/config/search/metatags, as this is where the content types get their configuration settings form.
Then i assumed, this could be overridden on a per node basis by setting the page title on the node itself.

I've added some attachments to confirm my settings.


How to db_select DISTINCT on a particular field in Drupal 7? I understand that you can specify ->distinct() on the db_select statement so that it only returns distinct values when looking at ALL fields. But what I want is to return distinct values by only looking at ONE field. Here's my code:

$event_table = db_select('my_table', 'e')
    ->distinct()
    ->orderBy('e.time', 'ASC');//ORDER BY
$event_table->join('node', 'n', 'e.nid = n.nid'); //JOIN node with events
$event_table->groupBy('e.time');//GROUP BY time
$event_table->fields('e')//SELECT the fields from events
    ->fields('n',array('type','status','title'))//SELECT the fields from node
    ->orderBy('e.time', 'ASC');//ORDER BY

$result_event_table = $event_table->execute();
$result_event_table = $result_event_table->fetchAllAssoc('time');

Suppose I want the distinct column to be e.nid. You'd think  ->distinct('e.nid') would work but it still returns distinct values based on all fields (i.e. distinct(columns1, column2, column3, etc).

Assuming you're trying to get to roughly this query:

SELECT DISTINCT e.nid AS nid, e.time AS time, n.type AS type, n.status AS status, n.title AS title
FROM
{my_table} e
INNER JOIN {node} n ON n.nid = e.nid
GROUP BY e.time
ORDER BY e.time ASC

You would use:

$query = db_select('my_table', 'e')
  ->distinct()
  ->fields('e', array('nid', 'time', 'foo', 'bar'))
  ->fields('n', array('type', 'status', 'title'))
  ->groupBy('e.time')
  ->orderBy('e.time');

$query->join('node', 'n', 'n.nid = e.nid');

If you use this query then, its provide proper distinct query.

<?php

$select = db_select('service_payment_transaction','o');
$select->distinct('o.transaction_id');
$select->innerJoin('users', 'u', 'u.uid = o.user_id');
$select->fields('o');
$select->fields('u');
$select->condition('o.service_gv_code','','!=');
$select->range($start,$page_count);
$select->groupBy('o.service_gv_code');
$select->orderBy('transaction_id', 'DESC');
$result_query = $select->execute();


How to display a block only for an article with a specific node id? I have quickly seen view reference and context module. Though they can display a view or block to a specific content type, I'm not sure if they can do it within a specific node.

As an example: I want to display a block only for an article with node id 3.

Can that be done?

I would steer clear of using PHP for block visibility.  If you type something wrong you can break any number of things.

Just go to your block settings, and take a look at the vertical tabs at the bottom of the page.  The first option is Pages.  Just change the radio button to "Only the listed pages" and enter node/3 in the box.

EDIT

If you use the Views Reference module mentioned in your question, then you can quite easily embed a Views block as one of your fields just as any other field.  The field itself can't be exclusive to a node ID, only an entity type.  However, you could just leave it blank for the other entities of the same type and use Field Permissions if you are worried about other people using the field incorrectly/at all.

One unrelated helpful hint with Views Reference - I generally tag my "reference-able" views with the same tag (i.e. Embeddable, Referenceable e.t.c.).  then you can easily select which Views to make available to the Views Reference field.

You MIGHT be able to embed blocks with Entity Reference combined with BEAN or Boxes, but I'm not 100% sure.  Failing this you are probably looking at breaking up the entire $content variable in the template and embedding it yourself (which would mean much more maintenance if fields get added or removed), using Views and turning the whole content types into blocks that can be positioned (MUCH effort).

NEW

Enable php filter module ,  add new content in body section  do something like this picture

(load your module accrding below notes)

if we wanted to place this custom block into a page, we would simply substitute these values into our PHP code snippet (which we place in a node (page or other content type)) as follows:

Drupal 7

<?php
$block = module_invoke('block', 'block_view', 26);
print render($block);
?>

Drupal 6 And Earlier

<?php
$block = module_invoke('block', 'block', 'view', 26);
print $block['content'];
?>

Notice that the middle two terms ('block', 'view') always stay the same. You're simply updating the first and last term.


How to change sender email Id using hook_mail_alter How to change the sender email id for some emails, using hook_mail_alter. The default SMTP configured email ID is 'test@myfirstdomain.com'
The subject gets altered correctly using the hook_mail_alter, however, the email which I receive is still from the default configured email 'test@myfirstdomain.com'.
function test_mail_alter(&$message) {
 switch ($message['key']) {
  case 'activation':

    $from = "test@myseconddomain.com" ;
    $message['from'] = $from;
    $message['headers']['From'] = $from;
    $message['headers']['Sender'] = $from;
    $message['headers']['Return-Path'] = $from;
    $message['subject'] = 123;
    break;
}

}

According to the documentation:
/**
 * Alter an email message created with MailManagerInterface->mail().
 *
 * Hook hook_mail_alter() allows modification of email messages created and sent
 * with MailManagerInterface->mail(). Usage examples include adding and/or
 * changing message text, message fields, and message headers.
 *
 * Email messages sent using functions other than MailManagerInterface->mail()
 * will not invoke hook_mail_alter(). For example, a contributed module directly
 * calling the MailInterface->mail() or PHP mail() function will not invoke
 * this hook. All core modules use MailManagerInterface->mail() for messaging,
 * it is best practice but not mandatory in contributed modules.
...

Can we check if the mail is sent MailManagerInterface->mail() like this and not any other way.


How do you functional test your Commerce Kickstart 2.0 projects? Since Commerce Kickstart 2.0 has its own Drupal installation, I don't see how to use SimpleTest with it.  I did find this documentation for the regular Drupal Commerce, not Commerce Kickstart 2 from what I can gather.  When I try to find what it alludes to in this documentation (CommerceBaseTestCase ), this does not exist in the Commerce Kickstart install that I can find.

So, how are people testing with Commerce Kickstart 2?  Let me be clearer with my question.  I have already installed Commerce Kickstart 2 and done some development.  I now want to create products and other elements programatically using SimpleTest to do functional testing.  However, SimpleTest starts with a clean install of Drupal.  This is not possible to use with Commerce Kickstart 2.0 because it has its OWN drupal version, and its not just a set of modules that I could enable programatically.

You can install the Commerce Kickstart 2 on your local environment and it would automatic have some data. If you do not know have a development environment I would recommend you to use Lazy Dubuntu (if you wish to build it on Ubuntu computer) or Acquia Dev Desktop 2 for Mac or Windows.

If you do not want to used your local environment you can use Pantheon to test it out for free.

If you want to playaround:

Free https://pantheon.io/
Free https://insight.acquia.com/free/register
Free http://simplytest.me/


Embedding images in a block from url How do I embed a URL in a block which is displayed as the linked image on the site?

For any source or path of any thing in drupal site use src like this. It will work everywhere.

<?php $src = base_path() .'sites/files/logo.png'; ?>

This src use like

<img alt="logo" src=" <?php echo $src ; ?>">

Enable PHP filter module that come with core module.

and in Block Body Choose Text format as PHP CODE.

I assuming block is created using Block module(Block UI)

I found the answer - rather easy really.... the module Image Block solves the whole problem for those of you who might see this post asking yourself the same question!

EDIT
The module simply creates an image block as said - it adds a "Add image block" to the block admin page. On the page you can choose to upload a picture - so you simply have to download the image from the URL and upload it in the block.
Hence it does not exactly solve the problem but this is a workaround.


Database query in template.php Is it ok to query the database in a template.php file of a sub-theme. If not where do I put it? Below I have function that is querying the database and it works fine but I want to make sure I doing it the right way =).

function inTheTemplateFile() {
   $query = db_query("SELECT tid FROM taxonomy_menu");
   return  $query->fetchAll();
}

The template should idealy not be used to do database queries or other code that belongs in the Model or Controller of the MVC pattern.
The problem is that it is impossible to have a perfect implementation of the MVC pattern in Drupal.

What I mostly use as a rule of thumb is this:

Is this functionality that belongs to a module? Then put it in a module.
Would I have to copy this to a new theme if I made a second one? Then put it in a module (or parent theme if it should be in a subset of themes).
Does this function get/compute data or results which should be provided by a module? (like fetching user-data or a list of items) Then put it in a module.

In general the theme should only contain HTML, JS, CSS and a minimum of PHP used for simple loops, printing and simple conditional statements.

So the answer to your question would be; Probably not, it should probably be in a preprocess function or a getter function (like book_get_books()) in the module.

Edit: As Clive points out in the comments, Drupal does not strive to be fully MVC. The MVC pattern is only used to make it clear what belongs in the template, the controller and view don't really exist in drupal. Even the view is not as clear cut as it is in something like Symfony or Zend framework.

You should never use query database on your templates.

Instead, data should come from views, and after, from a controller o event that render this view


taxonomy_get_tree return only few terms i have a problem with taxonomy_get_tree().

I want to get all tags from taxonomy. Tags's vocabulary ID (vid) is 1. When I check this in database there are about 4000 terms. If I use taxonomy_get_tree(1) it returns only 150 terms.

Do anybody know what I'm doing wrong?

Thanks for every advice.

Try this on your code:  taxonomy_get_tree(1,0,NULL,TRUE)

Syntax:

taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE)

  Parameters

  $vid: Which vocabulary to generate the tree for.

  $parent: The term ID under which to generate the tree. If 0, generate
  the tree for the entire vocabulary.

  $max_depth: The number of levels of the tree to return. Leave NULL to
  return all levels.

  $load_entities: If TRUE, a full entity load will occur on the term
  objects. Otherwise they are partial objects queried directly from the
  {taxonomy_term_data} table to save execution time and memory
  consumption when listing large numbers of terms. Defaults to FALSE.

This problem was caused by wrong migration from drupal 6 site to drupal 7. Some connection were missing.


Add attribute to main menu item In my project I would like to add the following attributes to my "Login" main menu item:

data-toggle="modal" data-target="#login-modal" (Am using the Bootstrap theme)

I checked out the menu attribute module but it does not allow for these attributes.

Please is there a way?

You can use this HOOK_menu_link_alter and add new attribute from there.

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu_link_alter/7

function MYMODULE_menu_link_alter(&$item) {
  if ($item['link_path'] == 'user/login') {
    $item['options']['attributes']['data-toggle'] = 'modal';
    $item['options']['attributes']['data-target'] = '#login-modal';
  }
}

Note : Make sure you clear cache and are checking this for anonymous user.

You can use drupal module Bootstrap login modal

  Adds a login and register link in the nav bar. Opens them in Bootstrap
  Modals.

  This module is intended for use with the Bootstrap theme.

  By
  default the login and register links are added to the navigation
  region, but they can be moved on the block admin page.


How to include jQuery UI on a page without PHP? I want to include jQuery widgets on my Drupal 7 page. So, I started the way is described here:

drupal_add_library('system', 'ui.dialog');
drupal_add_js('jQuery(document).ready(function(){jQuery("#dialog").dialog({ modal: true });});', 'inline');

However, there are two problems with this approach. First, I would prefer to keep the pages themselves HTML (with JavaScript, of course - but without PHP). And these two lines are the only PHP lines on a large HTML/Javascript page.

Second, JavaScript itself is in quotes which prevents some visual assistance from the editor (since everything is in the string) and forces me to use only double quotes or escaped single quotes inside.

So, I was wondering if there is a way to specify drupal_add_library outside the page, and get Drupal to read <script> tags and JavaScript inside those tags.

In general, I didn't find relevant documentation on Drupal side (relevant being not for theme or module developers but for those who want to use JavaScript / JQuery / JQuery UI as part of site building). If I missed it, I apologize!

How about creating a 'scripts.js' file in your theme folder and then simply either add it in using the drupal_add_js method in template.php (the same method you are using above) or if it's something that's more global, include it in your theme's .info file. You will need to tweak the JQuery call according to 7 standards. I use both of these methods all the time and it works great.

So in your 'scripts.js' file you will have something like this:

(function ($) {
Drupal.behaviors.myTheme = {
attach: function(context, settings) {

// your custom JQuery here

}
};
})(jQuery);

... and then call that however you wish as I have described above. You can also have a look at this post: Managing JavaScript in Drupal 7

If you don't want to use php at all, then the best standard way to go about will be to add it in the .info file in theme folder. That will make drupal print you js in all pages. The down side of this approach will be that your js will loaded in all page even if you need or dont need.

scripts[] = js/myscript.js

Another way to this will be by adding js directly in the header of your theme with direct url, it not recommended and is not a standard way to go about. But that works.

<script type="text/javascript" src="http://your-site.com/js/jquery.min.js"></script>

<script type="text/javascript" src="https://your-site.com/js/jquery-ui.min.js"></script>

<script type="text/javascript">
jQuery(document).ready(function(){jQuery("#dialog").dialog({ modal: true });});
</script>

The available methods of adding javascript depends are.

By defining in the theme.info file.
Adding it inline.
Adding an external js file.

You can also use the php function drupal drupal_add_js to do this

This functions lets you easily add a JavaScript file or helps in setting an inline code to any page in your theme and it takes 5 parameters (you see  it in the api reference).

There is a detail post on this here.


Calculating duration between two dates I am using Views Calc for Drupal 7 to calculate duration. I have some questions:

If use Date (Unix timestamp) and subtract end date from start date of my date field with time it gives me seconds then I divide it with 86400 (the seconds in a day) it gives me number of days.

My code in Views Calc:

( %field_data_field_we_from_date.field_we_from_date_value2 -
  %field_data_field_we_from_date.field_we_from_date_value ) / 86400

which is great;

however:

If I use date (not UNIX time stamp) and with no time only year, month, and day then it gives me a number which I don't understand what it represents. If I divide it with 86400, the answer does not look correct. My problem is that we don't need to add time in the field. The end-user doesn't like to see time field with date.
When I try to use NOW() it give error in Views Calc setting which says NOW value is not allowed here! I need NOW() - my_date_field to get age and other duration which do not have end date field.
ROUND() function also doesn't seem to be working.

Any help would be highly appreciated.

You can do a little tweak.

After you get the only date in YYYY-MM-DD string format, concate 00:00:00 as time to the string. then you can get unix time format by using function strtotime() that takes a string date format and returns an integer of time format (unix).

Hopefully this helps you getting the correct duration.


How can I rearrange a menu link programmatically? I created Menu Link Content entities and saved them in a menu.

$menu_link = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
])->save();

$menu_link_2 = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
])->save();

How can I rearrange $menu_link_2 to be a child of $menu_link?

Looking at menu_ui, they seem to update Menu Link Content in a given order, and then rebuild the menu tree; finally, the Menu entity is saved.

$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link_manager->updateDefinition($menu_link_2->getPluginId(), [
  'parent' => $menu_link->getPluginId(),
]);

How can I rebuild the menu tree and save the menu?

Why? I'm writing a Kernel test for a module that fires when the menu link content has been saved AND then when the Menu itself has been saved.

You can rearrange a custom menu link when you set the 'weight' of the menu. See below code.

$menu_link = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
  'weight' => 0,
])->save();

$menu_link_2 = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
  'weight' => 0,
])->save();


Why doesn't drush respond to commands after install Setup

I just followed the directions on the drush website for installing drush.

I performed the command php -r "readfile('http://files.drush.org/drush.phar');" > drush

Then attempted the next command php drush core-status which resulted in lots of text basically saying "Permission Denied".

So I went ahead and performed the next direction which makes the scripts executable. chmod +x drush

The Problem

I then attempted php drush core-status again.

Now the console just sits there when I type the command. It displays nothing and never released back to prompt. I had to ctrl+c to free up the console.

The Question

What am I doing wrong here? Are their dependencies on drush that are not listed in the install document? Is their some way to see errors that are not printed to the console?

I was using php 5.4 originally but updated to 5.5 and that did not solve the problem. CentOS 6.7.

At the time of my comment the phar for drush wasn't working correctly. That very well may be fixed by now, however, I've still found installing drush via composer to be the easiest solution.

You should be calling drush on its own, in the root of the Drupal install:

drush core-status


Custom theme function and template suggestion I'm trying to create a theme function, with a template:

/**
 * Implements hook_theme().
 */
function mycustomtheme_theme($existing, $type, $theme, $path) {
  return array(
    'custom_function' => array(
      'template' => 'my-template',
    ),
  );
}

The my-template.tpl.php file is in the module directory and it works, I have added this to my page.tpl.php:

<?php print theme('custom_function', array()); ?>

I've tried to copy that template on my theme, but it doesn't work, Drupal always reads the module template, not the theme.

Have I forgotten something?

/**
 * Implements hook_theme().
 */
function mycustomtheme_theme($existing, $type, $theme, $path) {
  return array(
    'custom_function' => array(
      'template' => 'my-template',
      'path' => path_to_theme(),
    ),
  );
}

OR for the my-template.tpl.php file is in the module directory

/**
 * Implements hook_theme().
 */
function mycustomtheme_theme($existing, $type, $theme, $path) {
  return array(
    'custom_function' => array(
      'template' => 'my-template',
      'path' => drupal_get_path('module', 'mycustomtheme'),
    ),
  );
}

I think if you want the theme to pick up the template you need to put it in the theme folder not a module folder.  I doubt very much that the theme system goes looking elsewhere for template files.