How to use traditional (national/native) dates and calendars?

I'm hoping that someone else can Optimize this solution and make it better.
I'm ready to receive Any suggestion or criticism or any Other solution for this Challenge.

Features:

Does not requires any hacking or patching core /frontend solution
,display when dates are rendered
Does not change any date in database
Compatible and tested with PHP versions 5.3 and hereinafter
Supports Iranian/Persian/Shamsi/Jalali , Arabic/Hijri/Islamic, Thai, Hebrew...
Calendar systems
Better Performance becuse Doesn't outbreak the drupal core

Method 1, Using "IntelDateFormatter" Class:

First of all you must be sure that version of your php that installed is Newer than 5.3 and 'IntlDateFormatter' Extension was exist.
For use Traditional(National/Native) Date/Calender in Drupal 8 in nodes and Posted Comments with use of IntlDateFormatter class, add below codes to "THEME_NAME.theme":

For Nodes:

function THEME_NAME_preprocess_node(&$variables) {
    $locale = "fa_IR@calendar=persian";
    $dateType = IntlDateFormatter::NONE;//type of date formatting.
    $timeType = IntlDateFormatter::NONE;//if time format setting to none, will give you date itself
    $timezone = 'Asia/Tehran';
    $calendar = IntlDateFormatter::TRADITIONAL;//Non-Gregorian Calendar
    $pattern = 'y/M/d';

    $fmt = new IntlDateFormatter($locale, $dateType, $timeType, $timezone, $calendar, $pattern);
    $date = $variables['node']->getCreatedTime();
    $variables['date'] = $fmt->format($date);
}

For Comments:

function THEME_NAME_preprocess_comment(&$variables) {
    $fmt = new IntlDateFormatter(
    "fa_IR@calendar=persian",
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    'Asia/Tehran',
    IntlDateFormatter::TRADITIONAL,
    'y/M/d'
    );

    // Getting the node creation time stamp from the comment object.
    $date = $variables['comment']->getCreatedTime();
    $variables['created'] = $fmt->format($date);
}

Information about "IntlDateFormatter" Parameters:
locale: Locale to use when formatting or parsing or NULL to use the value specified in the ini setting, Link:http://www.w3.org/International/articles/language-tags

datetype:Date type to use (NONE, FULL, LONG, MEDIUM, SHORT). This is one of the IntlDateFormatter constants.

timetype:
Time type to use (NONE, FULL, LONG, MEDIUM, SHORT). This is one of the IntlDateFormatter constants.

timezone:
Time zone ID, default is system default,
Link:http://www.php.net/manual/en/timezones.php.

calendar:
Calendar to use for formatting or parsing; default is Gregorian. This is one of the IntlDateFormatter calendar constants.
The calendars ICU allows you to play with include:

Japanese (@calendar=japanese)
Buddhist (@calendar=buddhist)
Chinese (@calendar=chinese)
Persian (@calendar=persian)
Indian (@calendar=indian)
Islamic (@calendar=islamic)
Hebrew (@calendar=hebrew)
Coptic (@calendar=coptic)
Ethiopic (@calendar=ethiopic)

Link:http://userguide.icu-project.org/datetime/calendar

pattern:
Optional pattern to use when formatting or parsing. Possible patterns are documented at: http://userguide.icu-project.org/formatparse/datetime

METHOD 2,Using External Functions (like "jdf" for persian language):

First download this function form: http://jdf.scr.ir/download/
and then put downloaded file to your theme folder and add this code to above of "Theme_Name.theme"

include ('jdf.php');

and then add below code to appropriate place:

function Theme_Name_preprocess_node(&$variables) {
   $date = $variables['node']->getCreatedTime();
   $variables['date'] = jdate("l j F Y", strtotime($date));
}

I'm hoping that someone else can build on this and make it better.


How to use #states with a container element?

As it's been mentioned, the #states property doesn't work for fieldsets, containers.
You need some JS here, e.g:

The form

$form['promo_code_trigger'] = [
  '#type' => 'container',
  '#attributes' => ['id' => ['promo-code-add-el']],
  'data' => [
    '#markup' => t('Add promotional code'),
  ]
];

$form['promo_code_wrapper'] = [
  '#type' => 'container',
  '#attributes' => [
    'id' => ['promo-code-add-el-triggered'],
    'class' => ['hidden'],
  ],
];

JS

$("#promo-code-add-el").on("click", function (e) {
  $('#' + e.target.id + "-triggered").toggleClass('hidden');
  $('#' + e.target.id).toggleClass('active');
});


How to apply header and footer or layout to all pages in a panel enabled website?

There are lots of answers to your question. Here is mine :)

I usually define 3 areas. The Header and the Footer are "static" blocks that are shown in every site pages. The content is in the middle and is defined with Pages and Panels. That's it!


Security considerations for special characters in usernames?

I can think of three concerns when it comes to usernames and security: Cross Site Scripting (XSS), SQL Injection, and Homograph "attacks".

As long as you don't allow the < and > in usernames then you don't have to worry about XSS. If you want to allow one or both of those then you need to be more suspicious and do a thorough test of your site for XSS by entering a malicious username and seeing what happens.

SQL Injection should not be a problem. This has largely been solved in Drupal for a while and DBTNG in Drupal 7 makes it even less common. You could still test for it with some weird usernames that contain '; and other character combinations.

Homograph is then the worst thing. For a while (maybe still) you could register a username like Admin which looks a lot like Admin but in fact uses the MATHEMATICAL BOLD CAPITAL A from the list of confusables. The problem would arise from someone using a username that is a homographic match to a known "admin" on your site to register on the site and then using the contact or private message feature of the site (or even a public node/comment) to trick other users of the site into doing something stupid (e.g. posting a message "Our site is having login problems, please go to http://sitename.evil.example/password-reset and enter your credentials to have your login fixed."). By adding more characters to the allowed set of username characters you make a homograph social-engineering attack more likely/easier. I don't consider this to be a big problem and you should consider whether this is really a problem for your site before worrying about it.

The Real Name module is meant to give you this ability without the form alter. I don't think it's really any safer for homograph attacks, though.


How to add a theme preprocess function for published state?

You can fetch the node using routeMatch and add the class like this:

function THEME_NAME_preprocess_html(&$variables) {
  $routeMatch = \Drupal::routeMatch();
  $node = $routeMatch->getParameter('node');
  if (isset($node) && $routeMatch->getRouteName() == 'entity.node.canonical') {
    if ($node->isPublished()) {
      $variables['attributes']['class'][] = 'class-name-published';
    }
    else {
      $variables['attributes']['class'][] = 'class-name-unpublished';
    }
  }
}

This only adds the body class if you're on the entity.node.canonical route, to make sure that we always get a node object from the route parameter.


Try to run http://serversite.com/update.php.

You may have forgotten to clear the cache before you download the Database you upload to the server.

Next Time try try to clear the cache before you export your database file. Also I will recommend you use Backup and Migrate Plugin, that should be efficient in the future without error


How do you restrict specific content types per user role

You can set the permissions for each content type and role with Drupals default permissions.

Go to /admin/people/permissions there is a section called Node where you can set the individual permissions for each content type:

Create new content
Edit own content
Edit any content
Delete own content
Delete any content

Keep in mind that the permission Bypass content access control overrides the access restrictions of the individual content types. So if a role has this permission, the user can view, edit and delete all content.


how is config saved in nodeapi_example module?

There is no hook that needs to be implemented by the module for that purpose: Saving the value is automatically done by Drupal. In that case, the value for the nodeapi_example_node_type form element is saved in the nodeapi_example_node_type_<CONTENT_TYPE> Drupal variable, which is the variable the module accesses for the default value.

// Compare the following line...
$form['rating']['nodeapi_example_node_type'] = array(
  '#type' => 'radios',
  '#title' => t('NodeAPI Example Rating'),

  // with the following.
  '#default_value' => variable_get('nodeapi_example_node_type_' . $form['#node_type']->type, FALSE),
  '#options' => array(
    FALSE => t('Disabled'),
    TRUE => t('Enabled'),
  ),
  '#description' => t('Should this node have a rating attached to it?'),
);

Similar code is used in locale_form_node_type_form_alter().

  if (isset($form['type'])) {
    $form['workflow']['language_content_type'] = array(
      '#type' => 'radios',
      '#title' => t('Multilingual support'),

      // The variabile name is <FORM_ELEMENT_NAME>_<CONTENT_TYPE>.
      '#default_value' => variable_get('language_content_type_' . $form['#node_type']->type, 0),

      '#options' => array(t('Disabled'), t('Enabled')),
      '#description' => t('Enable multilingual support for this content type. If enabled, a language selection field will be added to the editing form, allowing you to select from one of the enabled languages. If disabled, new posts are saved with the default language. Existing content will not be affected by changing this option.', array('!languages' => url('admin/config/regional/language'))),
    );
  }

As for the purpose of the other node hook implementations:

nodeapi_example_node_delete() is called when a node is deleted
nodeapi_example_node_insert() is called when a node is inserted in the database
nodeapi_example_node_load() is called when a node is loaded
nodeapi_example_node_update() is called when a node is updated
nodeapi_example_node_validate() is called when data entered for a node need to be validated
nodeapi_example_node_view() is called when a node is being show

Notice that hook_node_update() and hook_node_insert() are mutually exclusive: Drupal calls one or the other, but not both the hooks at the same time. The first is called when an existing node is update; the second is called when a node is created.

In your code the error is the mismatch between the form element name (followbtn_node_type) and the name of the Drupal variable you are using (followbtn_default_mode_<CONTENT_TYPE>). You need to change your code in one of the following ways:

$form['followbtn_rating']['followbtn_node_type'] = array(
  '#type' => 'radios',
  '#title' => t('NodeAPI Example Rating - Custom'),
  '#default_value' => variable_get('followbtn_node_type_' . $form['#node_type']->type, FALSE),
  '#options' => array(
    FALSE => t('Disabled'),
    TRUE => t('Enabled')
  ),
  '#description' => t('Should this node have a rating attached to it?'),
);

$form['followbtn_rating']['followbtn_default_mode'] = array(
  '#type' => 'radios',
  '#title' => t('NodeAPI Example Rating - Custom'),
  '#default_value' => variable_get('followbtn_default_mode_' . $form['#node_type']->type, FALSE),
  '#options' => array(
    FALSE => t('Disabled'),
    TRUE => t('Enabled')
  ),
  '#description' => t('Should this node have a rating attached to it?'),
);


How can I create dynamic options based on the existing bundles from hook_drush_command()?

This should work. Drush bootstraps Drupal before discovering module commands, so the first step is to make sure your commands are defined in a drush.services.yml file as usual.

From there, you should be able to define dynamic options using hook options. Since Drush bootstraps Drupal prior to discovering module commands, you should find that the Drupal site is always bootstrapped when your hook is called. You can inject the services you need through your drush.services.yml file.

EDIT When I read through the comments I thought that you said this was working when you were using hook_drush_command, so I answered as if you were asking how to convert and do the same thing in Drush 9. I don't remember the internals of the convoluted Drush 8 bootstrap very well, but I'm not sure this is possible in Drush 8.


Dealing with nodes that do not have the field when sorting views using date field

You would need to sort your posts by two criteria

Has a expired date
The value of the expired date

Or alternatively you could use ASC/DESC to display those without an expire date first. Doing that would effect the sorting of the rest of the nodes.

If you want to use two criteria, you could create a computed CCK field that has a value of 0/1 indicating if it has an expire date. You can use that to display all nodes without expire date first, and then sort those with an expired date by the expired date.


Why entity_metadata_wrapper->save() doesn't update node's revision?

When you edit a node via the UI, it is done via node_form().  This has a call near the top to node_object_prepare(), which sets up default values for that node.  This includes setting the default value of $node->revision, which is used by node_save() to determine whether a new revision is needed or not.

The Entity API is revision aware, but node_object_prepare() is a node-specific thing.  This means that you need to manage the values yourself, including setting the revision property to mimic what the node edit form will do.


Instead of running the libraries_load() function:

$library = libraries_load('easyzoom');

I just used the libraries_get_path() function to get the path and attached to the element and added scope of footer.

$easyzoom_library_path = libraries_get_path('easyzoom');

$element['#attached']['js'] = array(
  $easyzoom_library_path . '/dist/easyzoom.js' => array('scope' => 'footer'),
);


How can I run Drush as user 1 in version 5?

See drush topic core-global-options; you will see that the --user flag is still supported.

Of course, you do not really 'log in' to your Drupal site with Drush.  The usual convention is that Drush commands should call API-level functions, which are expected to operate independently of the current user.  (Drupal does access checks before calling the API functions.)  There are only a few instances, mostly in contrib, where setting the user is necessary.


Module hook to add_js to any entity type?

hook_entity_view() should do the trick

  Act on entities being assembled before rendering.

e.g.

function MYMODULE_entity_view($entity, $type, $view_mode, $langcode) {
  switch ($type) {
    case 'node':
      ...
      break;
  }
}


mymodule.install file not creating the table in drupal 7

you should uninstall the module
write the hook_schema function
enable the module.

You should also specify the  primary key in the hook_schema

 'primary key' => array('field_name'),

You can check the drupal link for the hook_schema


Cannot post new content after installing varnish

I finally found a solution. Inside my default.vcl file I added the following block at the top of sub vcl_recv:

sub vcl_recv {

  # forward request directly to Apache if SESSION cookie is set.
  if (req.http.Cookie ~ "(SESS[a-zA-Z0-9]*)=") {
    return (pass);
  }

  ... # whatever else you need to do in vcl_recv
}

Basically I'm just checking to see if my session cookie is set (anyone else reading this might have one formatted differently) and if so, forwarding it to Apache. This seems to have fixed the problems as new content can be posted again. Not really sure why the elaborate cookie filtering I had in place (and which was working in every other case except posting new node content) didn't work, but this seems to be the solution, even if it feels a little heavy handed.


I cannot figure out how to add the search form to a child element in the menu!

The search button on that site looks like it is a menu item however you will find that it is a separate entity, nothing to do with the menu at all.

Usually that kind of thing is achieved using Javascript and AJAX.  Javascript to make the form appear, and AJAX to submit it.

Have a look at the Popup module, it might be what you are after.


A menu is not a block, it's just a collection of links... but the core menu module from Drupal renders the menu as a block to be easier for you to place it in the page and change its location.
There are multiple ways to export or import a menu. Yes, features module is one of them, but for a beginner I would suggest a module only for this, it should be easier. You can try this module.


pager is not working on update of Views 7.x-3.7 to Views 7.x-3.8

I recently had the same problem. Issue for me was Views 7.x-3.8 changes the file plugins/views_plugin_query_default.inc to move the following code from the execute function to the query function.

I fixed it using the following patch:

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


OutboundPathProcessor is not appending $options array?

It seems there is a bug report for that. I found a reference to that issue in a inline comment inside LanguageNegotiationContentEntity::processOutbound().

At the moment, after applying the patch from that issue, query parameters get added to the URL as you would expect and without any need to instantiate 'prefix', but fragment doesn't. More work/comments should go into that issue to assist with resolving it.

As an alternative and in order to get fragments to work, you could try extending the Drupal\Core\Routing\UrlGenerator and replace the url_generator.non_bubbling service. (See https://www.drupal.org/node/2026959.)


Blocks: Old vs. "Custom" and Config vs. Fields

What you describe are three different things:

If you put code in a class that extends BlockBase, then yes, this is
a block plugin.
If you add a custom block in the block library, then you store
content in the database as block_content.
If you place a block in the block library then you add a block
configuration, this is a config entity with the name block.

In a block configuration (3) there can be either a plugin (1) or a block content (2).

You can configure fields in (2), then the storage will be managed by drupal, also for image fields.

If you put form fields in (1) then they are not content, but config. You need submit code to handle this. The result of a file field remains temporary until you decide to save it. And combining config with an uploadable file seems a bit odd, but is possible, see for example the site logo.

Comparing both, I would start with (2) and only use (1) if I need code to make something that (2) does not provide.

Edit: Answer to the comment

If you use (2) you probably should be able to solve most of the tasks you describe in the comment in theming (preprocess + twig).

If not, there may be a solution by using (1) + (2). Put the image in block content (to store it properly in the database), but then use this not as a custom block as in (2), but pull the data in your own plugin. For this put a field in blockForm() to configure the block content id and then use in build() the entity api to load the field data of the configured id.

In fact drupal does the same to get the block content entity into a block, it uses also a plugin for this, but you would make your own.


Rule to create user on webform submission by anonymous user

It looks like your issue is about what is described in "Create entity fails when the user is anonymous" (which is an open Rules issue, current status = RTBC).

That issue also contains a patch (attached to comment #4 of that issue), which might help as a (temporary?) work around.

Note: another way to get it to work, appears to be to use the token [data:email-value-raw], as suggested in a comment to this answer (credits: olisb).


Just chunk the output by using the field names:

{{ content.field_custom }} {{ content.field_custom1 }}

Then do the same for the remaining field.


Could be a couple things, without seeing any of your code it's difficult to help you.

Try:

Making sure you're using double quotes (") instead of single quotes (') around the new line characters. (This is because PHP does not interpolate strings defined by single quotes).
Setting the Content-Type to text/plain in the mail headers. (If you need HTML in your email, use <br /> for new lines).

Also, you should always use \r\n with emails so the new line is recognized across all platforms.


Import a class via template.php or other ways

The code needs to go in node.tpl.php, not page.tpl.php or template.php. Just follow these steps:

If you haven't already, copy the code from node.tpl.php into a file with the same name inside your theme's folder.
Edit the node.tpl.php file and add your markup around the main node div
Flush Drupal's caches (or at least the theme reigstry)

Then your nodes will all be wrapped in the markup you need.

If you just need to do this for a specific content type (I'm going to guess at one called image here), your template file will need to be called node--image.tpl.php. You'll still need the original node.tpl.php file in your theme though, as node template overrides won't work without it.


Call to undefined function menu_load() in .../public_html/includes/menu.inc on line 579

Here are few tips:

Make sure your Drupal core has all the files in the right place (especially menu module).
Make sure your imported database is in UTF-8 format.
Upgrade your Drupal core to the latest version (drush fr && drush up drupal).
Clear all your caches (drush -y cc all), including your memcached (killall memcached).
Rebuild your registry by using Registry Rebuild.
Ff you're using modules which are implementing drupal_bootstrap() (such as Secure Site), disable them.
Try disabling your PHP cache engines (such as XCache, Zend optimizer) to see if that's the problem.
Test it on different environment/machine.
Check your database collation (it should be case insensitive, e.g.: general_ci).
Eventually restore your database from the point where it was working before.


Fatal error: Unsupported operand types in includes\common.inc on line 3022

From official system requirements:

  PHP 5.3.x and higher may produce errors or unexpected behavior

Thus, sadly, what you are seeing is pretty much "expected" unexpected behaviour. Drop back to PHP 5.2.x (x ≥ 5) or upgrade to Drupal 7 or 8 for a full fix.

If you want to only fix this one, consider what AyeshK wrote in comment:

  The $elements variable probably contains an array element that the key does not start with a hash sign and the value is scalar.

There is a lot of things about array operators. Comments under PHP documentation shows that many things are far from obvious. Also, it changed a bit from version to version. Have you tested if $elements is an array in the first place? "Simply" add tests to make sure if operand is still valid, and provide a fallback if it isn't (recreate original behaviour) and you will be good to go.


Migrating user profile picture from D6 to D7

I believe you need to do picture migration separately per the docs (assuming you are using Migrate D2D, which you probably should).  This is all I had for picture migration from one I did last year:

$picture_arguments = $common_arguments + array(
  'machine_name' => 'pictures',
  'description' => t('Migration of user pictures from Drupal 6'),
  'default_uid' => 1,
  'source_dir' => '/some/path/to/sites/default/files/',
  'destination_dir' => 'public://pictures',
);

Migration::registerMigration('DrupalPicture6Migration', $picture_arguments['machine_name'], $picture_arguments);


How to redirect user "back two pages" after login

Append

?destination=[PATH]

to your login link.

You can do this with the Menu Token Module


How to add an entity reference field value on Behat Test

If you have an entity reference field, you need to refer to the entity with it's name/title/label field (this applies for taxonomy terms too). Like you did it.

This code will run for your association:

/**
 * Entityreference field handler for Drupal 7.
 */
class EntityreferenceHandler extends AbstractHandler {

  /**
   * {@inheritdoc}
   */
  public function expand($values) {
    $entity_type = $this->fieldInfo['settings']['target_type'];
    $entity_info = entity_get_info($entity_type);
    // For users set label to username.
    if ($entity_type == 'user') {
      $entity_info['entity keys']['label'] = 'name';
    }

    $return = array();
    foreach ($values as $value) {
      $target_id = db_select($entity_info['base table'], 't')
        ->fields('t', array($entity_info['entity keys']['id']))
        ->condition('t.' . $entity_info['entity keys']['label'], $value)
        ->execute()->fetchField();
      if ($target_id) {
        $return[$this->language][] = array('target_id' => $target_id);
      }
    }
    return $return;
  }

}

Which also means, the first item will be tried to associate with your user, which doesn't mean, that it can be (i.e. for content type restriction). So make sure you have only one entity which named like you want to associate. Also make sure, you don't have ', ' and ' - ' in your value, because those will be converted to multi value, and if ' - ' is present than the ': ' value will be converted to key: value pairs. You need to say exactly the entity name which is possible to refer inside that field (but as far as I can see in the code, make sure you don't have space before and/or after the name field's value, because the query above may fail to find your entity). Also check if your field is a real field, (not like the path 'field', which is not a field) you can do it, be executing the field_info_field_map() command, and if you find your field machine name there, as a key, you are fine.

If all the above is fulfilled and you already has a node which can be referred by the user's field_lines_ref field and the node title is 'Line Name' you should be able to create your user with the reference:

Given users:
    | name | pass | mail    | status | roles  | field_lines_ref |
    | test | test | t@t.com | 1      | Tester | Line Name       |

From features file or

$user_obj = (object) array(
  'name' => 'test',
  'pass' => 'test',
  'mail' => 't@t.com',
  'status' => '1',
  'roles' => 'Tester',
  'field_lines_ref' => 'Line Name',
);
$user = $this->userCreate($user_obj);

from context object.

If these doesn't help, you may need to debug your own code (including vendor code), to see where is the problem.


How do I transfer anonymous data the user when he registers?

In fact it turned out to be simple (after spending a long time trying to be clever).

In hook_form_user_register_form_alter() add a value field to the form...

$form['mydata'] = array(
  '#type' => 'value',
  '#value' => $mydata,
  // in any form you like
);

Then in hook_user_insert() that data is in the $edit array, and already added to the $account object. Make sure you unset it from the $edit array otherwise it'll get put into the 'data' field. Anyway by this point the $account has a uid so it's possible to save the data.


You best bet is to write a small JS script where it will clone the pager's element content into an empty element within that field.

Rewrite the field you wish to insert the pager into. Add a span element or whatever you choose.
Write a small js script to copy one elemen'ts content to another. Use this as an example: https://stackoverflow.com/questions/3475727/how-to-copy-text-from-one-div-to-another-in-javascript


How to add a block to the main page region?

Go to YOUR_SITE/admin/structure/block and find the Content region

then go to Configure

Then configure the Visibility settings, in this case this block only will be showed in the front page.


Order pending but credit card charged drupal commerce

The answer is you need to set the workflow to set the order as completed. Commerce out of the box takes the safe route and assumes nothing about your shopping cart workflow. There is an email that can be configured in Rules for the order confirmation.

The order confirmation email is sent by the rule named Send an order notification e-mail that is under the tag Commerce Checkout in the Rules UI.

To update the order as completed you will need to create a new rule to set the order as completed based on your business rules. It can be as simple as setting the order as completed upon successful completion of an order.

You can use the event Completing the checkout process which will trigger after a successful card charge with Auth.net module or any of the other payment modules, Conditions are none for a simple checkout, actions are Update the order state, data selector is commerce-order then "Order State" is "Completed".

Here is a visual of the rule:


INVALID_SERVICE Error Code on CAS forced login page

this happened to be a nginx misconfiguration


Node content not available to anonymous users

Try rebuilding site content permissions. Every now again that has tripped me. In D7 you can find it @ /admin/reports/status/rebuild.


I found a good solution.  Since there were multiple elements that depended on the same condition for visibility, I realized I could put them into a fieldset and define the condition for the fieldset instead.  This did the trick.


Risks of developping your own theme from scratch?

if, in a theme developed from scratch, you forgot to provide the code for render some elements, are they going to stay hidden?

Yes, of course - if you develop a theme and override core templates, anything that's left out will remain left out. There's no magic in Drupal, it's just PHP at  the end of the day. Think of it from the other side of the equation - if you were building a theme from scratch, and Drupal kept injecting markup into your templates without your say-so, wouldn't that be a crazy state of affairs?

  Is that because developers forgot to render them manually somewhere?

That's impossible to say from here. Could be that, could be some rogue CSS hiding them, could be a theme override of status messages nulling the output, and a bunch of others besides. The only way to know is to have a look and see what's there.

If the theme follows any sort of convention at all you should be able to look for a variable called $messages for the status messages. Usually it's located in page.tpl.php.

What you're essentially asking is akin to "I've built a car from scratch, if I leave out the brakes with someone else put them in for me?". The answer is "Only if someone intervenes manually; the assembly line won't do it automatically".


Password Security for Downloading PDF in drupal7

There are two methods to ensure security of your files:

1) You can choose the "Private downloads" method in admin/settings/file-system, and

Either set your files path to a directory outside your web root so
that they don't have an URL
or leave them where they are and protect them with some .htaccess directive (Order deny,allow and deny from all).

Apache won't serve them directly, and Drupal will read them and serve them with a virtual path system/files.

Then you can set permissions for the files by using an access control module (content_access or nodeaccess or node_privacy_byrole or og) and restricting access to the posts where they were uploaded, so that only some user roles can see them.

Caveats:

Your file-related modules must support the private download method
The private method is a bit slower because of the additional processing.
If you already have uploaded files their links may break if you change the download method now.

2) You can use pdf using mpdf module. it offers the ability to password protect your files.


Need a list of third party video services that i can offload the conversion and serving up of my private videos?

Try these:

ZenCoder
Bits on the Run
Kaltura

with Video module


How to leave user profiles even when there are several pages?

Easiest way:

For each View (which would have User as base table no doubt and which has uid as contextual filter) you add an attachment View Display and pin it to the top of the main view. In that attachment, under 'Format: Show:' you select to show 'User' instead of 'fields', using the same view mode that is shown for the normal profile.


You should force user registration before checkout and allow Drupal to handle this. There are a couple of things you can do to make it very tough for non-humans to get through:

Require user verification for registration. This is out of the box functionality with Drupal and is accessible in the system configuration area.
Consider using a module such as Captcha or Honeypot to expose traps for bots so that they cannot continue.

Don't work against Drupal's user and form system on this one. Let them do the work for you.


Passing a node refernce id to a form via hook_form_alter()

ok, figured this out incase anyone is interested, may only work for my use case but perhaps it will help someone else.

function mymodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "rating_node_form")
    {
        // dont require title
        $form['title']['required'] = FALSE;
        // validate
        $form['#validate'][] = 'mymodule_form_validate';
        // call after form is built
        $form['#after_build'][] = 'mymodule_after_build';
    }
}

function mymodule_after_build($form, &$form_state) {
       //set the nid to the argument of the nide you are viewing
       $form['field_bar_name']['und']['nid']['#value'][0] = arg(1);
       //set the default value
       $form['field_bar_name']['und'][0]['nid']['#default_value'] = arg(1);
       //set form value
       $form['field_bar_name']['und'][0]['nid']['#value'] = arg(1);
       return $form;
}


After a long a research and development, I came to an conclusion that this could be the answer:

foreach ($view->result as $result) {
  $result->_entity->set('field_name', array(0 => 'value'));
}


How do I get the number of rows selected from the query?

Use $query->countQuery()->execute()->fetchField(); This is fast.

See detail example.

$number = $this->connection->select(static::TABLE_NAME, 'f')
    ->condition('event', $name)
    ->condition('identifier', $identifier)
    ->condition('timestamp', REQUEST_TIME - $window, '>')
    ->countQuery()
    ->execute()
    ->fetchField();


Using select list with Views exposed filter when it is a custom schema through hook_views_data

Unfortunately for me the project is too far gone to create the underlying design with entities, which seems to be the only way that I'm going to achieve that, so instead I am going to be using AJAX like forms which hopefully (in time) will output into Views (to save time and hopefully provide some flexibility). So for now I'm building Panels with blocks that I'm creating programmatically and then using drupal_get_form('mymodule_mainform') to add the content of those blocks with forms designed in different functions in my modules.
For that I'm using the Example module's 'block_example' module (block_example.module code pasted at the bottom here - find and replace 'block_example' with your module name if you want to paste it straight into your own .module file, remember though that you can't duplicate hooks, so copy the contents into any pre-existing functions or hooks with the same name).
To help out other people I've included the links that helped me here (may you have better luck!) "joshaust.in"'s .pdf was a brilliant explanation...
For conceptual understanding: http://joshaust.in/wp-content/uploads/2012/06/Entities-and-Bundles-in-Drupal-7.pdf
http://joshaust.in/2012/06/entities-and-bundles-in-drupal-7/
For attaching fields to your entity programmatically:
How to attach a field to an entity programmatically?
For programmatically creating your entities: http://www.phase2technology.com/blog/programmatically-creating-entities/
http://www.trellon.com/content/blog/creating-own-entities-entity-api
block_example.module
/**
 * Implements hook_menu().
 *
 * Provides a default page to explain what this module does.
 */
function block_example_menu() {
  $items['examples/block_example'] = array(
    'page callback' => 'block_example_page',
    'access callback' => TRUE,
    'title' => 'Block Example',
  );
  return $items;
}

/**
 * Simple page function to explain what the block example is about.
 */
function block_example_page() {
  $page = array(
    '#type' => 'markup',
    '#markup' => t('The Block Example provides two sample blocks which demonstrate the various block APIs.
            To experiment with the blocks, enable and configure them on the block admin page.', array('@url' => url('admin/structure/block'))),
  );
  return $page;
}
/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function block_example_block_info() {
  // This hook returns an array, each component of which is an array of block
  // information. The array keys are the 'delta' values used in other block
  // hooks.

  // The required block information is a block description, which is shown
  // to the site administrator in the list of possible blocks. You can also
  // provide initial settings for block weight, status, etc.

  // Many options are defined in hook_block_info():
  $blocks['example_configurable_text'] = array(
    // info: The name of the block.
    'info' => t('Example: configurable text string'),
    // Block caching options (per role, per user, etc.)
    'cache' => DRUPAL_CACHE_PER_ROLE, // default
  );

  // This sample shows how to provide default settings. In this case we'll
  // enable the block in the first sidebar and make it visible only on
  // 'node/*' pages. See the hook_block_info() documentation for these.
  $blocks['example_empty'] = array(
    'info' => t('Example: empty block'),
    'status' => TRUE,
    'region' => 'sidebar_first',  // Not usually provided.
    'visibility' => BLOCK_VISIBILITY_LISTED,  // Not usually provided.
    'pages' => 'node/*', // Not usually provided here.
  );

  $blocks['example_uppercase'] = array(
    // info: The name of the block.
    'info' => t('Example: uppercase this please'),
    'status' => TRUE,
    'region' => 'sidebar_first',  // Not usually provided.
  );

  return $blocks;
}

/**
 * Implements hook_block_configure().
 *
 * This hook declares configuration options for blocks provided by this module.
 */
function block_example_block_configure($delta = '') {
  // The $delta parameter tells us which block is being configured.
  // In this example, we'll allow the administrator to customize
  // the text of the 'configurable text string' block defined in this module.

  $form = array();
  if ($delta == 'example_configurable_text') {
    // All we need to provide is the specific configuration options for our
    // block. Drupal will take care of the standard block configuration options
    // (block title, page visibility, etc.) and the save button.
    $form['block_example_string'] = array(
      '#type' => 'textfield',
      '#title' => t('Block contents'),
      '#size' => 60,
      '#description' => t('This text will appear in the example block.'),
      '#default_value' => variable_get('block_example_string',  t('Some example content.')),
    );
  }
  return $form;
}

/**
 * Implements hook_block_save().
 *
 * This hook declares how the configured options for a block
 * provided by this module are saved.
 */
function block_example_block_save($delta = '', $edit = array()) {
  // We need to save settings from the configuration form.
  // We need to check $delta to make sure we are saving the right block.
  if ($delta == 'example_configurable_text') {
    // Have Drupal save the string to the database.
    variable_set('block_example_string', $edit['block_example_string']);
  }
  return;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function block_example_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'example_configurable_text':
      // The subject is displayed at the top of the block. Note that it
      // should be passed through t() for translation. The title configured
      // for the block using Drupal UI supercedes this one.
      $block['subject'] = t('Title of first block (example_configurable_text)');
      // The content of the block is typically generated by calling a custom
      // function.
      $block['content'] = block_example_contents($delta);
      break;
    case 'example_empty':
      $block['subject'] = t('Title of second block (example_empty)');
      $block['content'] = block_example_contents($delta);
      break;
    case 'example_uppercase':
      $block['subject'] = t("uppercase this please");
      $block['content'] = t("This block's title will be changed to uppercase. Any other block with 'uppercase' in the subject or title will also be altered. If you change this block's title through the UI to omit the word 'uppercase', it will still be altered to uppercase as the subject key has not been changed.");
      break;
  }
  return $block;
}

/**
 * A module-defined block content function.
 */
function block_example_contents($which_block) {
  switch ($which_block) {
    case 'example_configurable_text':
      // Modules would typically perform some database queries to fetch the
      // content for their blocks. Here, we'll just use the variable set in the
      // block configuration or, if none has set, a default value.
      // Block content can be returned in two formats: renderable arrays
      // (as here) are preferred though a simple string will work as well.
      // Block content created through the UI defaults to a string.
      return array('#markup' => variable_get('block_example_string',  t('A default value. This block was created at %time', array('%time' => date('c')))));
    case 'example_empty':
      // It is possible that a block not have any content, since it is
      // probably dynamically constructed. In this case, Drupal will not display
      // the block at all. This block will not be displayed.
      return;
  }
}

/*
 * The following hooks can be used to alter blocks
 * provided by your own or other modules.
 */

/**
 * Implements hook_block_list_alter().
 *
 * This hook allows you to add, remove or modify blocks in the block list. The
 * block list contains the block definitions. This example requires
 * search module and the search block enabled
 * to see how this hook implementation works.
 *
 * You may also be interested in hook_block_info_alter(), which allows changes
 * to the behavior of blocks.
 */
function block_example_block_list_alter(&$blocks) {
  // We are going to make the search block sticky on bottom of regions. For
  // this example, we will modify the block list and append the search block at
  // the end of the list, so even if the administrator configures the block to
  // be on the top of the region, it will demote to bottom again.
  foreach ($blocks as $bid => $block) {
    if (($block->module == 'search') && ($block->delta == 'form')) {
      // Remove the block from the list and append to the end.
      unset($blocks[$bid]);
      $blocks[$bid] = $block;
      break;
    }
  }
}

/**
 * Implements hook_block_view_alter().
 *
 * This hook allows you to modify the output of any block in the system.
 *
 * In addition, instead of hook_block_view_alter(), which is called for all
 * blocks, you can also use hook_block_view_MODULE_DELTA_alter() to alter a
 * specific block. To change only our block using
 * hook_block_view_MODULE_DELTA_alter, we would use the function:
 * block_example_block_view_block_example_example_configurable_text_alter()
 *
 * We are going to uppercase the subject (the title of the block as shown to the
 * user) of any block if the string "uppercase" appears in the block title or
 * subject. Default block titles are set programmatically in the subject key;
 * titles created through the UI are saved in the title key. This module creates
 * an example block to demonstrate this effect (default title set
 * programmatically as subject).  You can also demonstrate the effect of this
 * hook by creating a new block whose title has the string 'uppercase' in it
 * (set as title through the UI).
 */
function block_example_block_view_alter(&$data, $block) {
  // We'll search for the string 'uppercase'.
  if ((!empty($block->title) && stristr($block->title, 'uppercase')) || (!empty($data['subject']) && stristr($data['subject'], 'uppercase'))) {
    // This will uppercase the default title.
    $data['subject'] = isset($data['subject']) ? drupal_strtoupper($data['subject']) : '';
    // This will uppercase a title set in the UI.
    $block->title = isset($block->title) ? drupal_strtoupper($block->title) : '';
  }
}


If you're using Views, you could try the Views PDF module.

  With this module you can output a view as a PDF document. Each field
  of the view can be placed on the PDF page directly in the
  administration interface. Therefore a new display called "PDF" is
  added.

Or perhaps the Print module if you're just creating a PDF from a node.

  This module allows you to generate the following printer-friendly
  versions of any node:

  Printer-friendly version (webpage format) (at
  www.example.com/print/nid)
  PDF version (at
  www.example.com/printpdf/nid)
  Send by email (at
  www.example.com/printmail/nid)

Edit:

If you're willing to do a little legwork, you can use the Data module to expose your non-Drupal table to Views, and then use the previously mentions Views PDF


Is it possible for two drupal views to share the same pager limit

If you want to create the blocks yourself, eg, not just via the Block UI and Views, you can hack it together with using various hooks available within Views.

First out the door, I could see using Views' standard block for the now View, but in the next block,  using views_get_view_result() to look at the results of the now View and depending upon its result, eg, how many results there are, changing the pager of the next View to be whatever you want, in this case 1 or 2.

Note that this of course entails running the now View queries twice, so you could create custom blocks containing both Views and statically save the information to be shared across the Page but that introduces other ugliness.

And then if any of these Views are cached, another set of issues crops up.

So, as @molot has mentioned in comments, there is a bunch to think about here.


Can not access to the nth product's variation ( n > 1) programmatically

Basically, I wanted to get attributes attached to the current variation. According to Bojanz' answer: https://www.drupal.org/node/2893842#comment-12163314, there was no need to use $gift->variations. Bojanz corrected and told me $item->getPurchasedEntity() is the product variation, not the product

So the code would be:

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form['#order_entity'] = $this->order;

    $order_items = $this->order->getItems();
    /** @var \Drupal\commerce_order\Entity\OrderItem $item */
    $item = $order_items[count($order_items) - 1]; // the last item added to the order
    /** @var \Drupal\commerce_product\Entity\ProductVariation $gift */
    $gift = $item->getPurchasedEntity();
    $attribute = $gift->getAttributeValue('attribute_gift_type');
  }


Can You Render Data from Forced Fields in Views While Using format "Show: Content"

Yes, you have to decide whether you want to render Content or Fields. Those are two different concepts in Views. The first renders the entity template in the selected view mode and you configure the fields in the content type. The second renders Views field plugins which you configure in Views UI.

You can approach the issue from both sides:

Show: Content | View Mode

If you start with a View showing content, in the view mode you've selected, display a field for a second View dispay of the same entity. In the second View display select Show: Fields.

You need a module to add the View field to the content type, for example  EVA: Entity Views Attachment or Views Reference Field.

Show: Fields | Settings

Or start with showing fields,  add a field for the rendered entity

and select a view mode, which you then can configure, preprocess and theme like a normal node template.


How to save current User Points as field at moment of adding a node?

Simply add one more field to the Stuff content type and use Computed Field module for adding that field.Since field is on content type so its value will be added while adding the node with the value of user points user will have while creating it,afterwards it will be same or depends on php code computing value for this field.

  Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of fields. So start cooking up your PHP based values!


Display related content in view by entity reference in views drupal 7

I think you could use

Corresponding Entity References for Drupal 7

That way, current node will reference all nodes that reference it - and from this point creating a view is trivial - or you can simply display the field created for back reference, without need for a views module at all.

Other way is to use Views. Create a view displaying nodes from content type A, add argument content reference field > provide default argument > node ID from URL and display this block view on the nodes from content type B.


Possible to use PDO inside a custom module in Drupal 6?

You definitely could (Drupal is just a a PHP application, nothing special in that respect). But you'd lose support for stuff like table prefixing.
If you're looking to use PDO, and stay within the bounds of normal Drupal practices, you should install the DBTNG module:

This is a backport of the Drupal 7 PDO database compatibility layer for use with Drupal 6 modules.
...
This module does not override the existing database functionality but makes the new compatibility layer available under a series of functions identical to their Drupal 7 counterparts named dbtng_ instead of db_. For example with this module, use dbtng_set_active instead of db_set_active, with the exception of the following functions that funciton identically to their Drupal 7 conterparts: db_insert, db_merge, db_update, db_delete, db_truncate, db_select, db_transaction, db_close, db_condition, db_xor, db_and, db_or, db_next_id, and db_like.

That should let you write code that won't need to be changed for Drupal 7 and 8 (unless table/field names change of course).


Add extra obligatory fields when editing a node as anonymous user

You could use a the hook_form_alter to get the desired function:

function mymodule_form_alter(&$form, &$form_state) {
  if($form['type']['#value'] == 'DESIRED_CONTENT_TYPE') {
    if( user_is_anonymous() ){
      //Fields are required for anonymous users
      $form['field_ABC'][LANGUAGE_NONE]['0']['value']['#required'] = TRUE;
      $form['field_DEF'][LANGUAGE_NONE]['0']['value']['#required'] = TRUE;
    }
    else{
      //Hide fields for logged in users
      $form['field_ABC']['#access'] = FALSE;
      $form['field_DEF']['#access'] = FALSE;
    }
  }
}


The return path from path_to_theme() doesn't have a slash at the front of it and so becomes relative to the path you're currently at. That would probably explain why it works for pages in the root of your site, but not those that are at least one directory down.

You should be able to fix it easily by adding a forward slash to the start of the image path:

<img src="/<?php print path_to_theme(); ?>/images/brand_icons.gif" alt="" />

On another note, make sure you fill the alt in...people with screenreaders will thank you for it :)


Is it possible to set block weight inside template?

Block weight is stored in the database. There are functions to change their weight, but templates aren't the place for manipulating database data, that's where you write the HTML out.

If you want to display context blocks in a different order from the blocks in the system UI, use the "Show row weights" link to set a value that's higher/lower than the value in block admin UI.


How to exclude a custom 404 error page (not found) from a Popular Content block?

Option 1: Use the CustomError module

The CustomError module allows a site administrator to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them. Some more details about its features (from its project page):

  Configurable page title and descriptions.
  There are no author and date/time headers as with normal nodes.
  Any HTML formatted text can be be put in the page body.
  The error pages are themable.
  Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
  Allows custom redirects for 404s.

What you should be most interested in, is this part from that project page:

  Since the error pages are not real nodes, they do not have a specific content type, and will not show up in node listings, or in a Popular Content block.

Option 2: Tune the View that creates the block

Edit the View that actually creates the Popular Content Block like so:

Use the "Add" link to add an extra condition within "Filter Criteria".
The extra condition could be either of these:

"Content: nid", using "Is not equal to" as operator, and with "value" the node id for your 404 page.
"Content type" is different from "Content type ABC", whereras you first created such Content type ABC to create pages such as the custom 404 page (which automatically also covers other similar pages you want to always be excluded also).

Bonus: Also for 403 variations

Either option above can be used in case of a similar question related to 403 errors (Forbidden, or "Access Denied").


How to overcome a database error on field deletion

I tried manually adding a column with the missing name to the table in question.  Now a cron run spits out a series of 20 sets of error messages like this:

Notice: Undefined property: stdClass::$fid in file_usage_list() (line 649 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$status in file_field_delete_file() (line 363 of /path/to/drupal/modules/file/file.field.inc).
Notice: Undefined property: stdClass::$fid in file_usage_delete() (line 728 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1273 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1274 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1278 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1280 of /path/to/drupal/includes/file.inc).
The specified file could not be deleted, because it is not a valid URI. More information is available in the system log.

At the same time I notice the number of rows in my various deleted_data tables seems to decrease by 10 with each run.  Deleting a field likewise triggers 20 errors and a decrease in the number of rows in the deleted_data tables.

I'm hoping that this has been the fix.  It makes sense that it can't delete the files as they come in via a migration, and I've started bringing the files in on  a different field, so I rolled back and imported.  I'll update this once cron has run enough times that I can see if my deleted data logjam has cleared and fields can be deleted again.

UPDATE: It seems like there was a tremendous amount of backlog building up behind this database error.  I set a system cron job to trigger drupal cron once a minute (dev site, so no performance concerns) and over the course of many hours, the rows in the deleted_data and deleted_revision tables have started to go away, followed by the tables themselves.  A few empty tables and one with three rows in it remain, and I'm not sure if they will eventually be cleared, or if they aren't in whatever queue is being run through.  If someone knows how to check what tasks drupal has queued up to run in the background, please do comment and let me know.

IN CONCLUSION: In this particular case, where the system was trying to make a selection and not finding the column it expected to find, it seems like the only possible solution was to add the column in, so the select would return 0 rows instead of an error that stopped things from moving on.  I'm not sure what caused the discrepancy between expected columns and actual database schema, but I suspect it has something to do with an earlier struggle to get the media module working for me, that involved switching back and forth between the 7.1.x and 7.2.x branches of that module.  Somewhere along the way I think drupal lost track of what version was currently installed, and stopped being able to properly run the right database upgrades on install and update.  I'll read up some more on how to check if this is something I need to address, but if you've had a similar experience, that may be a place to start on debugging the source of your woes.


You can add this feature using the FileField Sources module. This module adds FTP (and more) upload to any FileField upload field, including the Video FileField upload field.


If manual steps are OK you can use this workaround:

The pathauto module always generates aliases using the first matching pattern type/condition combo. So simply create two matching patterns for your nodes. Generate URLs using the first pattern, deactivate this pattern and rerun URL alias generation (which now automatically uses the 2nd matching pattern).


All available variables returning node ID in views php in drupal 7

Start with print_r to see what's available:

<pre>
<?php print_r($data); ?>
</pre>

You will likely end up using $data, something like:

$data->_field_data['nid']['entity']->field_facebook_page['und'][0]['value']

If that doesn't work, take a look at
http://drupal.org/node/1140896#comment-5945164


Book page fields inherit content from parent

The solution was fairly simple after all.
I created two content types and used a field with Entity Reference to pass the values from the first content type to the second one.


Using RegEx with Rules to compare email addresses

You can use access rules which is built into core drupal.

Go to "/admin/user/rules" and add a new rule, for example %@domain.com, this will allow anyone to register who has that specific domain.


"Page Not Found" error when a google search form is submitted

Instead of using q, you can use as_q. The description given from the page I linked is the following:

  The as_q parameter provides search terms to check for in a document. This parameter is also commonly used to allow users to specify additional terms to search for within a set of search results.


Does node_delete() delete node_revision and comment as well?

Little more context on this one since I had to answer this myself recently. The node.module code starts the delete operation by invoking all HOOK_node_delete functions it is aware of:

  foreach ($nodes as $nid => $node) {
    // Call the node-specific callback (if any):
    node_invoke($node, 'delete');
    module_invoke_all('node_delete', $node);
    module_invoke_all('entity_delete', $node, 'node');
    field_attach_delete('node', $node);

    // Remove this node from the search index if needed.
    // This code is implemented in node module rather than in search module,
    // because node module is implementing search module's API, not the other
    // way around.
    if (module_exists('search')) {
      search_reindex($nid, 'node');
    }
  }

One of which is the comment_node_delete() function in comment.module (clearing comments):

/**
 * Implements hook_node_delete().
 */
function comment_node_delete($node) {
  $cids = db_query('SELECT cid FROM {comment} WHERE nid = :nid', array(':nid' => $node->nid))->fetchCol();
  comment_delete_multiple($cids);
  db_delete('node_comment_statistics')
    ->condition('nid', $node->nid)
    ->execute();
}

After it has finished with the modules that have references to these nodes, it then clears its own node tables for the NID:

  // Delete after calling hooks so that they can query node tables as needed.
  db_delete('node')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('node_revision')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('history')
    ->condition('nid', $nids, 'IN')
    ->execute();
  db_delete('node_access')
   ->condition('nid', $nids, 'IN')
   ->execute();

So - yes, node_delete clears both comments and revisions, as well as other node data and references.


How do I list all nodes created by the same author on a (custom) profile page?

I think this might be the solution

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


You don't need any coding to achieve this functionality, you can just go with Commerce and using Drupal's built-in roles, manage who has the permission to create content (items to sell) and who has the permission to buy it.

for the search aspect of it, I suggest trying Search API, which gives you facet like filtering feature (Like ebay), also you might wanna check Apache Solr for faster indexing


How to track the published/unpublished status for node revisions?

Try this hope it helps.

First create a Views page

Second add the fields you want to display based on your node. Add relationship 'author' so that you can add a user:name which is related to the author of the node.

Third change your use pager to 'page by date'. Next add a contextual filter Date: date(node). After adding do this.

And your output should be like this.

Additional, you can add exposed filter date so that you can filter on what month you want to check.

Hope this helps you in your problem.


Unset the "please wait" in drupal commerce

A simple way could be to hide it with CSS, but what is displayed by Drupal is actually configurable. The throbber with the Please wait... message is the default behavior but you can change it to a number of things. What you need to look at is the #ajax['progress'] attribute.

Usually #ajax['progress'] is not set in the form, and Drupal will add the default throbber with the Please wait... message in the JavaScript that handle the ajax request. The solution it quite simple, all you need to do is to set it like this:

$form['element']['#ajax']['progress'] = array('type' => 'throbber');

It will kill the message and only show the throbber. There are a number of ways to configure what Drupal does to show the user progress - you can read all about it in the link above.


Adding assets (css/js) for a custom module block (and withstanding a cache enabled install)

Modules can report how Drupal should cache the output of a module, through the use of a set of constants.

The constants should be used as in the following example of hook_block():

function mymodule_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array(
      'info' => t('Mymodule block #1 shows ...'),
      'weight' => 0,
      'status' => 1,
      'region' => 'left',
    );
    // BLOCK_CACHE_PER_ROLE will be assumed for block 0.

    $blocks[1] = array(
      'info' => t('Mymodule block #2 describes ...'),
      'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE,
    );

    return $blocks;
  }
  // …
}

The constants that can be used are:

BLOCK_NO_CACHE: The block should not be cached.
BLOCK_CACHE_GLOBAL: The block is the same for every user, in every page it is shown.
BLOCK_CACHE_PER_ROLE: The block could change basing on the roles the user who is watching the page has.
BLOCK_CACHE_PER_USER: The block could change basing on the user who is watching the page.
BLOCK_CACHE_PER_PAGE: The block could change basing on the page being viewed.

You could use some of the constants together; for example, if the block changes basing on the page, and the user who is watching the page, you can use BLOCK_CACHE_PER_PAGE|BLOCK_CACHE_PER_USER.

In Drupal 7, those constants have been renamed, and a new constant is added; this is the list of the constants used in Drupal 7:

DRUPAL_NO_CACHE
DRUPAL_CACHE_GLOBAL
DRUPAL_CACHE_PER_ROLE
DRUPAL_CACHE_PER_USER
DRUPAL_CACHE_PER_PAGE
DRUPAL_CACHE_CUSTOM

The last constant is used to report to Drupal 7 that the module uses its own cache. For Drupal it has the same effect of using DRUPAL_NO_CACHE.


How to expose edit link on editable areas for all authorized users?

There are two ways to do this.

The "gears" feature is from the "Use contextual links" permission on admin/people/permissions.  If you give that to the appropriate roles, your users should see that.

Personally, I don't like the Contextual Links feature, mainly because the markup it adds can mess with theme layout when you have other positioning going on. I typically add in my own edit links to pages, usually below the content somewhere. I will sometimes use a display: none on them, and then have a link in the footer menu that shows them all via jQuery.


Tips for Information Structure & Superfish Menu

You can always rebuild the menu, so I would just start adding content and organizing the links.  The main advantage of a CMS like Drupal is that you are not "locked in" to a specific configuration and you can always change it around freely at any time.

One thing to be careful about is that the deeper your navigation structure, the harder it is for users (particularly older users and those not skilled in using mouse, etc. as well as those on mobile devices) to use the menus, but this is something you can only find out once you actually build the menus and do usability tests.

As you note, you will need to first create the parent pages before you can add links underneath them to the child pages.


In my case using hook_menu will never work. Then i have to use hook_menu_local_tasks_alter to make it work.
Here is how.

function manage_child_menu_local_tasks_alter(&$data, $router_item, $root_path) {
   if ((arg(0) == 'node' || arg(0) == 'groups') && arg(2) == '') {
   $nid = arg(1);
   $node = node_load($nid);
   if ($node->type == 'project_auction') {
     $link = menu_get_item("node/$nid/demo");
     $link['title'] = 'Auction List';
     $link['weight'] = 10;

     $data['tabs'][0]['output'][] = array(
       '#theme' => 'menu_local_task',
       '#link' => $link,
     );

     $data['tabs'][0]['count'] = $data['tabs']['0']['count'] + 1;
  }
 }
}


What are possible alternatives for Admin:Hover, which suffers a major security issue?

There are several other modules that do this (quotes are from the project pages of these modules, where available):

Contextual Links (Backport of contextual.module in Drupal 7):

Hover over nodes, blocks, and views blocks to expose styled edit/configure/delete tabs.

Admin links

Block edit

... provides inline (on mouseover) editing capability for any block or node.

Administer Tooltip

... adds little icons to all entities (node, block, view, user) which are visible on mouseover ...


Running unit test only for my custom module

Sure, all you need to do is provide a path/file to phpunit and it will be limited to that.

vendor/bin/phpunit -c core modules/custom


How to alter single custom field value in views?

function hook_views_pre_render(&$view) {

  switch ($view->name) {
    case 'YOUR_VIEW_NAME':
      //  override the global custom text field value
      $view->field['nothing']->options['alter']['text'] = 'My custom text';
    break;
  }
}

Check the link for more details
How to insert values into Global custom text field of views programmatically?

add nid as field in view and use that field for condition
you can add condition as follows: if ($nid == '124') {  $view->field['nothing']->options['alter']['text'] = $nid}

Simple way is to create a new field field_waga which will have field_waga_1 as new name if you check in the view and then you can change the label and override that field with your custom value

if($view->result[0]->field_waga[0]['raw']['value'] == '10') {
//here you can create the field to act as custom text field and enter the custom //value
$view->result[0]->field_waga_1[0]['#markup'] = 'alter';
}


This is plain awfull and totally undocumented. But I found out:

# creates a date field for the valid_from/to migration mapping
$current_row->valid_from = array(
  'from' => (string) $current_row->valid_from,
  'to' => (string) $current_row->valid_to,
  //'timezone' => DateMigrateFieldHandler::arguments('Europe/Berlin'),
  //'timezone_db' => DateMigrateFieldHandler::arguments('Europe/Berlin'),
  //'date_type' => 'datetime',
);

Two issues with the code above are solved:

The array containing the dates has to contain the fiels from and to. Otherwise it does not understand the date range. I've seen this in the date migration example but never thought the field names are important for the mapping. (I rather used the target names value and value2.)
The array should not contain information about timezone and date types. The DateMigrateFieldHandler::prepare() will do that for you.

The working code above yields:

[field_date] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => 1970-02-01 00:00:00
                        [value2] => 2013-12-31 00:00:00
                        [timezone] => Europe/Berlin
                        [timezone_db] => Europe/Berlin
                        [date_type] => datetime
                    )
            )
    )

Fixed. :)


I need help with an existing variable of drupal

The "Database log messages to keep" tells the site how many entries to store in "Recent Log Messages" (/admin/reports/dblog). It stores a record of watchdog events and php warning/errors, etc.

The limit is stored in the variable table, under the variable name of dblog_row_limit.


I believe the image block module is not yet fully compatible with i18n module and you will need to apply the patch in this issue which according to the posters is reviewed and ready to be committed.

Alternatively you can install nodeblock and create a content type (i.e. block) and use it as a nodeblock and you will get all the benefits of nodes and blocks.  Therefore you can add image fields or any other fields that you need and after creating a node of that content type you will be able to add it in a region of your theme like a normal block. Nodeblock supports translatable content (Contrent translation with i18n and Entity Translation).


Page Content Type: Displaying error in Preview mode

The error is about accessing field_dark_theme from an un-existing node instance. The proper way of loading the node during preview is explained here.

On the other hand, welcome to the wonderful world of PHP for debugging properly (on Drupal), please check this post and this documentation entry check your proper IDE/stack on how to setup debugging tools.


zoom and centre gmap output based on results (views+gmap+location modules)

I just noticed someone talking about the macro behaviour for autozoom. I added behavior=+autozoom to my [gmap] macro in the Gmap views settings and the few tests I have done so far suggest it works


How do you theme an autocomplete dropdown

To theme the Drupal 7 finder autocomplete dropdown take a look at this video. Generally you write PHP into the 'Rewrite' settings on the advanced options of the finder. I would avoid using the theme() function, it might be obsolete.

To theme the Drupal 6 finder version, you may find this article helpful. It uses theme functions.


Here are a couple of ideas for you:

1) If there aren't too many nodes with assets - you could remove the contextual filter and create an "Or" Filter Group in the regular filter section of the view (based on NID). Then just list all of the NID's you want to filter by (NID 15 Or NID 47 Or NID153). That should pull in all of the assets from each of the Nodes without having to change the view much.

2) If you tagged the nodes containing the assets with taxonomy terms - you should also be able to use a regular taxonomy term filter instead of the contextual filter. I think in that case you would just need to add a Content: Taxonomy terms on node relationship to the view. That should open up a bunch of new taxonomy filter options in the regular filter section of views. You could then filter by term id or name.

You would just have to make sure you apply the Content: Taxonomy terms on node relationship to the term id filter when you set it up.


Drush is not recognizing Acquia extension

Can you confirm that you can see your acquia site aliases?

drush sa

I haven't done anything beyond the suggested tar -C $HOME -xf $HOME/Downloads/acquiacloud.tar.gz and drush help --filter=acapi shows all the commands.


It was my mistake. I was using another module, which provided page callback with higher priority. For the next time - it's advisable to install devel module and go to devel/menu/item?path=<uri> where used page callback can be clearly seen.


how do I change the url based on a theme?

Normally, you could accomplish this with URL rewrite rules or theme switching modules like ThemeKey but you're moving to a different sub-domain which Drupal is going to assume is a new database. The best way to do this then is to use the Domain Access module to simulate the use of a sub-domain without switching your database.

Domain Access is a little trickier to setup (read the install file carefully) but it allows separate themes for each subdomain with the "Domain Theme" module.

  Domain Theme -- Allows separate themes, theme settings and colors for
  each subdomain.


Trigger a module function after a node is saved or updated successfully in the database

You may be able to use Hook Post Action and then use this hook:

function my_module_node_postinsert($node) {
  if(!$node->type == 'article' || !$node->type == 'page' )
      return;
  my_module_do_index($node) ; // indexes the node
}

Give it a try and see if it helps!

The project link: https://www.drupal.org/project/hook_post_action


This is a question I make myself when facing new projects, Field Collection vs Entity Reference + custom entity or if the structure is simple, Field Collection vs custom field with several db columns / Multifield. Here's my opinion based in my experience.

Multifield is a great concept, it'd be a "lightweight" version of field collection, instead of creating an entity structure with relationships, it covers the simple use cases without creating the entity. It has a number of issues, though, such as not complete Features integration, not really multilingual etc (so if you plan to use this, contributions will be probably really welcome).

Field Collection is a great solution if you're doing a site that can be done just with a few tweaks here and there, it gives site builders a powerful tool to create complex structures without worrying much about the internals. It will basically create an entity that relates with the "host" entity by the ids, allowing to add fields to it and everything.
The disadvantages would come in the knowledge of the internals of Field collection that you need to perform complex operations such as managing a Field Collection with an Entity Reference on it, or migrate data. As it is a generic tool, it'd be fairly complicated to go one step beyond.

Another option you've got there is using ECK with Entity Reference, but my experience with this has been a disaster so far, I find it way easier to create the entity type by code without the helper.

It's a matter of what you need and what's the best fit for your project, if you've got the time and the developers to create entity types that relate with your data model through Entity Reference, you'll have more control over what's happening with your data structures, but then you're the "responsible" for that too.

After testing a while with all the solutions describe above, in my team we always go for the entity types + ER, but I can see that for small projects, without data migration or a complicated i18n setup, Field Collection is just the fastest way to go.


No, unfortunately there isn't.  If you look at the views_view and views_display tables in the Drupal database, that information simply isn't stored.

I even checked whether you can get to info like that if you're using the Features module with views, but even that only lets you know if a view has been updated since your last created feature, but gives no information about the date of any changes...


How to create a render array for a location CCK field?

Ah, ..in my node.tpl.php

// address here
$fvf = field_view_field('node', $node, 'field_location', array(
    'type'=>'location_default')
);
print render($fvf);

// google map here
print render($content['field_location']);

Great article: http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

pfew,
*-pike


Recommendation for modules/workflow to build a premium link directory

I'm building a site with free and paid memberships now; my use case isn't exactly the same but I'll share what I can.

I'm not using Drupal Commerce; in my case, users make a payment with PayPal and then I manually add a paid role to each account.  I intend to eventually set this up in Drupal Commerce but I haven't had the time yet.

When I add the paid role, a rule is triggered that automatically sets an expiration date using the Role Expire module.  Until very recently the 7.x rules integration was bugged but I am happy to report that it is now fixed and works great.

As for working with Commerce, Randy Fay also did a screencast on setting up content access for a membership site.  I'm not sure if the content access part is relevant but the final part of the screencast covers:

  Create a product representing the premium role.
  Create a rule that grants the premium role on order completion:

  After updating an order
  If the order state is Completed
  And the order contains our premium product
  Add a role to the user who is the owner of the order


Commerce Kickstart: How To Add Sort Fields To Search API?

For other travelers, the answer is that it's a bug with a patch that has not been made part of the official distribution as of 26 Sep 2014. See #6 for the patch.

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


Not familiar with charts, but in views SORT you could try using the opposite.

Ex: Sort Descending instead of Ascending. (so it reverses the order).

Then all you would have to do is override the pager so it says previous instead of next. I found some documentation here.


"Redirect to URL" means that when the action is executed the user will be taken to the specified URL.

This action does exist in Drupal 7 and Drupal 6 as well.


Views Filter with Checkbox and Searchfield

What I've found so far is the Module Composite Views Filter, which does quite the thing. You can display a filter on selection of dropdown. But not programatically. You have to fill your dropdown yourself.Not quite what I was looking for, but better than nothing.


Do a render foreach loop on a regular field?

$field_values = element_children($fields['field1']);
foreach($field_values as $field_value) { ... }

I was looking for the answer to this too, and ended up hunting through the render() function. It wasn't too far down the chain: drupal_render() calls element_children().

  element_children

  Identifies the children of an element array, optionally sorted by weight.

  The children of a element array are those key/value pairs whose key does not start with a '#'. See drupal_render() for details.


I have a script that need to place after closing tag after of body?

Adding a <script> tag (or any tag except a comment) outside <head> or <body> is invalid HTML. Drupal doesn't want to help you to produce invalid HTML, so it contains nothing that would help you to do this.

I would examine your motivation for doing this, and reconsider whether you want to produce a valid or invalid document. If you really want to go down the invalid route, then you may as well just edit your theme's html.tpl.php file and stick the script at the bottom, as you won't find any API methods that can be used to do it for you.

FYI, IE10+ will ignore the script altogether, Chrome and FF will honour it for now, but may not in the future, other browsers/versions will probably do various other things.


This question is quite old but here a solution

/**
 * Implements template_preprocess_form_element().
 */
function mytheme_preprocess_input(&$variables) {
  // remove size
  unset($variables['element']['#size'], $variables['element']['#attributes']['size'], $variables['attributes']['size']);
}


Can I have a GROUP BY as an expression? Without an alias

This can be achieved like so:

$select = db_select('my_values', 'v')
  ->condition('datetime', '2012-12-15 00:00:00', '>')
  ->condition('datetime', '2013-01-01 00:00:00', '<')
  ->orderBy('datetime', 'DESC');
$select->addExpression('FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*60)', 'datetime');
$select->addExpression('ROUND(MAX(value), 2)', 'value');

$groupBy = &$select->getGroupBy();
$groupBy['gb'] = 'ROUND(UNIX_TIMESTAMP(datetime)/60)';

$result = $select->execute();

Which creates this query:

SELECT FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*60) AS datetime,
ROUND(MAX(value), 2) AS value
FROM my_values v
WHERE (datetime > '2012-12-15 00:00:00') AND (datetime < '2013-01-01 00:00:00')
GROUP BY ROUND(UNIX_TIMESTAMP(datetime)/60)
ORDER BY datetime DESC


What are the implications of duplicate content issues with Drupal comments?

After investigating, I don't think there's an SEO problem here. It's an annoyance for sure but it's not a problem and here's why:

As per Google's recommendations here http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html on canonical URLs and duplicate content, you will not have any problems if you have duplicate content only if you properly specify your canonical URLs. Also, Google (and most probably all other search engines) will only display the canonical URL in search results and not the other URLs.

In Drupal's case, the canonical URLs are properly set. For example, I have created a test article (node/2) and added comments and replies to it and got the following pages:

/node/2
/comment/2
/comment/3

After inspecting their generated source code, they all have the same <link rel="canonical" href="/node/2" /> in their source code properly created. So basically only the main article page will display in the search results.

Now, whether to modify core to only generate a single page or to have the robots.txt file patched as you specified is beyond me. I'm sure there will be lots of considerations and special cases to consider before implementing any of the above and since there really isn't a problem maybe it's best to keep things as is.

Cheers!

Note: I'm using Drupal 7.17 (latest version as of today).


Using menus anywhere on page - how to stop them expanding by default when not used in menu region ( e.g. in a block or panel)?

The solution I chose in the end was to hand-code a drop down, based on the HTML markup output by a Views Exposed Filter form that I am already using (this also means that the look and feel is consistent).

So I created a block in the usual way and added the code shown below, and then in my 2-column minipanel added this block to the 2nd column and then added my minipanel to the panel page. The other column, 1st, of the columns contains the views exposed filter as discussed. See screenshots below, after the code:

<form>
<select name="field_type_value" class="form-select" onChange="document.location = this.value" value="GO">
<option value=""  selected="selected" disabled="disabled">Add something to our map!</option>
<option value="node/add/local-resource">person</option>
<option value="node/add/local-resource">organisation</option>
<option value="node/add/local-resource">project</option>
<option value="node/add/local-resource">wifi hotspot</option>
</select>
</form>

Other features in the code above:

Dropdown Form, when click on element, go to link without hitting a submit button - credit: https://stackoverflow.com/questions/4347080/dropdown-form-when-click-on-element-go-to-link-without-hitting-a-submit-button
Call-to-action "Add something to our map!" is not a selectable item in itself, so made this unselectable - credit: http://www.lattimore.id.au/2005/06/18/disable-options-in-a-select-dropdown-element/

Remaining thing to do:

The URLs each to call a different add content type form for each of the subtypes of content - I'll need to work out how to select a certain template from a URL or otherwise, but will be basing my customised content type form off this answer: How do you theme a content type's create/edit form in Drupal 7?


List Private Organic Groups Publicly without giving access to the node page?

You can tell Views to ignore the access control of some of the Views. On Views 3.x, this parameter can be found under "Query Settings" / "Disable SQL rewriting", and is described as:

  Disabling SQL rewriting will disable node_access checks as well as other modules that implement hook_db_rewrite_sql().

The full nodes will stay private, so you should make sure not to link to them in the View so that your users do not land on "Access Denied" (403) pages.


How to add inline Javascript code properly with drupal_add_js for a Drupal Commerce checkout pane?

Presumably you're using hook_commerce_checkout_pane_info

Try using $form['#attached'] to add your js to the checkout pane form instead. That may work better there.

$form['#attached']['js'] = array(
  drupal_get_path('module', 'my_module') . '/checkout_pane.js',
);


How does resizing of images work with lighttpd?

Change your lighttpd rewrite rule to this :

url.rewrite-final = (
"^/system/test/(.*)$" => "/index.php?q=system/test/$1",
"^/([^.?]*)\?(.*)$" => "/index.php?q=$1&$2",
"^/([^.?]*)$" => "/index.php?q=$1",
"^/rss.xml" => "/index.php?q=rss.xml",
"^/(.+/files/styles/.+\.+.+)\?(.*)$" => "/index.php?q=$1&$2"
)

That must work. if not disable the clean ulrs to see if the problem is solved or not .


Actually, I can't see how this could have been different prior to 8.3 - PHP's json_encode seems to have been escaping / by default forever, and neither Drupal nor Symfony seem to have overridden that in the past.

The service ID and class you would need to override is serializer.encoder.json (Drupal\serialization\Encoder\JsonEncoder), adding a JSON_UNESCAPED_SLASHES to the options bitmask in the constructor. (Confusingly, there's a separate service named serialization.json, which isn't the one that's used here.)

However, note that \/ is a valid escape sequence in JSON (if not strictly required), and a JSON parser must interpret this as a literal forward slash character to be working correctly. There should be no backslashed URLs in the parsed values. Is it possible that your client's parser library has a bug?


Using taxonomy hierarchy in Views arguments

2 ways to approach this:

Option 1: Custom module (preferred)

If you don't mind coding:

First, you'll need to create a view with a term contextual filter. It is also important to add "Has taxonomy term ID depth modifier" filter. This will ensure that if you pass the parent term ID, all items that are tagged in any of the parent's child terms will be included in the result.

Your custom module will have to do a few things to make this work:

Define menu items using the top-level terms. The menus will also accept child terms (sub-category) as optional parameters. In essence, you are defining menu items to be in this pattern - products/<category_id>/<[sub_category_id]>. Where sub_category_id is an optional parameter.
Define a menu callback which programmatically embeds the view. If the sub-category is not available, use the parent in generating the view. If the sub-category is available, use that instead.

Sample code:

<?php

/**
 * Implements hook_menu().
 */
function example_menu() {
  $items = array();

  // Define the menu for each top-level category. Each menu will have an
  // optional parameter that can contain the sub-category (a term under
  // the parent category).
  foreach (example_product_categories() as $tid => $term) {
    $items['catalog/'.$tid.'/%'] = array(
      'type' => MENU_CALLBACK,
      'page callback' => 'example_product_catalog_page',
      'access callback' => TRUE,
      'page arguments' => array($tid, 2),
    );
  }

  return $items;
}

/**
 * Page callback to generate the product catalog view.
 *
 * @param $parent
 *   The tid of a top-level product category.
 * @param $child
 *   A n-tier level of a product category.
 */
function example_product_catalog_page($parent, $child = NULL) {
  // @todo: Optional. Check that $child is a term under $parent.

  // If $child is defined, we use that to generate the product catalog.
  if ($child) {
    return views_embed_view('product_catalog', 'product_catalog_page', $child);
  }
  else {
    // If $child is not defined, we use the $parent to generate the product
    // catalog. This will also show all records tag in any of the parent's
    // child terms.
    return views_embed_view('product_catalog', 'product_catalog_page', $parent);
  }
}

/**
 * Returns an array of top-level product categories (terms) keyed by the tid.
 */
function example_product_categories() {
  $product_vocabulary = '<VOCABULARY_NAME>'; // The name of the vocabulary
                                             // that contains the categories.
  $categories = array();

  // Load the vocabulary using the name to get the vocabulary ID.
  // If you know the vocabulary ID, you can skip the loading of the vocabulary
  // object and proceed directly to the loading of the taxonomy tree.
  if ($vocabulary = taxonomy_vocabulary_machine_name_load($product_vocabulary)) {
    // Load a taxonomy tree with only the top-level terms.
    $categories = taxonomy_get_tree($vocabulary->vid, 0, 1);
  }

  return $categories;
}

Option 2: 2 Views

This would involve creating:

2 views, each with a page, or
1 view with 2 pages

The trick is to define 1 page that will accept 1 parameter only and another page that will accept 2 parameters. For the page that will accept 2 parameters, you can choose to ignore the 1st parameter or put in some validation (e.g. taxonomy validation).

Another option: Combination of modules

Although I haven't tried this, you might want to look at a combination of the following modules:

Taxonomy Menu
Pathauto
Views

I would imagine that this will take some custom codes particularly in creating a custom taxonomy path, which would involve implementing hook_taxonomy_menu_path(). The end-goal is to create a custom taxonomy path which would take the form of products/<parent-tid>/<[child-tid]> if the term has a parent or products/<parent-tid> if the term doesn't have a parent. The custom menus will then point to a custom view or views.


Backup & Migrate not working because of perrmission settings? what should they be?

Well last time I had the same problem what I did is connect with fillezilla and right-click to the root folder of my site then change permissions to 777 filezilla will go through all your folders and sites and will change all the permissions automatically, it will take some minutes but then all your folders and files will have 777 permissions, try again to use your back-up and migrate, do not forget to clear chaches, after use backup and migrate change the permissions to your settings.php and your private folder in sites/default/private that forlder is where backpup and migrate saves the backups.

Also make sure the the database user you are using with your drupal has all the privileges.


how to get uri of an image field in a views_view_list twig template using drupal 8?

Finally this was my solution.

The template:

    <{{ list.type }}{{ list.attributes }}>

      {% for row in rows %}

{{ row.content }}

      {% endfor %}

    </{{ list.type }}>

Twig filter:

class ImageStyleTwig extends \Twig_Extension
  {

/**
 * Generates a list of all Twig filters that this extension defines.
 */
public function getFilters()
{
  return [
    new \Twig_SimpleFilter('imagestyleurl1', array($this, 'imageStyleUrl1')),
    new \Twig_SimpleFilter('imagestyleurl2', array($this, 'imageStyleUrl2')),
  ];
}

/**
 * Gets a unique identifier for this Twig extension.
 */
public function getName()
{
  return 'imagestyle.mymodule_general.twig_extension';
}

/**
 * Get the url of the image by an image style
 */
public static function imageStyleUrl1($imageField, $imageStyle)
{
  return ImageStyle::load($imageStyle)->buildUrl($imageField[0]['#item']->entity->uri->value);
}

public static function imageStyleUrl2($imageField, $imageStyle)
{
  return ImageStyle::load($imageStyle)->buildUrl($imageField->entity->uri->value);
}

}


How can I add pager to the comments of advanced forum in drupal 7?

In your style directory, you should have a *.topic-header.tpl.php file. Make sure the following is where you want the paging to display:

<?php print($pager); ?>

Then, in *sites/all/modules/advanced_forum/includes/theme.inc*

Approximately line 446:

  pager_default_initialize($variables['node']->comment_count, variable_get('comment_default_per_page_forum'));
  $variables['pager'] = theme('pager');


Based on the comments on your question, I certainly hope you're doing this in a .install file and not a .module file.

The $ret variable is expected to be a reference, so you'll need to declare it before hand.

$ret = array();
db_change_field($ret ...);

Is your table name really content_type_?

And you may want to look at this and stick in a couple dsm() calls to see what the db_change_field() function is actually passing to MySQL and then you could trouble shoot the query directly.


Probably the easiest way is to just go to the ImageCache Styles page and re-save the style. Don't make any changes just hit save.

You could also just delete all the thumbnails out of the image_styles folder in your files/ directory.


How to exclude recursive module dependencies?

In my opinion, the best is have always in mind solid and stable solution.

If you have this problem you should change your design, not your code.

Your module should have a display, and your submodule should have a display who modifies your module's display.


I used the webform to create a contact form and mails are send


How to restore $form_state when rebuilding a form after a redirect

I got this working in the end. The solution was:

$form_array = drupal_retrieve_form($cached_form, $cached_form_state);
$form = $form_array['#form_id'];
$block['content'] = drupal_render($form);

where $cached_form and $cached_form_state were the $form and $form_state values that had been stored in $_SESSION. Note that '#form_id' is a literal string, I've no idea why drupal_retrieve_form returns an array with that string as a key.

This redisplayed the form in the block after the authentication challenge, with the user's pre-challenge selections populated into the form elements. I couldn't get it to work with either drupal_get_form() or drupal_build_form().


You'll likely have to change what you mean by "edit the node". You could use Field Permissions to restrict what they're able to change when editing the node.

But to truly accomplish this without letting them "edit the node", you'll need a very complex custom solution that would be unreasonably complicated for an answer on this site.


Per the other answer, blocks are 'dumb' and don't have the ability to have arguments 'passed in'. They can, however, grab arguments from the context of the page, like node IDs, current user etc.

You have two 'easy' choices really:

Write your own block: It is pretty easy, if you can do a little PHP. Create a module and implement hook_block(). There are many examples on Drupal.org.
Use the Panels and/or the Views module: Panels allows you to create panes that can have all manner of variables and contexts passed in, BUT without a special theme the block will have to live in the content area, not a Drupal region; so it depends on your site, and where you want the block. Views can create blocks too, and receive arguments from the page URL, current user and also custom code via the Views PHP module. Views and Panels work together very well.


All you need is $form['#submit'][] = 'custom_redirect';, if you want your custom submit handler to be ADDED to the default submit handlers.it will run along with the other (user module submit handlers) this way.

If you need this function only as your submit handler, then

$form['#submit'] = 'custom_redirect'; (assignment not addition to the submit array)

No need to alter the $form action.

Just alter the original submit button title if its necessary, no need to add another.


Is alternative available in back end for drush migrate-import "ID"?

We can achieve this, without using the Drush Commands

  drush migrate-import 'ID'

After the import process,

$migration = "Migration ID"
$migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
$executable = new MigrateExecutable($migration, new MigrateMessage());
$executable->import();

If you dont want to use Drush Commands, then Create the custom module and use this above command.