Change crop focus for specific styles on certain existing images I just migrated a 15,000 story news website and am doing some quality testing on that migration.

The site uses about 5 image styles for various things, including a REALLY wide one (~960x400px) at the top of every story. This works awesome for images with horizontal/landscape orientation, but causes some weird cropping for images with vertical/portrait orientation.

I don't want to use a solution like imagefield_crop, which will change the cropping on all images (square thumbs are less problematic, for instance). Any idea of modules that allow me to override the default cropping focus from Image Styles for specific styles on specific images?

Thanks!

(Additionally, these images are in Field Collections, so any module suggested should work with that. Currently, it seems that imagecrop does not.)

For my purposes, Manual Crop was the best solution.


Possible to manage display of Profile2 profile fieldset on user registration Using profile2 module I have set my Student profile to "Show during user account registration". This shows the fields I have created for the profile2 Student profile in a fieldset inside the user registration form.
I am now struggling to gain any control over the display of my profile2 Student profile fields on the registration form.
It is possible to manage the display of a profile2 profile displayed on the user registration form through display suite or another method, or is the only option using hook_form_alter.

Thanks

It's a while since I used panels for this, but I'm quite sure you can use panels, and enable the panels page for the user/%user/edit page. Then create a new variant for this page and rearrange the elements through the content section as you would for a front-end panel. If you're not already using panels for other aspects of your site, you may want to try Display Suite, which I've never tried out. Choose the one that works best for your needs and stick with it to avoid module bloat.


How to get formatted date string from a DateTimeItem object I have a standard Drupal date field 'My date' (field_my_date). I can get its value:

$node->field_my_date->value  // returns: "2017-12-14T08:00:00"

But I want to get a formatted date string, which should look like: "14.12.2017".

If I analyse the field in the interactive shell (drush core-cli), then I see, that I can get the DateTimeFieldItemList object or DateTimeItem object:

>>> $node->field_my_date
=> Drupal\datetime\Plugin\Field\FieldType\DateTimeFieldItemList {#8836
 0: Drupal\datetime\Plugin\Field\FieldType\DateTimeItem {#8841},
}

>>> $node->field_my_date[0]
=> Drupal\datetime\Plugin\Field\FieldType\DateTimeItem {#8841
 value: [
   "value" => "2017-12-14T08:00:00",
 ],
}

But I have not found any method to reformat the date string. Is there some possibility to define the format of the output date string? Or do I have to reformat the output string e.g. like this:

date("j.n.Y", strtotime($node->field_my_date->value));

A date field has two properties, value to store the date in UTC and date, a computed field returning a DrupalDateTime object, on which you can use the methods getTimestamp() or format():

// get unix timestamp
$timestamp = $node->field_date->date->getTimestamp();
// get a formatted date
$date_formatted = $node->field_date->date->format('Y-m-d H:i:s');

For a date range field:

// formatted start date
$start_date_formatted = $node->field_date->start_date->format('Y-m-d H:i:s');
// formatted end date
$end_date_formatted = $node->field_date->end_date->format('Y-m-d H:i:s');


Perform action once a form has been validated On Drupal 7, I would like to execute some code once a form has been validated.

I have seen many usage of hook_form_FORM_ID_alter : implementing this hook and adding a custom callback to $form['#validate'] I could perform action on validation.

But I need to be absolutely sure the form has been validated to perform my actions.

Is there some other hook to do so ? Or something I could do in hook_form_alter to ensure that ?

You should add a submit callback instead of a validation callback. Submit callbacks are called after the form has been validated.

function yourmodule_form_FORM_ID_alter(&$form, &$form_state) {
  $form['#submit'][] = 'yourmodule_custom_submit_callback';
}

function yourmodule_custom_submit_callback($form, &$form_state) {
  // Execute here your code
}


Delete Custom Content Type Content with Custom Fields I want to delete the content of a custom content type, which has thousand of nodes. The problem is that I can delete the references from the node database table, but the issue in this solution is that the content still remains in the custom field types database table, and when I want to recreate some data, it gives me the error of duplicate data.

Is there a solution to delete custom content type nodes with there related custom field types?

I am using Drupal 7.

You could use node_delete or node_delete_multiple to do this:

// Retrieve all nids for your custom content type.
$result = db_query("SELECT nid FROM {node} WHERE type = :node_type", array(":node_type" => "<YOUR_CONTENT_TYPE>"))
  ->fetchAll();

// Delete all nodes.
foreach($result as $nid) {
  node_delete($nid);
}

// You should also be able to use node_delete_multiple().
// node_delete_multiple($result);


simple layout fix for IE I'm using Omega3 and having just a couple styling issues with IE. (The site looks good in every other browser) Is there a simple way to detect IE and call an IE specific style sheet to fix these couple layout issues?

I've tried setting/unsetting css/js aggregation and clearing caches. Also tried adding this code to my template.php file and creating a ie8.css file:

drupal_add_css(path_to_theme() . '/css/ie8.css', array('weight' => 999, 'browsers' => array('!IE' => FALSE, 'IE' => '(lt IE 9)&(!IEMobile)'), 'group' => CSS_THEME));

I'm looking for a simple way to detect IE and add a couple lines of css. Thanks!

Arguably the simplest (and least Drupal'y) way:

In html.tpl.php:

<head>
<!--[if lt IE 8]>
<link rel="stylesheet" href="<?php print base_path() . path_to_theme(); ?>/css/ie7.css" type="text/css" media="all" />
<![endif]-->
</head>

Clear your theme cache if adding the template to your theme for the first time.
Install the module, Conditional Stylesheets, which allows you to add conditional stylesheets to a theme's .info file.
Add 37 lines of code to template.php.

New to StackExchange, hope I did the right thing here. Thanks, @jdu.


How to enable contextual links for views content panes? If I do not enable module "Views content panes", I see all block generated by Views in  "Miscellaneous" category. When I insert such block in my panels, contextual links are displayed well fore each block.

But If I enable "Views content panes" module, all views are moved to "Views" category and disappear from "Miscellaneous" category. I get some additional options, but I miss contextual links: no contextual links rendered for views.

How to output contextual links for views inserted with "Views content panes"?

For contextual links to show, you need to create a content pane in your view. +Add > Content Pane. There will be a new panels category automatically created called "View Panes".


Attaching library to form isn't working I'm using hook_form_alter.  I'm having a weird situation where attaching my library works only if I do what I would think is incorrect:

$form['#attached']['library'] = array('somemodule/somelibrary');

But not if I do this:

$form['#attached']['library'][] = array('somemodule/somelibrary');

What could cause a thing like this?  I debugged to see what was happening in the FormBuilder, but it seems like the library is added either way.  It's not removed by any other module or anything.

Those two statements are not equal.

$form['#attached']['library'] = array('somelibrary');

Resets the library array to only contain "somelibrary".  This would remove anyone else's library that may need to get loaded.

$form['#attached']['library'][] = 'somelibrary';

This adds "somelibrary" to the existing libraries array for inclusion. (this is correct)

$form['#attached']['library'][] = array('somelibrary');

This is the wrong structure.

For Drupal 8

$form['#attached']['library'][] = 'somemodule/somelibrary';


Filter view using taxonomy name in url I have a view that shows a thumbnail of the node and the teaser of the node for all nodes of a certain content type. What I want to do is to only show nodes tagged with a certain word, using the url

My website taxonomy page has this format /category/tags/beauty

How can I do this?

Add an Argument to your view with Taxonomy: Term ID (with depth). You may want to use %2 for the title (or %3?). At the bottom of the argument config form you'll see "Set the breadcrumb for the term parents."


Does aggregating JS/CSS interfere with my drupal_add_js()? I want to use drupal_add_js and drupal_add_css on a per-page basis so I have added a 'scripts' text field to my basic content type and have set the Format Type to PHP.

It works beautifully until I turn js/css aggregation back on; then, none of the files I specified are loaded.  Why?

Because Drupal is still using the previously aggregated files (despite me flushing the cache many times).
Because of some more sinister issue that will prevent me from adding my CSS/JavaScript in this manner.

I see other people doing the same thing here: https://drupal.org/node/290982.

Yes, drupal will definitely miss your custom JS scripts in it's js aggregation build phase, if you're loading JS on different pages. This is because by the time a user (or you) hits the other pages, the aggregated js file has already run previously, and created the cached JS file it thinks is all it needs. It uses this cache file until the cache is cleared or the crontab is run.

A couple of options are to either:

try using the drupal_add_html_head() function to add the js when ever you want, or,
write some js to detect what library is needed (perhaps based on a data attribute element in the markup), and then conditionally load the other js via the getScript method.

Good luck.


How do you update a data blob column by searching and replacing a string using drush? How would one do the following in drush? I want to change some data in one of the users table for one of my users. The thing I want to change is in the data blob column with all the punctuation's and what not. I can copy the data blob out, edit, it and then paste it back in, but was wondering how can this be done via drush with a search and replace?

You can use the following MySQL statement in the drush SQL console:

drush sqlq "update users set data = replace(data, 'string_here', replacement_string') where uid = 1"


How to show a date in the correct timezone? I have a Datetime Range field (field_date) in a content type. Once I create my content type I set the Start Date as:

2017-02-27 19:30:01

Now I want to get the value and show the date in other format, so try to use the following code:

// Loading the node.
$node = Node::load(2100);
// Getting the start date value.
$date = $node->field_date->value;
// Printing to see what is the output.
dpm($node->field_date->value);
$date = strtotime($date);
// Printing my timezone.
dpm(drupal_get_user_timezone());
// Applying my custom format.
$date = \Drupal::service('date.formatter')->format($date, 'custom', 'Y-m-d H:i:s', drupal_get_user_timezone());
// Printing to see the output.
dpm($date);

This is my output:

// It's fine.
2017-02-28T00:30:01
// Its fine.
America/New_York
// This is not what I waiting for. I'm waiting here: 2017-02-27 19:30:01
2017-02-28 00:30:01

So, how to show a date in the correct timezone?

I suspect the problem has to do with some of the nuances of strtotime().

strtotime() can take just about any string, and convert it into a Unix timestamp.  The problem is that when the string doesn't contain an explicit timezone, it will use what is set by date_default_timezone_get().  That should be set from the current user, though (it is set by the account proxy).  However, the string that you are pulling out of $node->field_date->value is implicitly in UTC.  In other words, I think the string is being parsed by strtotime() is being interpreted as in 'America/New_York' and not 'UTC'.

The good news is that you can simplify your situation a lot.  The field item for a date range consists of four parts

'value' is the start date as a string in UTC
'start_date' is a DrupalDateTime object representing 'value'
'end_value' is the end date as a string in UTC
'end_date' is a DrupalDateTime object representing 'end_value'

For a plain date time field they are

'value' is the date as a string in UTC
'date' is a DrupalDateTime object representing 'value'

So, you can work with the DrupalDateTime() object directly.  In addition, that date.formatter service should pull in the proper timezone in use by the user viewing the page by default (in addition to using the user's active language).

I suspect something like this will work

$node = Node::load(2100);
$start_date = $node->field_date->start_date;
$formatted = \Drupal::service('date.formatter')->format(
  $start_date->getTimestamp(), 'custom', 'Y-m-d H:i:s P'
);

Note I added the 'P' format placeholder in there so you can see what what timezone the system thinks is in use.

Make sure you have the proper timezone set up on admin/config/regional/settings, and that your user timezone is what you are expecting.  Also ensure that you have the proper timezone set in your php.ini (it's the date.timezone setting); weird things happen when this isn't set (And off the top of my head, I don't recall if that causes a warning in the installer or on the status report when not set.  I remember the issue, but not whether it got committed).


Static vs. Dynamic Queries in Drupal 7 and the Right Syntax to Use Does anyone know of a good tutorial that explains, not with just one example of an easy query, how to create complex select queries in Drupal 7 that uses the preferred method of query writing?

I've written some complex queries in my custom module that use pretty elaborate and long, basic query syntax (a select clause, order by, where, etc.). I'd like to write them in the preferred format for Drupal 7 that I BELIEVE is supposed to look something like this:

https://www.drupal.org/dynamic-queries

I don't find that to be a very useful primer however. I want some actual guidelines for putting together complex statements with all the various options (if something like this exists).

And is it always better to write the queries like this?

I'd like to add a pager and this seems to be the only way to that.

I hope this question isn't too ambiguous. I'm really just looking for a tutorial on constructing these types of queries.
Thanks!

If you're creating a query that will need to be modified by a 3rd party or if your creating drupal.org project code then use things like db_select().

For all other use cases I prefer db_query() as the mental overhead is a lot lower.


Connect to remote DB using global php drupal 7 views I am using Views PHP module for custom coding in views.

I tried using mysql_connect function to connect to a remote database using the "GLOBAL PHP" field and get some data through custom coding. Is it safe to connect to database through the "GLOBAL PHP" field? Or are there any security risks?

Nothing is a security risk in and of itself. If you know basic PHP and the basic usage of mysql_query and how to sanitize your input -- you're fine.

What you're proposing is not by any means a best practice, proper use of Views or the Drupal API (sorry).

If you want to make Drupal aware of other databases see:
https://drupal.org/node/18429
If you want Views to be able to query an external DB table see:

https://api.drupal.org/api/views/views.api.php/function/hook_views_data/7

if you want to know how to describe your table to Views using the Drupal Schema API for an existing table see the Schema contributed module which leverages the built in Schema API of Drupal 7:

https://drupal.org/project/schema

If you want to make a view and alter its SQL or resultset see: (possibly interacting with another DB, or using PHP to alter the row results somehow, maybe by examining another db query result)

https://api.drupal.org/api/views/views.api.php/group/views_hooks/7
https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7

All of these options make use of Drupal core features for interacting with 3rd party databases, Drupal API or Views contributed module API.

Your approach is taking an embedded php field in a view and ignoring Drupal and its architecture to achieve what you want. It's as secure and safe as your experience and knowledge make it. I prefer to stand on the shoulders of others and leverage the security built into Drupal and its supported APIs.

You may find the Data module useful in making your 3rd party data play nicer with Views.

  Data module helps you model, manage and query related sets of tables.
  It offers an administration interface and a low level API for
  manipulating tables and accessing their contents. Data module provides
  Views integration for displaying table data and Drupal search
  integration for searching table content.


How to properly test access permissions when generating links? I have a page that is only accessible by some people. It's entry in hook_menu contains following:

$items['mymodule/mypage'] = array(
  'title' => 'Edit Product',
  'page callback' => 'mymodule_mypage',
  'access arguments' => array('view mypage'),
  'file' => 'pages/mypage.inc',
);

It works all right, it shows page when it should and throws 403 when needed. Now I need a link to it on some other page. Usually I would just use:

  <?php echo l('My Page', 'mymodule/mypage'); ?>

in tpl.php file where I need it. But I don't want it to be visible for people who will get 403 if they will click it. l() does not test for permissions on it's own. And I feel reluctant about using logic in templates like this:

<?php if ( user_access('view mypage') ) : ?>

    <?php echo l('My Page', 'mymodule/mypage'); ?>

<?php endif; ?>

I always believed than if's in templates are only to provide things like odd/even, marking visible tabs and deciding if markup should be outputted, like if(!empty($header)).

On the other hand, building this in the module and passing to the template seems like an overkill for such a simple task.

So what is the "canonical", cache-safe way to achieve this?

Additional information about what this link really is in this case:

Link is related to the page it is presented on, so block does not make sense.

Leaving it to the user to add link to the menu, so that menu system will take care about permissions, is not applicable, as it violates the "if something have to be done during install, always the same way, and requires no user input of any kind, don't leave it to the user" rule. If there is a way to automatically place it in menu in a way similar to node/%/edit links shown on node/% pages, all right. I'll be happy to accept that as an answer. But my question is general, without assumption that links share front part. In my exact case, they actually do not.

You can check the access for any url-path in your module using menu_get_item():

$menu_item = menu_get_item('mymodule/mypage');
$access = $menu_item['access'];
if ($access) {
    $mylink = l('My Page', 'mymodule/mypage');
} else {
    $mylink = '';
}

Put this code e.g. in some preprocess function in your module, change $mylink variable to sg that is available in your .tpl.php, so you only need to print this variable in your tpl.php.


How do I change the rate modules output to "# of users like this"? I am using the Rate module.

The current display for my thumbs up widget is:

(thumbs up image) 2 users have voted, including you.

I would like to change it to:

(thumbs up image) 2 users like this

How do I change the default tpl to accomplish this?

print $up_button;

if ($info) {
  print '
' . $info . '
';
}

if ($display_options['description']) {
  print '
' . $display_options['description'] . '
';
}

I haven't used the module. But looking at the code, you essentially need to override the preprocess function in the module which is used to generate the string.

Open rate.module in an editor and search for the text string that you are looking to change. In this case, this string would be something like "have voted", which should lead you to the function named rate_preprocess_rate_template_thumbs_up(). This is the function that you should look to override. You can see that the strings are added as part of two format_plural calls and should be straightforward to amend in the override function.

You can perform the override either from a custom module or from your theme's template.php file. Since the module is using a preprocess function to make its changes, I recommend using a process function (note the difference in name) when you override it. There should be plenty of documentation and examples available on drupal.org and drupalSE to aid you if you are unfamiliar with overriding.


How to allow users who have cancelled their accounts to re-activate / re-enable them? If a user cancels their account on a Drupal 7 site, is there a way to allow them to re-activate their account without requiring administrator intervention?

If a user has second thoughts and wants to rejoin the site using the same e-mail address, I would like to make it easy for them.  I have set the Account cancellation method to Disable the account but keep the content.

There are two URL which can help you in achieving this. First you will have to use Advance User module & then you can extends some hooks of it according to your need for account re-activation.
There is a blog written on similar issue which may help you - Enable/Disable User.

I hope you find your solution.


From local server to web hosting I have created a website on local with bitnami. Now I want to upload it to a web server (probably on hostgator).

I don't care about content. The site is empty and I will add content only when I upload it.

I just want to keep the settings, permissions, content types and modules. So, I can start add content on air.

If I copy paste the htdocs folder with ftp in the server, this will work?

The simple way, (used to do all this useless stuff before GIT and capistrano...)

Copy/upload all (hidden) the contents of your Drupal folder in the public_html or whatever your server document root is for that site.

Export your local database in a dump file.

Create a mysql database on the live server, import the local dump.

Edit the sites/default/settings.php file on your live server to serve your new database credentials.
Edit the .htaccess file on the live server to your needs.

Visit your site.Clear the cache tables.

Set the correct permissions on settings.php (check status reports for errors) and the desired setUp on sites/default/files etc for file uploads

That's all


How do I create a new admin sub page and how to make it appear in the admin menu? Let's say I have to create an extra users management views block for contributors role only, with some different columns, filters and actions available.

How do I create a simple page which is restricted to some roles only and automatically has the backend theming to put my views block in there? (I always put views blocks on pages, it makes editing views easier)

And last, how can I make that page appear in the admin toolbar as sub item of admin/people?

Do I have to write a custom module for that or maybe create a template file? Or is that maybe all in all a wrong approach?

Easiest way I think of is to create a page display for you view. Set the path to admin/people/mypage and under the menu settings in views choose tab, give your menu item a title and keep the menu setting at Navigation as it defaults to.

Now if you navigate to admin/people you will see a new tab with your page and menu title.

In the views configuration you can add access restriction to your URL / menu item.

If you insist on not creating a page display and instead want to place your block on a page, without coding you own module I would use Panels and Page Manager. You will need the modules Ctools and Panels. Under structure and pages, create a new page and give it your URL, set it to have a menu item (as described in the Views example) and use Panels as variant type. Once your Panel is created you can place your block into any region available in the layout you choose.


how to associate multiple nodes with one node I have a content type "events" and all the node created under this content type will have further node.

The red boxes in the above pictures are node links which are associated to the "event node".

Every node created under "Event Content Type" will have relative information nodes as shown in boxes below.

How i should be doing this association? Should i create content types for all red boxes and then make entity/node references ?

any clue?
thanks

I recommend that you model this from an object oriented perspective. I would create the following content types:

Event content type (composed of event, overview, agenda, live broadcast maybe)
Speakers
Resources
Venue
Sponsorship
Registration

The reason for embedding overview, agenda and live broadcast to the event is because they are closely related to to specific event and creating separate content type for them would be expensive (because there is a very less probability that two event have the same agenda or overview).

Whereas other content types such as Speakers, Resources, Venue, Sponsorship, Registration can be regarded as separate content types, because:

To allow referencing the same content type by multiple event nodes i.e. for example, you will have a speaker who would speak in several events, or a resource that would be useful in several events hence, you will be avoid loads of duplication/inconsistency etc.
The other reason to create separate content type is to achieve low coupling and high cohesion. Speakers are different than events, the best way would be to reference than to embed a a list of speaker into event content type. Fields of a Speaker content type, does not directly relate to an Event (i.e. Database normalization perspective)

This would give you a clean set of content types that are linked with each other using references and can be queries very easily using views, contextual filters and relationship.

Good luck.


Deprecated code cleanup: Updating EntityManager to EntityFieldManagerInterface EntityManager is deprecated so I am trying to update code for Drupal 9. The documentation says it should usually be changed to EntityTypeManager, but in this case the code is using getFieldStorageDefinitions so it needs to be EntityFieldManagerInterface.

I changed this line:

  $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);

To:

  $fields = \Drupal::EntityFieldManagerInterface()->getFieldStorageDefinitions($entity_type);

Which gives this error when I run behat:

  [error]  Error: Call to undefined method Drupal::EntityFieldManagerInterface() in _drush_behat_get_entity_field_types() (line 95 of /app/drush/Commands/contrib/behat-drush-endpoint/behat.inc) #0 /app/drush/Commands/contrib/behat-drush-endpoint/behat.inc(123): _drush_behat_get_entity_field_types('node')

However, I don't understand this error, because EntityFieldManagerInterface does have getFieldStorageDefinitions.

How can I update entityManager to EntityFieldManagerInterface?

Here's the full function if that's useful:

function _drush_behat_get_entity_field_types($entity_type) {
  $return = array();
  $fields = \Drupal::entityManager()->getFieldStorageDefinitions($entity_type);
  foreach ($fields as $field_name => $field) {
    if (_drush_behat_is_field($entity_type, $field_name)) {
      $return[$field_name] = $field->getType();
    }
  }
  return $return;
}

EntityFieldManager has no shortcut in \Drupal, so you need to get it through \Drupal::service():

$fields = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions($entity_type);


Numerous dependencies don't get installed with "drush en -y" command for rooms module I tried to install the rooms module, obviously a very complex module with lots of dependencies, I tried with drush:

drush en rooms -y

This is the module:

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

But even after doing that, from the back end, tons of dependencies are missing.

Additionally, the Rooms page has absolutely no information on required dependencies...

Am I missing something here?

Drush will only check the .info file for dependencies, in the case of the Rooms module those are:

dependencies[] = date
dependencies[] = date_api
dependencies[] = date_popup
dependencies[] = jquery_update
dependencies[] = libraries (>=2.x)
dependencies[] = variable

If Drush is missing any of those out, you have a buggy version of Drush and need to get an issue opened for it (or check for a similar existing one).

Other than that any "missing" dependencies are either down to a bug in the Rooms module, or your expectations being incorrect.

For example, maybe you're expecting Drush to auto-download all of the dependencies for the sub-modules included with Rooms as well?

It won't, those are considered separate modules. If you want those dependencies downloaded/installed automatically, you'll need to run drush en for each module individually.


How can I print the views title in node.tpl.php? I could print the view with this code in node.tpl.php.

<?php
$view = views_get_view('view_name');
print $view->execute_display('view_display_name', $args);
?>

How can I print the views title ?


How do I programmatically duplicate a view display? I have a view (my_view) with the following displays:

master
page_1

I am looking for a way to programmatically duplicate page_1.

    $view = Views::getView('my_view');
    $storage = $view->storage;
    $display = &$storage->getDisplay('page_1');
    // Create a new display.
    // Remove some exposed filters from the new display.
    // save the view.

How can I achieve this?

The View entity comes with a handy function for duplicating an existing display, ->duplicateDisplayAsType().

->duplicateDisplayAsType() requires 2 arguments--ID of the display to duplicate & new display's type.  First one is self-explanatory--if you want to duplicate something, you need to know what you want to duplicate (visit a View and look at the URL for the unique ID).  For the second arg, a View Display needs to be of a certain type--page, block, feed, etc.

Finally, we have something like below:

$commentView = \Drupal::entityTypeManager()->getStorage('view')->load('comment');

// ->duplicateDisplayAsType() returns the new display's ID so it's not 100% necessary
//   to assign the return val to a variable.
$new_page = $commentView->duplicateDisplayAsType('page_published', 'page');
$new_block = $commentView->duplicateDisplayAsType('page_published', 'block');

$commentView->save();

Above, I am using the default 'Comments' view and duplicating the 'page_published' Display as both a new page and new block.  Try copy pasting the above code into a Controller and triggering the controller method once and visit the View to see your new Displays.

Finally, as with most entity operations, you'll want to ->save() it afterwards.

Note:  Using (presumably) \Drupal\views\Views::getView() will return a ViewExecutable--aka a configured View which is used for generating the actual output.  You cannot edit the View's config via ViewExecutable.  Above, I am using the entityTypeManager() to query for a View so I can retrieve the actual Entity so we can modify its configuration.  The above code can act as boilerplate--try switching out values to achieve your desired goal.

EDIT: To answer your question more definitively, the above example code could be translated to match your code snippet:

$view = \Drupal::entityTypeManager()->getStorage('view')->load('my_view');
$new_page = $view->duplicateDisplayAsType('page_1', 'page');

$view->save();

Edit 2:  Sorry, I didn't answer your second part--how do we modify the display after duplicating.  This may not be the most efficient way so someone please tell me if there is a better way to do it.  Luckily you want to only remove a filter.   Because filters are not yet OOP, they're just giant arrays with specific keys you need to set.  This part does get a bit more complicated.

There is one thing you need to keep in mind though--the default display will apply its display_options across all displays unless you override them in the 'defaults' array on the specific display configuration.  You can override defaults for each display_option so you can still inherit defaults for some properties while overriding others.

For comments, specifically, the filters are all placed on the 'default'.  Out of the box, the Comments view only comes with the page_published display.  Let's say we want to duplicate the page_published display, copy over the filters from the original display, remove its default filters, and then array_pop() one of the filters off our new display.  So starting from scratch again:

$view = \Drupal::entityTypeManager()->getStorage('view')->load('comment');
$new_display_id = $view->duplicateDisplayAsType('page_published', 'page');
// Must use the getter--the display property is protected
// We assign by reference because there is no setter--we cannot set the display
//   options again after modifying but we can modify the referenced var to change
//   the original values
$new_display = &$view->getDisplay($new_display_id);
$default_display = &$view->getDisplay('default');
// Copy the filters from the 'default' to the new display
$new_display['display_options']['filters'] = $default_display['display_options']['filters'];
$new_display['display_options']['filter_groups'] = $default_display['display_options']['filter_groups'];

// Tell Views not to use the defaults for these two specific properties
$new_display['display_options']['defaults'] = [
  'filters' => FALSE,
  'filter_groups' => FALSE,
];

// For demonstration purposes, we remove 1 filter from our copied over filters
array_pop($new_display['display_options']['filters']);

$view->save();

You should see a page exactly like the page_published except it should be missing 1 filter.


Key / Value fields module where you can choose the type? Is there a module which creates a field where you can choose the field type of the key and also the value during content type creation?

You can use the Field Collection module to achieve that functionality:

Provides a field-collection field, to which any number of fields can be attached.
A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

The idea is:

Create a Field Collection.
Add key/value fields to it with the field types of your choice.
Add a Field Collection field to the content type you want these key/value fields on.
Set the source of that Field Collection field to the new Field Collection you've just created.
Repeat for whatever other content types you need to.


Access denied for admin user after new drupal 6 install I just installed Drupal 6 (Don't ask why) from a fresh install (Version 6.29). I followed the install steps, created an admin user, set the correct time zone, etc.

But when I login and attempt to proceed to the admin panel, I get Access denied
You are not authorized to access this page. I have read about this issue many other places, and have attempted many solutions, but none seem to work for me.

I noticed that there is nothing in the sessions table of my MySQL database for this drupal install (but there is data in other tables). I think that this has something to do with it, but ti could be that there is info in the table, but it is immediately removed due to a session/cookie issue.

I have repeatedly removed all my browser cookies each time I have tried a solution. I have tried many solutions on drupal.org, many of which have been also referenced on other sites, but none have worked.

OS: Mac OSX 10.9 (Mavericks)

Web Server: Apache/2.2.24 (Unix) PHP/5.4.17 mod_ssl/2.2.24 OpenSSL/0.9.8y DAV/2 Server at XX.XX.XXX.XXX Port 80

Not using SSL for this drupal install.

It may be that your cookie domain is not set correctly, this is a known cause of Access Denied errors when logging in, and it might be worth removing cookie domain info from settings.php and see if that works, and go from there.


How to implement a follow author (or user) function? Is it possible to implement a Follow button for authors of posts in Drupal 7, so that users can:

Follow any one they wish, and
Be notified about the new posts of those authors.

This sounds like 'Mashable Follow button' for authors.

Do you have any suggestions about how to implement this?

Minimal solution

The Notifications module currently only has an Alfa version for D7 (which is this question is about), which dates from Dec 2011.

Therefor, use the Flag module as an alternative. So that users can "flag" authors they want to "follow". You'd want to use a flag related to entity "users", which is a non-global flag. Probably defined with a label like "Follow Author" (to 'flag' an author) and "Unfollow Author" (to undo a previously flagged Author).

Combine this with using the Rules module to send eMails whenever content gets updated by some author. Whereas the eMails are sent to all users who "flagged" that author (= the users who indicated they wanted to "follow" that author). If you'd only want to send such eMails for a subset of content that's being updated (eg only for selected content types), then it's just a matter of adding an appropriate extra "condition" to your rule.

Improved solution

Optionally you may also want to consider the Message module for more options in the area of sending some type of notifications. For this, you need a flag like described above (say with machine name follow).

On top of that you need a Message type and a custom Rule, both are detailed below. And you probably also want to add a custom View of those messages.

Message type

Below is an export of "a" Message type that you could use to get started (by simply importing it in your own site). It defines the message to be created when a user is flagged and it actually works together with the custom rule below. This message type has machine name user_following, and uses a replacement token like @following_user (adapt both to fit your needs, eg change @following_user to @user_who_flagged if you prefer):

{
  "name" : "user_following",
  "description" : "User following",
  "argument_keys" : [ "@following_user" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@following_user started following [message:user:name]",
        "format" : "plain_text",
        "safe_value" : "\u003Cp\u003E@following_user started following [message:user:name]\u003C\/p\u003E\n"
      }
    ]
  },
  "rdf_mapping" : []
}

This Message type (compare to a Content type ...) will be used to create Messages (compare to Nodes) that will look as in this example:

  Hillary.Trump started following Donald.Clinton

To avoid confusion, note that [message:user:name] in the message type sample above is the user to which the Message is targeted, not the flagging user!

Custom Rule

Here is a rule (in Rules Export format) which creates a message when a user is flagged:

{ "rules_somebody_started_following_you" : {
    "LABEL" : "Somebody started following you",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "user" ],
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_follow" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "user_following",
            "param_user" : [ "flagged-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:following-user" ],
          "value" : "[site:current-user]"
        }
      }
    ]
  }
}

Some more details about this rule:

Its purpose is to deliver a message (using the Message module) to a user being flagged (using the Flag module).
It is triggered after a user is flagged with the flag with machine name follow.
It creates a Message with machine name user_following.
It makes a variable with machine name following_user available as a replacement token for the message to be created ... so that the "flagging user" (= [site:current-user] when the flagging happens) can also be included in the message to be created.

Custom view

With the above rule and message type, you'll have "messages" that get created ... "So what?" you may think. Well, since all this is entity API based, you can create a custom view (using Views) to visualize these messages, e.g. shown via a path like /user/nid/messages. Whereas the only limitation for such Views is your own imagination (you could even create the Charts about those Messages (eg by originating user, by date, etc).

Additional info

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework. Possibly also the similar set of 8 video tutorials about the Flag module.

For more details about the Message module, refer to some interesting Use Cases detailed within its Community Documentation. And/or checkout the video introduction "Your Drupal site can talk" (if you want you can fast forward to about 03:30 where it really starts).

Note: this approach can be used also for any type of users (not just for "authors").


Using webform variables I've this hook that gets submitted values from my form which as 2 select options elements and prints the 2 values submitted.function modsubmit_webform_submission_insert($node, $submission)
{
$cont=0;
foreach($submission->data as $val) {
      $value = array_shift($submission->data);
        $value = array_shift($value['value']);
        $data[$cont] = $value;
        $cont=$cont+1;}

drupal_set_message("The value inserted was: {$data[0]},{data[1]}");
}
Now i want to use this two values to make a sql query in db, and the result showed in a table.
I can't get this to work, solutions needed

Thanks

If you want to alter how a submission is rendered, for example adding a table, you need to implement hook_webform_submission_render_alter(). The hook receive the data for the submission in $renderable['#submission'], and the node in $renderable['#node'].

An example of hook_webform_submission_render_alter() is webform_webform_submission_render_alter(), which contains the following code.

function webform_webform_submission_render_alter(&$renderable) {
  // If displaying a submission to end-users who are viewing their own
  // submissions (and not through an e-mail), do not show hidden values.
  // This needs to be implemented at the level of the entire submission, since
  // individual components do not get contextual information about where they
  // are being displayed.
  $node = $renderable['#node'];
  $is_admin = webform_results_access($node);
  if (empty($renderable['#email']) && !$is_admin) {
    // Find and hide the display of all hidden components.
    foreach ($node->webform['components'] as $cid => $component) {
      if ($component['type'] == 'hidden') {
        $parents = webform_component_parent_keys($node, $component);
        $element = &$renderable;
        foreach ($parents as $pid) {
          $element = &$element[$pid];
        }
        $element['#access'] = FALSE;
      }
    }
  }
}

The purpose of hook_webform_submission_insert() is inserting the submitted data in a database. You can use that hook to save the data in a database, and show those data in a page rendered from your module, but hook_webform_submission_insert() is not thought to render any data.
To make a paragon, hook_webform_submission_insert() is equivalent to hook_node_insert() that is invoked when a new node is saved, but that should not render any page.


Is there any documentation for the UUID module? I think I need to utilize the UUID module to make universal ID's for some taxonomy terms. However, after installing the module it doesn't seem to do anything and the configuration interface has only one button that does nothing.

I can't find any helpful articles, tutorials, or documentation for this module. Anybody have any suggestions?

UUID is an "API" module. It wont do anything out of the box. It is for other modules to use the functionality provided by UUID.

See the module's README.txt file:

  This module provides an API for adding universally unique identifiers (UUID) to Drupal objects, most notably entities.

  FEATURES

  Automatic UUID generation:    UUIDs will be generated for all core entities. An API is provided for other    modules to enable support for custom entities.    See https://www.drupal.org/node/2387671
  UUID API for entities, properties and fields:    With this unified API you can load entities with entity_uuid_load() so that    all supported properties and fields are made with UUID references. You can    also save entities formatted this way with entity_uuid_save() (depends on Entity API).
  Export entities to use as default/demo content:    The integration with Features module provides the ability to export UUID enabled entities with intact dependencies and references to other entities.  This functionality depends on Deploy module 7.x-2.0-alpha1 (soon to be    released) and is probably the most robust way for installation profiles and    distributions to provide demo content!
  Services integration:    The integration with Services module alters all UUID enabled entity resources    (nodes, users, taxonomies etc) to be based on UUIDs instead. This way it   becomes easier to share and integrate content between sites. This   functionality is used by Deploy module.
  More integrations:    UUID module integrates with Views, Token, Rules and provides some CTools  plugins.


How to change Taxonomy admin page title? I simply need to change the title on the (Drupal 8.8.4) administrative page which lists the existing vocabularies.

As far as I know/read, the routing.yml should be modified, shouldn't it?  (Is only the *defaults_title parameter that needs to be changed?)

Inside the taxonomy.routing.yml file, I only get the form routes for taxonomy term, if I am correct.

Do I need to modify the route elsewhere?

I have tried with the system.routing.yml file, listing many administrative routes (I thought it was the jackpot) but there is no route for the taxonomy page.

Could someone tell me where to go and which static route to change?

Related questions

How do I set the page title?
How to set admin theme for a route?

Could someone tell me where to go and which static route to change?

It's not a static route.  Like other entity collection routes, it is built with the aid of the comment annotations above the Vocabulary entity class.  VocabularyRouteProvider also comes into play, and it sets a _title_callback into TaxonomyController::vocabularyTitle for good measure.

At any rate, this is all a bit moot because you don't want to go modifying core files, because then when you update core you will have to patch them all over again.  Very tedious.  Instead you could implement your own RouteSubscriberBase::alterRoutes.


What is the reason to define indexes in hook_schema? How do I choose what fields to index and which ones not to? Is the index useful for when I set a condition in the database query for a quick look up of the rows? I guess this is an SQL question but I really want to know what indexes are used for Drupal entities.

What are all these indexes in the node table for?

  'indexes' => array(
    'node_changed'        => array('changed'),
    'node_created'        => array('created'),
    'node_moderate'       => array('moderate'),
    'node_frontpage'      => array('promote', 'status', 'sticky', 'created'),
    'node_status_type'    => array('status', 'type', 'nid'),
    'node_title_type'     => array('title', array('type', 4)),
    'node_type'           => array(array('type', 4)),
    'uid'                 => array('uid'),
    'tnid'                => array('tnid'),
    'translate'           => array('translate'),
  ),

MySQL Indexes
You can start by reading the MySQL reference.
You are right in saying that index is useful when you use a condition in your query. Deciding which fields to index is not as easy as it looks, though. There are pros and cons to each index, and it is not right to say that having an index always boosts overall performance at the expense of disk space.
Using index results in faster lookup of data when queries use the indexed columns in its conditions; however, large indexes can slow things down in cases of heavy inserts or updates to the table as any update to the rows result in updates to the index as well.
Therefore, you have to carefully decide if it is worth adding an index to the column even if you are going to use it in a query. In most cases it is.
On the next level, when you are using multi-column indexes, you have to be even more careful about the queries. Suppose you define:
CREATE TABLE test (
    id         INT NOT NULL,
    last_name  CHAR(30) NOT NULL,
    first_name CHAR(30) NOT NULL,
    PRIMARY KEY (id),
    INDEX name (last_name,first_name)
);

You might expect a query like this to use an index, but it won't.
SELECT * FROM test WHERE first_name = 'hw';

The reason is explained in the documentation:

The name index is an index over the last_name and first_name columns. The index can be used for lookups in queries that specify values in a known range for combinations of last_name and first_name values. It can also be used for queries that specify just a last_name value because that column is a leftmost prefix of the index (as described later in this section).

Drupal
As far as Drupal is concerned, it uses the Schema API to define those indexes. As you would see, these are common fields that are used in queries on the node table.


Is it possible to do a user search by taxonomy? my question is because I have users with a taxonomy field and what I want to do is search for those taxonomies.

Example: a user in his profile chose a taxonomy, let's say soccer.
I want to make a search engine in which users search for soccer and all users who have a soccer taxonomy appear.

I do not know any module for this and I do not know if it is possible to do it with a view.

•Drupal 7
•Views 7.x-3.20

Any help?

Create a "User" View

Add a "Filter Criteria" with your taxonomy field

Click "Expose this filter to visitors, to allow them to change it"

Done.


Disallow forward date input (CCK Date) How do I disallow future dates in CCK date field?

Check out

http://drupal.org/node/751826

and look into forms validation.  You could check if your date is less than the current date and if not, bzzzzt.


An invalid implementation mymodule_form_alter was added by hook_module_implements_alter I am trying to have my module alter menu_ui functions. Changing my module's weight didnt help and I read that hook_module_implements_alter is the way to go. So, as described here I am appending my module to the end of the implementations:

/**
 * Implements hook_module_implements_alter.
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ('form_alter' == $hook) {
    $group = $implementations['mecca_hierarchy_access'];
    unset($implementations['mecca_hierarchy_access']);
    $implementations['mecca_hierarchy_access'] = $group;
  }
}

But this just throws:

  Uncaught PHP Exception RuntimeException: "An invalid implementation
  mymodule_form_alter was added by hook_module_implements_alter()" at
  /path/to/core/lib/Drupal/Core/Extension/ModuleHandler.php line 591

My form alter looks like this:

function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  // commented code
}

What do I do wrong?

The exception is raised from the following code. (See ModuleHandler::buildImplementationInfo().)

    // If a new implementation was added, verify that the function exists.
    if (!function_exists($module . '_' . $hook)) {
      throw new \RuntimeException("An invalid implementation {$module}_{$hook} was added by hook_module_implements_alter()");
    }

It simply happens because, in your case, there isn't any mecca_hierarchy_access_form_alter() or similar hook, most probably because there isn't any mecca_hierarchy_access module.

The code you want to use is probably the following one.

/**
 * Implements hook_module_implements_alter().
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ('form_alter' == $hook && isset($implementations['mymodule'])) {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

Always check the implementation of your module has not been already removed from another module, or your hook implementation would actually set $implementations['mymodule'] to NULL.


Enabling a contributed module under certain path only Is it possible to enable a certain custom module under specific path only e.g. /store, and not load under other sections of a website? I am using Drupal 7.

Well yes you can ... but you shouldn't you may want to think of the code quality of the custom module, because it should only be responsible for the exact functionality you require.

I say you can because yes:

//Enable.
$modules = ['custom_scarry_module'];
module_enable($modules, TRUE);

// Disable.
if (module_exists('custom_scarry_module')) {
  module_disable(['custom_scarry_module']);
}

But again perhaps rethink the "why" aka what Jaypan said.


Issue with drupal cache I have developed website using drupal 7. I created block using Views Slideshow Cycle. I uploaded the site to server. The slideshow not displayed in live site. But after clearing cache(using configuration->Development->Performance) the slideshow is visible.The problem is that i need to clear the cache frequently to display the slideshow. The below image is the site without slideshow.

This is the site with slideshow after clearing cache.

I am also having hidden fields using field permission. That are also visible to anonymous users. But I gave the field view permission only to authenticated users. Those fields are hidden for anonymous user after clearing cache.
I didn't enabled cache pages and cache blocks. But the site in my local system does not have this issue.
These issue only with my live site. My hosting server is apache.
I have this problem for a month. Please suggest me a solution

There is an issue when views, javascript and caching are used in combination.
Some information that may be of help:

https://drupal.org/node/1873970
https://drupal.org/node/1811828
https://drupal.org/node/1984774

As far a I can understand the cached page or block cause the js to fail. In another answer it is stated:

  This may be a timing issue, flexslider may require the images to be
  loaded when it is called so it can work off their attributes, remember
  that $(document).ready() fires after the DOM has finished loading
  whilst $(window).load() fires after all images on the page have loaded
  - giving you intermittent results if they are cached etc, replace:

  $(document).ready(function(){ ... }); with

  $(window).load(function(){ ... });

I have not found a sure fire answer /solution to the issue and may broaden out the question to see if there is an advised fix for views+cache+js=problem.


Do something conditinally on node.tpl.php depending on if the node is tagged with certain taxonomy vocabulary I found how to do this if the node is tagged with certain terms here.
But what I would like to do is to do something conditionally in node.tpl.php only if the node is tagged with a certain vocabulary.

For example, I have a vocabulary called "Color" with terms "Red" "Blue" "Yellow". I would like to display the text "It has color" only if the node is tagged with at least one of those terms. Otherwise print nothing.

How can I do this in  node.tpl.php ?

Each taxonomy term in a node also gives you the vocabulary id that it belongs to.  So you could look through the terms to see if one matches the vocabulary id of your "Color" vocabulary and then display "It has color" when found.

An easy way to do this would be to use a loop:

<?php foreach ($node->taxonomy as $key => $term): ?>
  // Say the vocabulary id of "Color" is 10.
  <?php if ($term->vid == 10): ?>
    <div>
      <?php print views_embed_view('my-views', 'default', $args); ?>
    </div>
    // etc
    <?php break; ?>
  <?php endif; ?>
<?php endforeach; ?>

For reference, to access the vocabulary id of a single term:

$node->taxonomy[TERM_ID]->vid;

Where TERM_ID is the id of the taxonomy term.


Using entries from custom block library in twig template? I have two custom library blocks for the footer of a website I am developing. The idea is that admins may change the footer quite freely with a wysiwyg editor without any theme changes.

The problem is that I don't find any way to use only the contents of the custom library blocks (without the Drupal generated layout destructing code) in the footer twig.

Am I trying to do something impossible or just missing something obvious?

wbr

hank

Use Twig Tweak and

{{ drupal_entity('block_content', 123) }}

This renders only the block content, without a block template.


Displaying content in different ways I sort of ran into a problem here, for a new project a piece of the homepage can have different layouts.

For example:

-----------------
| N  |    C     |
| E  |    O     |
| W  |    N     |
| S  |    T     |
|    |    E     |
|    |    N     |
|    |    T     |
-----------------

or

-----------------
|       C       |
|       O       |
|       N       |
|       T       |
|       E       |
|       N       |
|       T       |
-----------------

or

-----------------
|               |
|     NEWS      |
|               |
-----------------

So there are 3 types of layouts, news + content, just content and just news.
What would be the best way to do this? Currently I'm using Panels to build the homepage, this is just a small part of it.

It also would have to be very convenient for the user to switch styles, any ideas for this?

You can use Panels, Display Suite and Context to build a different layout flexible and custom layout in your theme.
You can also build a custom theme with there layouts and switch the layout home page based on context. If you are planning for theme, you can write a subtheme for Omega, a HTML5 base theme, or can you choose the best base theme as per your need.


How to detect device in template file in drupal 7 I want to get the device whether is it Mobile,Tablet,Iphone or desktop based on the screen width. I know about breakpoint and picture module. But I need to change some HTML based on that condition. How can I get the condition in tpl file.

I would use Context & Context Mobile Detect


Permissions based on multiple OG groups? Is it possible to have permissions, based on multiple organic groups?

I have 2 group content types: One 'Organisation' group type and one 'Department' group type.
There are multiple organisations and each organisation and multiple departments. Each organisation has the same departments. So for example:

ORGANISATION GROUPS:

Google
Yahoo
Microsoft
Samsung

DEPARTMENT GROUPS:

Customer Service
Management
Finance
Sales

Each user will be a member of one organisation and one or more departments.

What I want is:
If an admin adds content (like a news article), he can choose the organisations and/or departments. Users in both the chosen organisations and departments can see the content. If a user is in a chosen organisation, but not in a chosen department, he can not see the content.

If no organisation is checked, the users in all organisations can see the content (if they are in the chosen departments). If no department is checked, the users in all departments can see the content (if they are in the chosen organisations). If no organisation and no department is checked, all users can see the content.

I tried to use sub-groups, but then the admin has to choose all the (for example) 'Sales' departments of all the organisations instead of just clicking one 'Sales' department.

It's not possible out-of-the-box.  Organic groups access control basically says if a user is in one group they can see the content in that group.

However you could write your own hook_node_access that evaluates the logic you described.


Rebuild form is not working in #ajax callback I've tried to build a form with #ajax submit function and rebuild the form. The following is my code.

function campaign_new_form($form, &$form_state){

 if(!isset($form_state['num_names'])){
   $form_state['num_names']=2;
 }

 // Create wrapper for ajax
 $form['#prefix'] = '
';
 $form['#suffix'] = '
';

 for ($i = 1; $i <= $form_state['num_names']; $i++) {
   $form['name_' . $i] = array(
     '#type' => 'textfield',
     '#title' => 'Value ' . $i,
     '#required' => true
   );
 }

 $form['add_button']= array(
  '#type' => 'submit',
  '#value'=> 'Add more',
  '#ajax' => array(
    'callback' => 'campaign_new_form_callback',
    'method' => 'replace',
    'effect' => 'fade',
    'wrapper' => 'form-wrapper',
 ),
);

 return $form;
}

function campaign_new_form_callback($form, &$form_state){
  $form_state['num_names']++;
  $form_state['rebuild'] = true;
  return $form;
}

It always renders two fields. What is the problem in my code?

Setting the rebuild in the ajax callback will not work, as the form has already been built at that point. It needs to be set in a submit function, which is fired before the form is built. You also need to increment your counter in the submit function for the same reason - if you do it in the ajax callback, the form is already built so the increment is not saved. It needs to be done in the submit function.

function campaign_new_form_submit($form, &$form_state)
{
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}


Access / Alter user registration form submit button in $form variable In drupal 8, I have created a custom module to alter the user login and register forms in 2 class that extends UserLoginForm and RegisterForm respectively.

Whereas for the login form I can add some link in the $form['action'] array or add a class to the submit button:

 $form['actions']['submit']['#attributes'] = [
    'class' => ['btn', 'btn-primary'],
 ];

a contrario, there is no action array in user register $form variable(!)

So how can I access in my class the submit button, and more generally, the action array?

While UserLoginForm is a regular form based on form api, RegisterForm is an entity form, where the actions are defined in a separate method EntityForm::actions(), which is overridden in RegisterForm:

  protected function actions(array $form, FormStateInterface $form_state) {
    $element = parent::actions($form, $form_state);
    $element['submit']['#value'] = $this->t('Create new account');
    return $element;
  }

which you can override again in your extended class.


How can I trigger a rules event by code ? I'm using Commerce for the website I'm building right now.
I want to trigger the event "Calculate the sell price" after an order is updated to a status, I made one called "Approved".
The reason I want to do that is that the Tax is calculated at this event and at the "Checkout: Checkout" page, but the store manager wants to choose if the customer should pay tax or not, he wants to do that manually not using billing or shipping conditions.

I added a boolean field "Apply VAT?" to  the order page and added a condition if that entity exists and is true to apply the VAT tax, but this is:not done at the checkout page and I noticed that if I change the status back to "Checkout: Checkout" the VAT tax is applied and this is because of the "Calculate the sell price" event (tell me if I'm wrong).

I was thinking to build a rule with the event "Order is updated" and the action to be a PHP code to invoke the event again, I know about rules_invoke_event, but I can't get it working.

I also have problems with the tax not being applied to the shipping cost, but this is another problem (maybe I will open another question of this)

I will appreciate any answers, thanks!

I managed to invoke the event "calculate sell price" by adding a rule with the event "When existin line item is updated" and then adding a call to rules_invoke_event() in PHP code like this:

rules_invoke_event("commerce_product_calculate_sell_price", $commerce_line_item);

I was previously calling this rule incorrectly, without adding the $commerce_line_item so this problem is resolved, now the shipping remained.
Thanks for your time!


Switching multiple DB and mysql_close Do we need to call mysql_close(); before switching the database using                db_set_active('sharedb');?

No, you should not call any mysql functions at all. You don't mention the drupal version, but in 6, it's likely that you're actually using the mysqli extension and in 7, you're using PDO.

I don't think that a handful open database connections is going to be a problem, they will be automatically closed by the end of the request. So unless you have a long-running process or more than a handful connections you need to make, I wouldn't worry.

If you have either of those, then you might need to care about this, if you're on 7.x, there's an API for this: Database::closeConnection().

On 6.x, you're not so lucky, while you could check global $db_type (see db_set_active()), and call the right function, you also need to pass global $active_db to the function to close the right connection and you can't update $db_conns in db_set_active(), so that will not know that you closed the connection and you can't re-open the connection again.


Site search plus google search I am searching for a way to have the drupal search pull up pages from the drupal site PLUS search results from google in general (not site specific search). Does anyone know some direction how to accomplish this?

You need to check with this two Google Site Search & Google Custom Search Engine modules.


How to delete node revisions I need to delete all node revisions before upgrading to Drupal 7 to save time in migration. Is there any way to do that?

You can use the following code.

db_query('DELETE FROM {node_revisions} nr WHERE nr.vid NOT IN (SELECT n.vid FROM {node} n)');

You don't want to delete all the revisions: You want to delete all but the current revision.

Executing only that query is going to leave data about deleted revisions in other database tables, as modules that save information about a revisions are not notified a revision is going to be deleted. I am thinking of the CCK module, for example, which saves information about the node fields in its own database tables. The CCK module executes the following code, when a revision is deleted.

/**
 * Implementation of hook_nodeapi 'delete_revision' op.
 *
 * Delete node type fields for a revision.
 */
function content_delete_revision(&$node) {
  _content_field_invoke('delete revision', $node);
  _content_field_invoke_default('delete revision', $node);
  cache_clear_all('content:'. $node->nid .':'. $node->vid, content_cache_tablename());
}

A more complete code would be similar to the following one.

$query = db_query('SELECT nr.nid, nr.vid FROM {node_revisions} nr WHERE nr.vid NOT IN (SELECT n.vid FROM {node} n)');

while ($revision = db_fetch_object($query)) {
  if ($node = node_load($revision->nid, $revision->vid)) {
    node_invoke_nodeapi($node, 'delete revision');
  }
}

db_query('DELETE FROM {node_revisions} nr WHERE nr.vid NOT IN (SELECT n.vid FROM {node} n)');

Looking at the code of node_revision_delete_confirm_submit(), I don't see anything else that needs to be done.

The new code I wrote could take much time to be executed, depending on the number of nodes, and revisions. This means the code should be executed:

In an implementation of hook_cron()
As a batch operation
In a PHP file that bootstraps Drupal, and increases the execution time with @set_time_limit(240)
With Drush

Considering that the code is only necessary for the migration, I would avoid the first two options, which would require you to write a module you need just in this very specific case. If you have more sites, and all of them need to execute the same code, option 3 is always possible, and that is what is done from Drupal with cron.php.
About option 4, I would first check Drush doesn't have already commands that could be helpful in this case. I would not reinvent the wheel, when it is not strictly necessary. I would also check how to write Drush Shell Scripts.


Override path with Views How can I override the default display of a taxonomy term with a view ?

eg : the path of a taxonomy term taxonomy/artist/artist_name take me to the default display of a taxonomy term and I want to display a specified view to the same path.

in resume override the path.

thanks !

Make the page display path taxonomy/term/% and the first argument to the view should be the term ID. There is a disabled view for this purpose which should set these up for you, but if you already have a view you can also make that override the core taxonomy path by making the two adjustments I mentioned.


How to hide Fivestar rating field after first comment? The accepted answer on How to limit a user to one vote when using Fivestar? doesn't work for me, but the author hasn't provided a solution yet, so I felt this is worth a new question.

My goal is exactly the same as the one in the article mentioned above: I'd like to hide the Fivestar rating field (called field_stars) in the comment form when a user comments on a node on which he/she's already commented.

Is there another solution (for example with the Rules and Flags modules)?

Edit: I already have a flag called Commented on my site and a rule that flags a node on behalf of the commentator when someone commented on it (which works perfectly). I'd really like to use it to fix this problem. I tried something, based on the information I found here:

function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $flag = flag_get_flag('commented') or die('no "commented" flag defined');
  if ($form_id == "comment_node_stuff_form") {
   if ($form['#node']->uid == $user->uid OR $flag->is_flagged($form['#node']->uid, $user->uid)) {
      unset($form['field_stars']);
    }
  }
}

Unfortunately, it doesn't change anything (I don't get any errors either).

In your node.tpl.php you should have the following code

hide($content['field_fivestar']);
print singlerating_print_rating($node->nid, $content['field_fivestar']);

I presume field_fivestar is the fivestar field you are using and not field_fivestar_rating


Some drupal database operations won't complete On a development server (and it's sister staging server), I'm not sure how I got myself into this situation. When running drush updatedb I get this error below.

$ drush updatedb
The following updates are pending:

redirect module :
  7101 -   Add status field.
  7102 -   Disable redirects that could cause infinite loops.

webform module :
  7322 -   Add index on {webform_submitted_data}.data.

Do you wish to run all pending updates? (y/n): y
Cannot add field redirect.status: field already exists.                                       [error]
Performed update: redirect_update_7101                                                        [ok]
Cannot add index data to table webform_submitted_data: index already exists.                  [error]
Performed update: webform_update_7322                                                         [ok]
Finished performing updates.

I occasionally dump the production server database onto dev and stage to have an updated copy.

Is there a way I can push through this?

Is everything working fine on the production server?  If so, try erasing the development database, and then copy the production database over it again.  Drush sql-sync does not delete the target database by default.

drush @dev sql-create
drush sql-sync @prod @dev


Query and load entity by Entity Type Manager Currently I am firstly "searching" for an taxonomy term entity with the Entity Query in Drupal 8:

$termIds = \Drupal::entityQuery('taxonomy_term')
  ->condition('field_code', $code)
  ->condition('vid', 'computer')
  ->execute();

And then I am loading the taxonomy term entity:

      $termId = current($termIds);
      $term = \Drupal::entityTypeManager()
        ->getStorage('taxonomy_term')
        ->load($termId);

Is there a way to do it in 1 step, instead of these two?

You can do this in one step by using loadByProperties():

$term = current(\Drupal::entityTypeManager()->getStorage('taxonomy_term')
  ->loadByProperties(['field_code' => $code, 'vid' => 'computer'])
);

This method is a shortcut for basic entity queries like you have here and also includes the step for loading the entities.


Add a small javascript/HTML to a page So I have a small bit of HTML and Javascript that I want to embed in a basic page. I go to edit the page, turn off rich text editing, and paste the HTML/javascript. I save, and then the javascript portion gets deleted while the HTML stays.

Is there any reason for this?

It is worth noting that the site is maintained and run by the university, although I have full permissions.

Other people say just add a bit of php and add_jscript(), but don't say where that goes, or how to get to that file.

EDIT: So I contacted the IT department and they suggesting adding the script as a block, and then adding the block to the page. Thanks for all your help!

It looks like what's happening is your text format settings are stripping the JS out of the page. You can edit the formats by going to /admin/config/content/formats, or you may just need to select a different format for the node in question (under the body field when you edit the node).

If you need the JS available on several pages, have a look at: https://www.drupal.org/node/304255.


Alter form field from module In my user profile, I have some fields I want to alter. For my regular fields I use:

mymodule_form_alter(&$form, &$form_state, $form_id)

That works, but inside the $form there are some fields missing. Like for example the Timezone settings and the Private Messages. So fields from another module (like Private Messages) or standard settings. How can I alter those?

I tried a custom template file for the user profile and there I have access to those fields inside the $form. But I shouldn't altern them in a template file, right? So what would be the right approach for this?

hook alter normally works on contrib modules. I can see the reason why it has not been working is due to fact that the module needs to be altered got more priority than the altering module.

To overcome such scenario you need to manually change the priority of your custom module, this can be done by changing the value of weight column in system table.


How to add an image gallery to content type What I need is to let the user add a few images in the content type, and after the user posts Title, Body message, these images should show as a gallery on the node.

I know how to do the gallery via views Gallerific, but how do you add this gallery to a node?

This might be of interest to you. It uses a content type and views for each user.
Add a gallery for every user in a block If you require further assistance please let me know. The answer is quite detailed and is broken up step by step. What version of Drupal are you using.


ajax callback add more on a select field I am trying to implement a "add x" on a select field but it doesn't seem to work.

I've tried to follow this example but they use a submit for that.

$form['myfield'] = array(
    '#type' => 'select',
    '#options' => $optionsServer,
    '#ajax' => array(
        'callback' => 'ajax_select_change',
        'wrapper' => 'names-fieldset-wrapper',
        'method' => 'replace',
        'effect' => 'fade',
    ),
);

$form['#tree'] = TRUE;
if (empty($form_state['num_names'])) {
   $form_state['num_names'] = 1;
}
$form['myfieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('myfieldset'),
        '#prefix' => '
',
        '#suffix' => '
',
    );
for ($i = 0; $i < $form_state['num_names']; $i++) {
   $form['myfieldset']['field'.$i] = array(
       '#type' => 'textfield',
       '#title' => t('field'),
       '#size' => 60,
       '#required' => TRUE,
   );
}

function ajax_select_change($form, &$form_state){
    //$form_state['num_names'] is used to create x new textfield
    $form_state['num_names'] = $form_state['values']['myfield'];
    //rebuild this form to get the new count
    $form_state['rebuild'] = TRUE;
    //change the fieldset containing the code to build textfield
    return $form['myfieldset'];
}

Is it doable?
I can try to create a button then trigger it when I change the select value but this is clearly a crappy hack.

Any idea?

EDIT: I find out some solution:

function my_form($form, $form_state){
    $form['container']['myField1'] = array(
        '#type' => 'select',
        '#options' => $optionsField1,
        //don't forget the $form_state['values']['container']['myField1'] as default, it will keep the same value after the rebuild
        '#default_value' => isset($form_state['values']['container']['myField1']) ? $form_state['values']['container']['myField1'] : $form_state['num_names'] ,
        '#ajax' => array(
            'callback' => 'ajax_select_change',
        ),
    );
}

function ajax_select_change($form, $form_state){
    $new_state = array();
    $new_state['build_info'] = $form_state['build_info'];
    $new_state['rebuild'] = TRUE;
    $new_state['values'] = $form_state['values'];
    $new_state += form_state_defaults();

    $new_form_array = drupal_rebuild_form('my_form', $new_state);
    $new_form = drupal_render($new_form_array);

    $commands = array();
    //reload form
    $commands[] = ajax_command_html('#formId', $new_form);
    //change inside Id #price
    $commands[] = ajax_command_replace('#price', drupal_render($form['container']['myField2']));
    return array('#type' => 'ajax', '#commands' => $commands);
}

EDIT 2: see the proper solution below (in the comment), much more simple and make more sense!

After an AJAX submit by a select or some similar not submit element the Form API rebuilds de form if no validate errors are found. See drupal_process_form() where this is stated in the inline comments:

// However, for forms that have not been fully executed (e.g., Ajax
// submissions triggered by non-buttons), there is no submit handler to set
// $form_state['rebuild']. It would not make sense to redisplay the
// identical form without an error for the user to correct, so we also
// rebuild error-free non-executed forms, regardless of
// $form_state['rebuild'].

Your code is not working because you update your number of elements in the callback function in this line:

$form_state['num_names'] = $form_state['values']['myfield'];

The callback function is executed after all form processing so your modifications are done too late. In fact, callback function should only return the response, no modifications on the form should be done here.

Try something like this:

$form['myfield'] = array(
    '#type' => 'select',
    '#options' => $optionsServer,
    '#ajax' => array(
        'callback' => 'ajax_select_change',
        'wrapper' => 'names-fieldset-wrapper',
        'method' => 'replace',
        'effect' => 'fade',
    ),
);

$form['#tree'] = TRUE;
if (empty($form_state['num_names'])) {
   $form_state['num_names'] = 1;
}
else {
  // If there's is value in myfield update number of available names elems.
  $form_state['num_names'] = $form_state['values']['myfield'];
}

$form['myfieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('myfieldset'),
        '#prefix' => '
',
        '#suffix' => '
',
    );
for ($i = 0; $i < $form_state['num_names']; $i++) {
   $form['myfieldset']['field'.$i] = array(
       '#type' => 'textfield',
       '#title' => t('field'),
       '#size' => 60,
       '#required' => TRUE,
   );
}

function ajax_select_change($form, &$form_state){
    return $form['myfieldset'];
}


How to show a specific date format in an English view? I have multi-language web site. I have a date field with a specific format in a view, and I want to display the date in English format.

How can I do this?

In views, click on your date field and select Custom as your Date format.

Then see the PHP Date Manual, under Custom Date Format type your custom date accordingly.

For Example:


How can I call node id in template file? Using Drupal 7.

I have a page--front.tpl.php template file. And I want import a node in this file.

How can I do it?

Here is my solution:

<?php
$view_mode = 'teaser'; // Or 'full' for example

$node = node_load(2);

$view = node_view($node, $view_mode);

print render($view);
?>


How to get parent paragraph from a child block preprocess Searched all over the place but cannot find anything similar. Here's the issue...
The setup:

'Page' content type
'Block Content' paragraph type

The 'Page' content type has a field for referencing the 'Block Content' paragraph, called "Components" (set to unlimited). Now we can use paragraphs within our page. Simple.
The 'Block Content' paragraph type has a field for referencing blocks (using the module Block Field). It also has two other fields for title and subtitle. These fields need to be displayed on the referenced block template for this paragraph instance. This is the issue.
I have included some images to show the setup.
I am trying to use theme_preprocess_block to inject these fields (title and subtitle) into the correct block using $vars['plugin_id'] from the block preprocess but the issue is that the block does not know its paragraph parent. And if I don't know the parent, I can't retrieve these fields that I need to inject into the block.
This answer suggests using the following to get the parent:
$parent   = $variables['elements']['#node']->_referringItem->getEntity();

But in my case I could not find anything equivalent in my block preprocess function.
Update 1:
I tried (from within theme_preprocess_block):
dpm($vars['elements']['content']['#block_content']->_referringItem->getEntity());

This give the following error:
Error: Call to a member function getEntity() on null in limit_preprocess_block__banner_block()

Update 2:
I just dumped the $vars from the preprocess function and noticed that there seems to be the paragraph id in there. But I don't know how to access it from the $vars variable. Is it possible? (see dump image below)

IMAGE 1:

IMAGE 2:

IMAGE 3:

IMAGE 4:

IMAGE 5:

The linked answer was using this inside a node hook.
In case of hook_preprocess_block(&$variables) you can try $variables['elements']['content']['#block_content'] instead. This should return the content entity, similar to the linked answer.
Notice: $whateverEntity->_referringItem is not cache-safe, so if you are referencing the same block on multiple paragraphs, this will not work reliably.


Translate routing and menu titles I've made two yml files, for both routing and menu item:

Route:

tester_helper.products_controller_overview:
  path: '/assortment'
  defaults:
    _controller: '\Drupal\tester_helper\Controller\ProductsController::overview'
    _title: 'Assortment'
  requirements:
    _permission: 'access content'

Menu item:

tester_helper.products_controller_overview_link:
  title: Assortment
  parent: main
  route_name: tester_helper.products_controller_overview
  menu_name: main
  weight: 3

Is it possible to translate both the path and the menu item title?

For example:
EN (english):
"Assortment" => /assortment

DE (german):
"Sortiment" => /sortiment

_title in *.routing.yml and title in *.links.menu.yml are translatable by default. Go to user translation (/admin/config/regional/translate) and search there for 'Assortment' and translate it.

The path is not translatable. See this similar question:

Translating paths in routing.yml

In the answer you find some ideas.


How do I add certain Fields to a View (not all fields are showing in Add list)? I'm creating a view where I'd like to output a custom field. I am basing this off an already existing view, which already uses the said custom field.

However, when I hit the 'Add' button in the View's Fields section I do not see the same Fields as the already-built view.

Is there some way to associate the View with a certain group of Fields so that I can add them?

Is there some way to associate the View with a certain group of Fields

Yes, this is done by adding a relationship.

For example, if you create a content view and add a relationship of Content: Author, you will now be able to add user fields, such as User: Picture or User: E-mail to name a few.

Therefore, look if the already built in view is using a relationship. (It's under Advanced, located on the far right of the View's settings).


Get proper block title from block object I have a block object in drupal 8 that I am trying to get the title of. I tried $block->label() and it seems to work for some block types, but not for Views blocks. On those, it returns the block's admin label, not the configured title.

If it matters, I am trying to find this information from hook_preprocess_region().

If you were using hook_preprocess_block() it would be much easier to get the title, you would simply load the block by its id and get the label from the returned block object like this:

function hook_preprocess_block(&$variables) {
  $variables['new_title'] = \Drupal\block\Entity\Block::load($variables['elements']['#id'])->label();
}


Adding  around link or mail I have a custom module which prints html in hook_block_view. The text that my hook_block_view returns(in block['content']) might contain links and mail addresses.
Is there a drupal(or PHP) function that wraps the links/mail id in  ?

You can configure one of your text formats to use the "Convert URLs into links" filter, then to apply that text format to some text you can use the check_markup() function like this:

// Run text through the Filtered HTML text format.
$formatted_text = check_markup($original_text, 'filtered_html');

You can change 'filtered_html' to be whichever text format you want to apply.
Note that it will run all the other filters of that text format on the text also.


How to redirect anonymous users to a login page? I have several type of nodes for content that is contributed by authenticated users. I would like the links to be visible to anonymous users but if they click the link to have it redirect them to the user log in page and if at all possible have the destination send them to the node creation page? I can use either a custom module or rules. How do I do this? Also, how do I have the flag links do this too?

If you use the LoginToboggin Module. It Provides a login form on Access Denied pages for non-logged-in (anonymous) users, instead of just the standard "Access Denied". (Also, good for admins, who forget to login when trying to access admin areas too)


How to make a image url active in Views Table I've got a table with a column for images. The field display is link (see screenshot). For some reason it doesn't display as an active link. Any ideas on how to accomplish that?

I assume that this is a file field and that you chose URL to File as the field formatter. You would then need to scroll down and expand Rewrite results, tick the box for Output this field as a link, and in the box for Link path you need to enter the views token replacement for your field name, which you can find by expanding the section below titled Replacement patterns—in your case it is likely to be [field_scan]

Once you enter that, you should have what you are calling "active link" which in more precise terms would be called an hyperlink or anchor tag.


How do I prevent delimiters in a URL from being URL encoded? I need to know how to get a +-delimited string to be appended to the end of the URL path without the + character being URL encoded.

Why: I'm trying to pass arguments to a View. I'm working on a custom module to conditionally route webform confirmations to a View. The view will take multiple arguments, returning all nodes matching the arguments (currently trying to do this with Views 3.0).

I've done proof-of-concept tests on the view that demonstrate that for a view with a path of, say, cbos/name1+name2 it will produce the desired result (i.e., displays nodes name1 and name2). So I know that this can be done from the Views side. (I'm pretty certain at this point Views has nothing to do with it, I just need to make clear why I need to do this.)

The problem is on the custom module / webform side.

I'm creating the URL path using the following code:

while ($cbo_short_name = db_fetch_array($result)) {
if ($count > 0) $delim = '+';
$cbo_short_names_arg .= $delim.$cbo_short_name['cbo_short_name'];
$count = $count + 1;
}
$redirecturl = "cbos/".$cbo_short_names_arg;
$node->webform['confirmation'] = drupal_urlencode($redirecturl); // ... have also tried setting this via the form settings page using tokens

... where $cbo_short_name is an array of short names (usually initials) for organizations. (There's usually only 1, but in about 15% of cases there will be 2 or 3 short names. The visitor has to be shown all of them. Hence, the View)

What this should do is produce a URL path of the form given above; what's happening is that '+' is getting URL encoded as %2B (e.g. cbos/name1%2Bname2), which breaks the Views argument string -- only the first result is returned.

If I could somehow force '+' to be passed intact, without URL encoding, this would work. But I'm at a loss for how to do that.

What I've tried so far:

Setting the confirmation URL on the form settings page (preferred,
since I don't have to hard code it).
Setting the redirect URL
programmatically (what you see above).

Both work to set a value, but in both cases the delimiters are URL encoded in the resulting URL path.

I am sure I am missing a or the point here, but, could you do something like this:

while ($cbo_short_name = db_fetch_array($result)) {
  if ($count > 0) $delim = '+';
  $cbo_short_names_arg .= $delim . drupal_urlencode($cbo_short_name['cbo_short_name']);
}
$redirecturl = 'cbos/' . $cbo_short_names_arg;
$node->webform['confirmation'] = $redirecturl;

eg, sanitize your arguments but then glue them together with the + (that isn't encoded) ?


Views Contextual Filter by current day I am using the Date Repeat Entity module for generating a checklist for users.  I am able to use Views to display the list in chronological order for tasks relevant for the current user using a Contextual Filter.  Could I also use a Contextual Filter to only show the current nodes that have a date equal to the current date?

I would think this could be done by entering some PHP code as shown here:

I'm not sure how a regular filter will be able to grab the current day

Add your date field to the filter.

You will then see this screen

Click apply and continue

Click on select a date, and select relative date

Put today as your relative date.


Default statistics module. Count views of only published nodes when administration users see it I need to change default functionality of statistics module.

I want to count views of only published nodes by administration users too. I can't find any hook for this.

Now if administration user see unpublished node, counter is increased.

Is this possible without hacking a core?

The Statistics module doesn't use any hook because generally works when Drupal has not completed its bootstrap phase. (That is if caching pages is enabled.)

What you can do is creating a custom module that runs right after the Statistics module, and execute code similar to the following one.

function mymodule_exit() {
  global $user;

  drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES);
  $is_node = (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == NULL);

  if (variable_get('statistics_count_content_views', 0) && $is_node) {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    $node = node_load(arg(1));
    if (!$node->status) {
      db_merge('node_counter')
        ->key(array('nid' => $node->nid))
        ->fields(array(
          'daycount' => 1,
          'totalcount' => 1,
          'timestamp' => REQUEST_TIME,
        ))
        ->expression('daycount', 'daycount - 1')
        ->expression('totalcount', 'totalcount - 1')
        ->execute();
    }
  }
  if (variable_get('statistics_enable_access_log', 0) && $is_node) {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    $node = node_load(arg(1));
    if (!$node->status) {
      db_delete('accesslog')
        ->condition('title' => truncate_utf8(strip_tags(drupal_get_title()), 255))
        ->condition('path' => truncate_utf8($_GET['q'], 255))
        ->condition('url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '')
        ->condition('hostname' => ip_address())
        ->condition('uid' => $user->uid)
        ->condition('sid' => session_id())
        ->condition('timestamp' => REQUEST_TIME)
        ->execute();
    }
  }
}


Configure CKEditor - WYSIWYG HTML editor What is the way to configure CKEditor - WYSIWYG HTML editor for Drupal 7 sites?

You can install the CKEditor module for Drupal for that: http://drupal.org/project/ckeditor

You will have to include CKEditor by yourself, which you can download from here

Install the Drupal module and put the ckeditor folder from the second link under sites/all/libraries and that should be it.


How to use Rules to redirect a user based on URL argument? I'm using Drupal 7 and the Drupal Commerce module. I'm now able to capture an argument passed by URL using Rules (thanks to this helpful thread). However, I'd now like to be able to redirect the user to one page if the argument equals one thing and send them to a different page if it equals ANYTHING else. Anyone know how to do that?

I tried using 'Page Redirect' as an action in Rules, after the action of capturing the argument in the URL (Action > Provide URL argument value), but there's no option in the Page Redirect action to send users somewhere based on the argument value.

So for example, I have users coming to the site with urls like so:

membership-renewal/?ID=promo1

Currently Rules is recognizing that they are using that URL and it's reading 'promo1' value using [ID:value] replacement pattern...I can print it out to the screen so I know it's reading it.

But I don't know how to then use that value to inform a page redirect for example.

Anyone know?

Well, if you're planning on doing it solely via rules, you can create a new rule for each if in your logic and then just set them to be actions one after the other. Something like this:

Action:
  RULE:
    IF: <condition>
    REDIRECT: <here>
  RULE:
    IF: <condition>
    REDIRECT: <here>
  RULE:
    IF: <condition>
    REDIRECT: <here>

This would effectively work like an if-elseif-else statement (assuming that the redirection is using drupal_goto().

But really, this sounds like a job for a custom action that takes the parameters and includes your own custom logic. It'd probably be a lot cleaner in the long-run.


Add subtitles to register form I'm trying to add some titles in my registration form. This is a part of my registration form:

But now I would like to have some titles like the following:

I know that you can alter the registration form like this:

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

}

But I don't know which attributes or ... to use.

UPDATE:

I'm now trying out the markup.

This is what I do:

function xmed_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['account']['mail'] = array(
        '#markup' => '
testtttinnng
',
        '#weight' => 116
    );
}

But this just replaces my email content ...

You can use Field group Contributed module...

Project page says..

  Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.


How can I create a Simple page that display the latest node of a content type? I write a little module for loading the content via ajax(one of the used tutorials) and now I need a page for the first visiting(front page). I don't want to do this with Views and looked around, but didn`t found a simple solution for this.

So, I extend the hook_menu () function with:

EDITED

$items['first-node'] = array(
  'page callback' => 'first_node_callback',
  'access callback' => TRUE, //EDIT -> 'user_access' creates Menu error
  'type' => MENU_CALLBACK,
);

and the callback:

function first_node_callback() {
  $query = db_select("node", "n");
  $query->fields('n', array('nid'))
    ->condition("type", "mytype", "=")
    ->orderBy("created", "DESC")
    ->range(0, 1);
  $nids = $query->execute()->fetchCol();
  $nodes = node_load_multiple($nids);
  return node_view_multiple($nodes, 'full');
}

EDITED END

Should i load this in the #markup or use a normal return or need i an extra theme output? I'm little bit confused with the possibilities!

Just do the following with node object in your page callback function. No need of returning separate #markup.

return drupal_render(node_view($node));


Display image fields of a node as slideshow I have created a content type with some text and image fields. I want to display its images as a slideshow below text fields in view node page of this content type. How can I do it ? Is view slideshow module suitable for this purpose ? or I have to use other module ?

I am working in Drupal 6.

Views Slideshow should be more than enough for what you need.

EDIT

I meant View field, not Views Field View - sorry.

  Viewfield provides a field that holds a reference to a View and
  renders it whenever the entity containing the field is displayed.