Node View Permissions module prohibits list of nodes in Views module I created a custom node type called 'Video' in D7, and in it are three fields, 'YouTube ID', 'Video Title', and 'Video Description'. Basically, I have a template for this node type that puts the YouTube ID into the YouTube iframe to show the video. Not a problem. It works. These videos are for authenticated users only, and I can paste the url of one of the video pages on my site, and if I am logged in, I can see it.

The problem isthat I cannot see my list of videos when logged in, unless I am logged in as admin. The View to see the list of videos (/user-area/video) is accessible, but there is no list displayed unless I am logged in as admin.

It is something with the view and permissions, because I can see the video list page (/user-area/video ~ created by Views module), but without the list on it ... and I can see the video content page (/user-area/video/[video-id] ~ drupal node, themed by .tpl.php).

Any suggestions?

UPDATE

I figured out that it has something to do with the Node View Permissions module that I am using for the 'Video' node type. Although the setting in that module for the 'Video' node type is 'View any', Views must have a difficult time with that. I can still access the video content page, but not the list of video generated by the Views module. I have to figure this out. I updated the title of this question.

The problem was the 'Node View Permissions' module not playing well with the 'Views' module (or the other way around). I removed the 'Node View Permissions' module and replaced it with the 'Restrict Node Page View' module. Did not work right away...had to rebuild permissions for the site. Problem fixed!


Create backup of MySQL database alongside Features module When collaborating with other developers, we are using Features module and push it to a repository, this way the files can be pulled to the developer's own development environment.

Our problem is the database.  What we do is export a SQL dump, and send it. Then import the SQL dump.

Is there a better way on handling database backups? Since I believe that Features module can't export the database.

It's hard to encapsulate every db configuration value into a Feature. And, Features was never designed to do that. A Feature was originally supposed to be a re-usable site component.

To capture more fully site configuration look at the Configuration module:

  The configuration management module enables the ability to keep track
  of specific configurations on a Drupal site, provides the ability to
  move these configurations between different environments (local, dev,
  qa, prod), and also move configurations between completely different
  sites (migrate configurations) without the use of modules with all
  configuration being owned by the site.

  For the most part this module provides the same functionality as a
  subset of the features module. Features module is currently the go to
  tool for moving configuration from environment to environment and site
  to site, and it does a great job doing this, but "configuration
  management" was never really what features was intended to do. The
  goal of features module was to group configurations together to
  satisfy a certain use-case. Instead most people use features to export
  configuration to code to ease with deployment between environments.
  Many of us have experienced the shortcomings of using features module
  for configuration management and found where it doesn't quite work to
  easily manage configuration. A couple other modules have spawned off
  to help with some of these shortcomings: features override, features
  plumber, Features Tools.

Additionally since not everything can be captured in Features, look into building your site via a Installation Profile where you can codify new Users, Content Types and custom variables as well.

I am currently using Features + an Installation Profile to build a webapp that lets notified individuals via email submit a Drupal Webform via a secretly keyed url parameter. You can use features (to an extent) but you really have to use many small features to get the job done, and not all modules play well with Features (like exporting Webforms, which requires node_export, uuid and THEN features) ...


How to use $form['#action'] in Views PHP field I print the comment form for each node in my view with the Views PHP module. The URL of the view is user/%/selection, and the code I am using is the following one.

$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_node_MYCONTENTTYPE_form', $comment);
$form['#action'] = url('user/'.$row->uid.'/selection');
print render($form);

When the form is submitted, I get /node/nid#comment-17 as URL.

Could you explain why $form['#action'] doesn't work?

Instead of this method, why cannot a new submit handler be written? so that you can use drupal_goto there and redirect.


How to Identify Fields from Field Collection? I have a Content Type, which has field collection and I need to load the fields present inside the field collection, Any idea on how to do this?

Very Important Note: There is no content created for this Content Type as yet.

This'll do it:

$entity_type = 'field_collection_item';
$bundle_name = 'field_profile_address';

$info = field_info_instances($entity_type, $bundle_name);

// $info at this point is an array of fields attached to the queried bundle.

From your last 2 questions I think you'd be very interested in the Field Info API docs.


Getting AJAX 200 error when view with custom exposed filter has no results [Edit 3: this turned out to be one of those phantom views problems (*) - after messing around w/ a test view cobbled together to use the custom filter, etc., etc., I ended up simply cloning the original mis-behaving view block, added it to a single page, and the thing worked!  So I took the original out of circulation and am now using the fully-functional clone.  I have no idea why the clone works and the original doesn't, but I'm not going to argue with the result.
(*) On occasion I have seen weirdness that seems to be related to choosing one views option, like a contextual filter validation method, then going a different route with a different validation method, and seeing what appears to be behavior related to the original choice.  Revisiting the settings fixed this "phantom" behavior....]
I created a custom exposed filter for a view, and everything works great when there are results for the view.  However, when the view returns no results, things get weird: my results aren't updated at all (I have auto-submit on), and I get a popup showing:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows
Path: /views/ajax
StatusText: OK
ResponseText:
[followed by what looks like the beginning of normal results]

I've searched high and low for a related Views issue on Drupal.org, as well as on StackExchange and the general internets, but I haven't seen a similar problem reported.
I tried flushing the Drupal cache, turning off Views caching, turning on Views debugging, all to no avail (nothing is written out to the log in the error situation).  There's nothing written to dblog when the error happens.
I tried adding a (Global: Text area) message to be shown for No Results Behavior under Advanced for the view, but that didn't change anything, and I don't see the message.
Out of curiosity, I added hook_views_pre_render, and I see the appropriate row count in the results for non-zero result sets, as expected. However, I see hook_views_pre_render being hit with zero results for the error cases, but there is another pass through the hook with results!
Furthermore, for the error cases, hook_views_post_execute is hit with results = 0, 1 row, and N rows, where N is the same number of results seen for the spurious result set for hook_views_pre_render for the same error case.  For non-error cases, both hooks are only hit once with the correct number of results.
Anyone have any ideas about this?
Thanks!
Lee
[Edit: I'm running Drupal 7.36 and Views 7.x-3.10]
[Edit 2: I applied the custom filter to a new, simpler view display - a page display, this time - and hardcoded a contextual filter and a matching taxonomy term in the custom filter code.  It turns out I was wrong about the error condition - there's actually one row being returned in the case that is showing up with an Ajax error for the original view block display.  Furthermore, I can run this page display with or without Ajax and not have a problem.  Lastly, for the 1-row case, I do see the 2 views hooks being called 2x each - once with 0 results, and once with 1 result for each hook.]

See my third Edit to the OP.  The problem has magically been resolved by using a clone of the original block display.  I don't know why this is the case, but that did the trick.


Best way to do geo redirection? I am working on a multilingual Drupal 7 site. I've been asked to set up an automatic redirect based on the user's location. I've tried the geo_redirect module but it does not work with internal URLs because it creates a redirect loop.

My site uses paths to switch languages. For example the German homepage is example.com/de.

It seems like there are various modules that say they can do this but some are just dev versions, some require a subscription to a geo-location service, and some like to populate the Drupal database with 200MB of geoIP data (huhhh???).

Here is an example of what I need...

User located in Germany goes to example.com
Website detects that they are located in Germany
User gets redirected to example.com/de (the German homepage)
If user in Germany goes to any URL with /de in it then no redirect occurs

Just wondering if anyone has any experience with this and how they went about doing it.

Thanks!

I would use Smart IP module.

  Smart IP identify visitor's geographical location (longitude/latitude), country, region, city and postal code based on the IP address of the user. These information will be stored in session variable ($_SESSION) with array key 'smart_ip', Drupal $user->data object with array key 'geoip_location' in Drupal 6 and 7 and user data service using the parameters 'smart_ip' as module and 'geoip_location' as name in Drupal 8 of the user but optionally it can be disabled (by role) at Smart IP settings page. Other modules can use the function smart_ip_get_location($ip_address) in Drupal 6 and 7 and \Drupal\smart_ip\SmartIp::query($ipAddress) in Drupal 8 that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code. It provides a feature for you to perform your own IP lookup and admin spoofing of an arbitrary IP for testing purposes.

You can get the user location in different ways using this module.

<?php
$smart_ip_session = smart_ip_session_get('smart_ip');
if ($smart_ip_session['location']['country_code'] == 'PH') {
  drupal_set_message(t('You are in the Philippines.'), 'status');
}
?>

Or

<?php
if ($_SESSION['smart_ip']['location']['country_code'] == 'PH') {
  drupal_set_message(t('You are in the Philippines.'), 'status');
}
?>

Now, in the Theme_preprocess_html function of your theme in the template.php file, use the above codes to check if the user is in a right place. Create template.php file in your theme and use this function:

function themeName_preprocess_html(&$variables){
{
      $code = $_SESSION['smart_ip']['location']['country_code'];
      $currentLocation = arg(1); //it returns the /de or any language
      if(strtolower($code) != strtolower($currentLocation))
           drupal_goto("www.example.com/".strtolower($code));

}

If the default provides the language code, it works well but if not, you need to handle that case. For example if the default language is English and the /en is not coming after example.com, then you need to check if arg(1) == 'en'. It is easy to do.

update

To get the user language use this code

global $language;
print $language->language;

So your code will be

function themeName_preprocess_html(&$variables){
{
      global $language;
      $code = $_SESSION['smart_ip']['location']['country_code'];
      $currentLocation = $language->language;;
      if(strtolower($code) != strtolower($currentLocation))
           drupal_goto("www.example.com/".strtolower($code));

}


Why is 'Confirm Order' pane being skipped? I’m trying to determine why the ‘Confirm Order’ pane is being skipped in my Drupal Commerce Kickstart website.

Configuring the checkout process is here.

admin/commerce/config/checkout

In the configuration settings i’ve set

‘Display this pane in a non-collapsible fieldset.’

i’ve also checked boxes of info to be displayed in the pane, such as Shipping service.

Anyone know why it is being skipped? and how to fix? this seems like a bug

This checkout pane / page is added by the PayPal Express Checkout module. PayPal EC has a step where you return from PayPal after authorizing payment to finalize the order, including taxes, shipping selection, coupon entering, etc. For other payment methods, this page is skipped.


How do I migrate users passwords? I want to migrate some users from my Drupal 7 installation to a new Drupal 8 installation. I do not want to migrate the whole site or any content. And I also do not want to migrate all users.

The problem is the password; I can export from Drupal 7 and import users to Drupal 8, but the passwords do not work anymore. I've also tried to update the hashes (password) in the database directly; so I copied the password fields from Drupal 7 to Drupal 8. That also doesn't work; I think the salt changed in Drupal 8.

Is there any solution for this?

Sorry for the confusion. Clarification:

Copying over the hashes from D7 to D8 works (I made a mistake with a backslash in the JSON output)!

So just copy over the D7 hashes (starting with $S$) from the D7.users.pass field to the D8.users_field_data.pass field. It will work. The first time, that the users logs in to the new D8 site, the password gets rehashed with the D8 algorithm (PhpassHashedPassword.check() and PhpassHashedPassword.needsRehash() are doing the magic).

Everything is fine :-) Thanks.

EDIT: Someone requested the code for this...

Here is my controller class that imports all the Drupal 7 users found in the file asde2.users.json:

  public function importAsde2Users() {
    // load asde2 user file
    $usersfile = $_SERVER['DOCUMENT_ROOT']."/".drupal_get_path('module', 'preosuser')."/asde2.users.json";
    PxLog::debug($this, "Loading asde2 users file ".$usersfile);
    // decode json array of objects
    $users = json_decode(file_get_contents($usersfile));
    PxLog::debug($this, "Found ".count($users)." Users in that file");
    $database = \Drupal::database();
    // import all of them
    foreach ($users as $user) {
      $newuser = \Drupal\user\Entity\User::create([
          'name' => $user->name,
          'pass' => $user->pass,
          'mail' => $user->mail,
          'status' => $user->status,
          'init' => $user->init,
          'created' => $user->created,
          'login' => $user->login,
          'access' => $user->access,
          'uid' => $user->uid,
        ]);
      $newuser->addRole("xx");
      $newuser->addRole("yy");
      $newuser->save();
      // dirty overwrite re-hashed hash
      $database->merge('users_field_data')
        ->fields(['pass' => $user->pass])
        ->keys(array('uid' => $user->uid))
        ->execute();
    }

    return ['#markup' => "Created ".count($users)." Users with that file", '#cache' => ['max-age' => 0]];
  }

Have fun.


Create Content Types that create other node for fields I would like to create a content type, say for example Podcast, that would have other pages for some of the fields.

A field_audio that is a file would automatically generate a /node_url/audio page, a field_transcript that is a Longtext would be `/node_url/transcript etc.

My initial hypothesis is to use a views page to set the path but I am really confused with the interface and how best to solve this problem.

EDIT

In order to clarify, I'll go step-by-step for the desired functionality.

A content type is configured to publish at domain.tld/podcast/podcast-title. This content type has a lot of fields that are removed from the display using Display Suite.

What I would like to do is to use URLs that automatically generate displaying content based URL parameters, similar to how Drupal tags do but for individual nodes.

Example website:
http://codepen.io/inkovic/pen/qEXJpo is the original content.
http://codepen.io/inkovic/pen/qEXJpo.css is the css
http://codepen.io/inkovic/pen/qEXJpo.htmlis the HTML and so forth.

I could do this manually with a contextual view + block on the actual node-url, but
Views -> Contextual Filter -> Content: Nid -> Content ID form URL would break if the url is different from the actual node.

So podcast/podcast-name/transcript would render a view based on the podcast-name part of the URL.

I do not want to create a custom content type of transcript, mp3, links etc and use Entity Relationship because that would ruin the content authoring experience.

You don't want to make a new node - just to show field value on separate page. Use Views module to accomplish that.

Create new View based on Content with Page display (path node/%/test_field).
Set Contextual Filter to Node NID (and make it global with "All display" option). Provide default value: Content ID from URL.
Choose field you want but remember to set "This page (override)" option.
Create as many page displays as you want with new path (based on the same rule - node/%/some_name) and select another field (under Fields)

That is how it should looks like:

[EDIT]
Install Sub-pathauto module for second level path aliases.


How do I change the dependencies of a library from another module I have a Drupal 8 module with the following section in the file flot_d8.libraries.yml

flot:
  version: 1.x
  css:
    component:
      css/flot.css: {}
  js:
    lib/jquery.flot.js: {}
    js/flot_d8.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

I have another module which is an optional dependency of flot. It does not need to be present, but if it is, it needs to be included in the dependencies section. So I need to add the line - timezone_js/timezone_js at the end...or, more likely, add the equivalent entry to the array that this yml file gets converted into.

Is there a way that one module can alter the assets of another module when it is installed?

I seems like I ~could~ just hard-code the line in myself, but I would like other people to be able to extend the flot module, without me having to add new dependency lines for every add-in.

Similarly, the Flot module has an element with a #pre_render function. Is there a way that a module can add an entry to the pre_render array of another module?

My flot plugin is called timezone_js. I created a file, timezone_js.module and added a call to hook_library_info_alter.

function timezone_js_library_info_alter(&$libraries,$extension){
  //We need to add this module as a dependency of the flot module.
  if ($extension == "flot_d8") {
    $libraries['flot']['dependencies'][] = 'timezone_js/timezone_js';
  }
}


Avoid adding breadcrumb if title is empty I created a view without the title but then the breadcrumb shows  as

Home>  >

If I add title to the view then it is showing as

Home> >Title

is there any way to avoid adding breadcrumb when empty title is present ?

I think you can remove the breadcrumb if you create a template for the view:

views-view--your-view-name--page.tpl.php


Correct way to validate config entities? In Drupal 8, how do I validate a ConfigEntity? I tried adding constraints, but then I found out this only works for ContentEntity, not ConfigEntity.

My ConfigEntity has 2 fields, and the options of the second field should be limited based on what's selected in the first.

Through Drupals #ajax mechanism I can limit the items in the second dropdown - that all works. However, with Javascript disabled or when creating the ConfigEntity programmatically, someone can still select a wrong value for the second dropdown, that doesn't work with the first dropdown selection. I checked ConfigEntityBase but couldn't find anything related to validation.

It depends on how your config-entities are created.
If the only way to create them is via a form, then you could just override the validateForm method in your form to ensure the entity is valid. In this context the entity should be available by running this code

$form_state->cleanValues();
$this->entity = $this->buildEntity($form, $form_state);

This is what content entity forms do (see \Drupal\Core\Entity\ContentEntityForm::validateForm).

However if you expect your entities to be added programatically or via REST and you need lower-level validation, then you could add a validate method to you entity and call this from the preSave method. Having it available as a public method (validate) would allow other consumers of your API to check if the entity was valid before they called save, thus avoiding the exception.

In terms of the contents of the validate method, you have lots of options. You could try and piggy-back onto core's constraint system - which uses plugins to define constraints. Or you could keep it simple and just return an array of errors. Finally you could keep use a middle-ground and just integrate with the validator component in the Symfony way, which would at least keep your validate return consistent with those for Content entities - something like so:

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Validation;

/**
 * Validates my config entity.
 *
 * @return \Symfony\Component\Validator\ConstraintViolationList
 *   List of violations. Empty if valid.
 */
public function validate() {
  $validator = Validation::createValidator();
    ->addMethodMapping('loadValidatorMetadata')
    ->getValidator();
  return $validator->validate($this);
}

/**
 * Defines validation rules for this config entity.
 */
public static function loadValidatorMetadata(ClassMetadata $metadata) {
  // Same validator rules.
  // Add your own as required.
  // Note this is static, so you don't have $this in scope.
  $metadata->addPropertyConstraint('someProperty', new Assert\NotBlank(['message' => 'Some property cannot be blank']));
  // But if you add a validation callback, you can operate in the context
  // of an instance.
  $metadata->addConstraint(new Assert\Callback(['methods' => ['someValidationCallback']]));
}

/**
 * Validation callback for some field.
 */
public function someValidationCallback(ExecutionContextInterface $context) {
  if ($this->something === 'something it should not be') {
      $context->buildViolation("Can't let you do that Dave.")
      ->atPath('something')
      ->addViolation();
    }
}


Execute actions (actions module not rules module) programatically How can an action from the actions module be executed programatically? In D7 there was actions_do() but in D8 actions are plugins or configuration entities according to https://www.drupal.org/node/2020549.

You should inject the plugin manager as a service if possible, but for a plugin (code) based action:

$manager = \Drupal::service('plugin.manager.action');
$action = $manager->createInstance('action_plugin_id')
$action->execute();

Or if it's an advanced action, it's a config entity, so load and execute it that way:

$action = \Drupal\system\Entity\Action::load($action_id);
$action->execute();

Again if DI is an option, inject the entity type manager service and use that to load the action instead.


How can I create Menu items through hook_install()? Like it was said in subject, how would I do that?

I need to create menu items once after module install and have the ability to edit them if needed.

module.link.menu.yml won't give me that ability.

Anybody have suggestions?

You can use hook_menu_links_discovered_alter() to modify or add additional links to those provided in *.menu.links.yml files, but these types of links are not completely editable (e.g. you can not change their title in the UI).

If your links are content based, need to be completely editable later through the UI, or are being placed in a custom menu you can directly create the menu link entities:

MenuLinkContent::create([
  'title'      => 'My internal link from a route name',
  'link'       => ['uri' => 'route:myroute'],
  'menu_name'  => 'my-menu',
])->save();

Also check out the Entity API documentation, and Working with the Entity API for more information.


Different CSS file when in development mode Using Gulp I create two css files. One style.css and one style.min.css. Is it possible to load the style.css when developing (locally) and the style.min.css when in production (remote)?

You can specify two different libraries in mymodule.libraries.yml. Then in your mymodule.module file attach the one that matches your current deployment env:

function mymodule_page_attachments(array &$attachments) {
  if (PRODUCTION) {
    $attachments['#attached']['library'][] = 'mymodule/lib_prod';
  } else {
    $attachments['#attached']['library'][] = 'mymodule/lib_dev';
  }
}

I am using code like this to decide on which deployment level I am:

  public static function getDeploymentStage() : string {
    // lazy cache
    static $ds = null;

    if (null == $ds) {
      if (isset($_SERVER['SERVER_NAME'])) {
        switch ($_SERVER['SERVER_NAME']) {
          case 'anwalt-seiten.de':
          case 'www.anwalt-seiten.de':
            $ds = AsdentBaseService::DS_PROD;
            break;
          case 'stage.anwalt-seiten.de':
            $ds = AsdentBaseService::DS_STAGE;
            break;
          default:
            $ds = AsdentBaseService::DS_DEVELOPMENT;
            break;
        }
      } else {
        $ds = AsdentBaseService::DS_DEVELOPMENT;
      }
    }

    return $ds;
  }

Note that any drush command will run in dev-mode here.
You can also use $settings from settings.php or any environment variable instead.


How to add sidebar to taxonomy page or node page? Thought a bit more how people use Drupal CMS to update categories. Categories will be taxonomies in a view so that they can refer nodes to the categories.

Also at the most when click on category, it will be either a full taxonomy page or node page.

Sidebar will have taxonomy categories on left column and right column will explain more information. So if it is on same taxonomy, the menu item will be highlighted to let user know where they are on.

The problem is how to add sidebar to either taxonomy page or node page and set menu item active / highlighted?

Normally I'd advocate writing it yourself, but in this case there are modules that do exactly what you want.

Create a block for the taxonomy you want to display and only display it on certain URL's (I'd use the path alias module to create a specific URL for relevant content e.g. '/CONTENT_TYPE/CONTENT_TITLEand test for/CONTENT_TYPE/*` on the block admin page)

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

You can use the Menu Trail By Path module to indicate what the active trail should be in the menu.


Pass parameters with tokens Is it possible to send parameters along with tokens?

I have a module that defines the mod1_info and mod1_tokens.  If I enter %token:mod1:test on a page, it is replaced with .

What I actually want is to enter %token:mod1:test[variable] and get variable.

Is this possible?

Behind the scenes, the test.html is being built with a few dynamic parameters so it actually looks similar to test.html?param1=foo&param2=bar.  What I need is a way for someone editing the site to insert a token on any page, and be able to specify what appears as the link (an image, some text, or both).

Using Drupal 7, modules can easily handle tokens similar to [node:author:name], where the part of the token after node:author is referring to a user token. Differently from the Token module for Drupal 6, the code that in Drupal 7 handles the tokens allows the creation of dynamic tokens. This is because on Drupal 7, modules implementing tokens can replace any token, not just the tokens they defined. The normal loop used in hook_tokens() is the following one.

foreach ($tokens as $name => $original) {
  // Check the value of $name, and generate the replacement that is assigned to
  // $replacements[$original].
}

Using the following code, you could get what you are trying to achieve. Tokens have a specific format, which is different from the one you are describing, though. The code has not been tested.

function mymodule_token_info() {
  $type = array(
    'name' => t('Anchors'),
    'description' => t('Your description'),
  );

  return array(
    'types' => array('anchor' => $type),
  );
}

function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'anchor') {
    foreach ($tokens as $name => $original) {
      list($file, $title) = explode(':', $name);
      if (!empty($title) && !empty($_GET[$title])) {
        $title = $_GET[$title];
      }
      else {
        $title = '';
      }

      $replacements[$original] = "$title";
    }
  }

  return $replacements;
}

The replacement for the tokens is so specific that I don't think you will find a module that does that. Your only possibility is a custom module you write.


Alter view with hook_views_post_render and save results to cache How can I alter the results of a view with hook_views_post_render but save the altered output to cache, in order to avoid the overhead of altering the results on every request?

The ideal scanario should be like this: Is the cache expired -> Yes -> alter the view's output -> Save new output in cache, Otherwise don't alter the output.

Yes Clive is right use

function hook_views_pre_render(&$view) {

instead of

function hook_views_post_execute(&$view) {


Administration menu module not working Im using D7.24
I downloaded admin_menu module (I tried also previous releases) but when trying to enable it I can't, and I get this info message in the description module field :

  Requires : System (>7.10) (is incompatible with version > 7.x-1.0-beta3) Required for : Administration menu Toolbar style (disabled)

I searched about this problem but I did not found anyone has this problem before!

Thanks in advance

EDIT:
This is the info that I get in status report :

Per this line in admin_menu.info:

dependencies[] = system (>7.10)

The module requires a core version of Drupal greater than 7.10. Currently yours must be less than that.

Drupal core is currently at 7.26; you'd be wise to update ASAP, there have been a number of security updates in recent memory.


AJAx HTTP ERROR, can't add views to Drupal 7 site, same behavior on 2 different sites I get these errors when creating views at every step, in Chrome errors says 200 in Firefox says 500...

I can get as far as having the view created, by ignoring the error, but then I can't add any fields, so it renders my Drupal site useless basically.

I have played around with Jquery versions and no solution seems to work.

Additionally, this behavior can be seen on 2 different website, identical...

Sites are both up to date Drupal 7, on status report everything is immaculate, they both run Boostrap theme but the admin Theme is Bartik

It was a problem with the hosting company....but they were great and changed to PHP 5.4(native) right away, fixed it.

Great job namecheap.com hosting, as usual, they are actually really good


How to remove only created hour? I'm using Drupal 7 and Clean theme. And when created a node, show date top on node. No problem. But i want remove only hour and min. tab.

How can i solve this?

I think you want to have your node show June 12, 2012

If that is the case, you can do this:

function THEME_preprocess_node(&$variables) {
  if ($variables['submitted']) {
    $variables['submitted'] = t('Posted: !datetime', array( '!datetime' => format_date($variables['node']->created, 'custom', 'F j, Y')));
  }
}

Here's PHP documentation for date formats: http://php.net/manual/function.date.php


Custom source to field in Feeds module? I'm setting up a way for a Drupal site to import data from third party sites using a PHP script that creates a XML structure.

I'm using the Feeds module, which otherwise works fine. But I miss something.

Now, I need to add a custom source from the feed that adds data to a field.

Like that I have a  inside the XML  that I want to be used for the nodes image_field. I need more then just a image, but as an example.

How do I do that?

Is there perhaps a way that will work so that I wont have to code it by myself?

PS. Since I've coded the script that creates the XML, I could easily change XML to about anything else that might work better. DS.

Feeds Xpath Parser module can help you map custom fields to your xml values.  I've used this myself.  There is also Querypath Parser which may do the same thing (I've never tried this one).


Programmatically Set Default Text Editor I have a customized module that requires tinyMCE as a library.

After module installation, I still have to set my text editor in the image above. It was found in the admin/config/content/wysiwyg.

How will I programatically set tinyMCE as a default text editor right after module installation?

Below code is used in wysiwyg_profile_form_submit() at wysiwyg.admin.inc. You can make use of it.

// Insert new profile data.
db_merge('wysiwyg')
  ->key(array('format' => $format))
  ->fields(array(
    'editor' => $editor,
    'settings' => serialize($values),
  ))
  ->execute();
wysiwyg_profile_cache_clear();

Another approach is using drupal_form_submit() to submit its settings form programmatically. But it would be more compliated.

Also, before settings the profile, you need to check if tinymce is existing.

if (wysiwyg_get_editor('tinymce')) {

  // set profile.

}


How can I add a constraint to a custom field I created? I have created a complex field type (my class extends DateRangeItem) that supports recurring dates by adding a property for storing an RRULE string:

class DateTimeRecurItem extends DateRangeItem {

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);
    // Prevent early t() calls by using the TranslatableMarkup.
    $properties['rrule_string'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('RRule String'))
      ->setRequired(FALSE);

    return $properties;
  }

  ...

I want to validate the RRule string (there's a RFC to validate it against). I can do this by creating a custom constraint and applying it like this:

$properties['rrule_string'] = DataDefinition::create('string')
  ->setLabel(new TranslatableMarkup('RRule String'))
  ->setConstraint('MyCustomConstraint')
  ->setRequired(FALSE);

The problem is I also need to know the value for the value property of the field (which is inherited by DateRangeItem). Implemented as above, my constraint validator will only be passed the raw string value of the rrule_string property.

I can't figure out how I can define a constraint that applies to the entire field (thereby having access to all of its field properties). There seems to be no interface for doing that.

To be clear, this is not a field I've added to a custom entity definition. This is just a custom field I defined that can be added to any entity.

In case of a field type, you can simply put it in the annotation.

Have a look at FileItem for example:

/**
 * Plugin implementation of the 'file' field type.
 *
 * @FieldType(
 *   id = "file",
 *   label = @Translation("File"),
 *   description = @Translation("This field stores the ID of a file as an integer value."),
 *   category = @Translation("Reference"),
 *   default_widget = "file_generic",
 *   default_formatter = "file_default",
 *   list_class = "\Drupal\file\Plugin\Field\FieldType\FileFieldItemList",
 *   constraints = {"ReferenceAccess" = {}, "FileValidation" = {}}
 * )
 */
class FileItem extends EntityReferenceItem {

Actually a bit surprised that the date classes don't have any constraints, that sounds like a bug.


Synchronize users strategy for Drupal 7? I am trying to think of a logical way to integrate another system's users with Drupal's. The actual integration is between Drupal and WHMCS. WHMCS has its own API so you can do things like getUser(emailAddress). What should be my strategy? Is there an easy way to make Drupal completely ignore the local "users" table and rather use another source for authentication? Perhaps auto-creating an entry on the Drupal side for non-existing users and automatically making users inactive that no longer exist on WHMCS's side?

UPDATE

I tried the suggested authorization providers suggested, but it seems my problem is the other way around. I don't want other sites to be authenticated using my drupal site's login details. What I actually want to do is use an installation of WHMCS, and use that as the authorized users list. In other words, when a user tries to log in using their whmcs details, it must log them into the drupal site. If they change their e-mail address on the drupal site, it must update it on the whmcs site. I know how write the api implemtation, I just don't know what I must use to do the groundwork. I would imagine there is already some kind of middleware that does the bulk of the work, and then I just have to code the implementation that does the lookup of a user, the call to update the details etc.

Is there something available that will allow me to easily integrate with a JSON Api like WHMCS?

I don't know anything about WHMCS but there seem to be a lot of apps around LDAP connectivity that you can get for it.

The LDAP project for Drupal works well for me for authorization, both with Drupal as the host and with Drupal as the client.


Automtically creating new redirects and alias on node_save Here is the code I'm using to change the name field of my nodes if they contain certain phrases.

$query = new EntityFieldQuery();
$query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'my_product')
    ->fieldCondition('field_my_name', 'value', 'Old Phrase%', 'LIKE');

foreach ($result['node'] as $key => $value) {
    $node = node_load($key);
    $node->field_my_name[LANGUAGE_NONE][0]['value'] = str_replace('Old Phrase', 'New Phrase', $node->field_my_name[LANGUAGE_NONE][0]['value']);
    node_save($node);
}

It successfully changes the name; however, I'd like to automatically create a new URL and also a redirect entry from the old URL to the newly generated one.

I have pathauto installed and my URL Alias is configured to use the my_name field, but the code above does not change the Alias.

Pathauto should automatically create a new alias with the updates (unless you have it turned off on the node). pathauto.module lines 519-522:

// Skip processing if the user has disabled pathauto for the node.
if (isset($node->path['pathauto']) && empty($node->path['pathauto'])) {
  return;
}

The Global Redirect module can then provide 301 redirects to the new URL alias.


show custom menu in page tpl file <?php if (isset($custom_links)) { ?>

<?php print theme('links', $custom_links) ?>

<?php } ?>

I've create a custom menu (machine name: menu-secondary-menu). And I want to display it in page.tpl. My condition is to show this this menu only if it has links added. I searched and found the above code. Please help me in customizing to my need.

<?php
// Enter the machine name of the menu you want to show.
$menu_name = 'main-menu';
// Check if there are any menu items in it.
if (count(menu_navigation_links($menu_name))):
?>
<div id="secondaryNav">
  <?php print theme('links', array('links' => menu_navigation_links($menu_name), 'attributes' => array('id' => $menu_name, 'class'=> array('links', 'inline')))); ?>
</div>
<?php endif; ?>


prevent user from putting 0000 in date field How can I force date validation upon input of a content type so that a user cannot type in 0000 as the year which causes an error in  Drupal 7.

You can use Field Validation to check against the date, it has a sub module or feature that has date validation.

You could also do this with a hook, probably hook node validate would be your best option for this.


no field settings in block views? coming from D6, Im confused about why I can't seem to choose which fields from a content type I want to be displayed when I want to use the view as block? I searched for drupal 7 views fields settings but the results weren't about this particular issue.

If you select the content link on the 'show' line in the format section of the block definition (first column), you can switch the format to fields and then the available fields can be added.  You may want to view the video learning series at nodeone.se called "Taming the Beast' for more on how to use Views.


FAQ display using Views I would like to set up a FAQ system using a custom content type and views. I would like to display the FAQs one of two common ways:

Each question is a link that hides/displays the answer below it when the link is clicked, or
Each question is a link that jumps down to a corresponding anchor on the page with the answer.

Are either of those possible in Views? I'm new to Drupal and learning as I go. Thanks.

There is a module that will do exactly that, called FAQ.

And it also integrates with Views should you need to extend it. But out of the box, it should do the two things you need (I have used it and did both things).


How come my view block is not loading using ajax? We have a view, myview, that has an exposed filter title (text input). The view has Exposed form in block:Yes and so we load it onto the page under admin/structure/block. The block has a machine name of exposedform_myview_title.

We want to remove it from display and only load the view block on click of an icon. How come my view block is not loading when using ajax?

View Setup:

view_name = 'myview`
when creating view, view page setting -> "create a page" was set to true
view machine name = mypage
view use ajax = Yes
view block (displayed using admin/structure/block) machine name exposedform_myview

Error message

  https://somesite/path/views/ajax?view_name=myview&view_block_id=mypage
  404 (not found)

myjs.js

This will load the view itself and not the exposedform_myview_title block. We want the exposedform_myview_title to be displayed.

(function($) {
  'use strict';

  Drupal.behaviors.iconClick = {
    attach: function(context, setting) {
      $('#someid', context).once().each(function () {
        $(this).on('click', function(clickEvent) {
          // Use Ajax to load form.
          $.ajax({
            url: drupalSettings.path.baseUrl + 'views/ajax',
            type: 'GET', // type: 'POST' not succesfull
            dataType: 'json',
            data: 'view_name=myview&view_display_id=mypage',
            //not successfull --> data: 'view_name=myview&view_block_id=exposedform_myview',
            success: function(response) {
              var output = response[1].data;
              $('.some-element').html(output);
            },
            error: function(data) {
              alert('error');
              console.log(data);
            }
          });
        });
      });
    }
  };

})(jQuery);

page.html.twig

...

my icon goes here

 view block exposed form should go here

...

we also tried to use Drupal.ajax, but that did not load the View into the required

(function($) {
  'use strict';

  Drupal.behaviors.iconClick = {
    attach: function(context, setting) {
      $('#someid', context).once().each(function () {
        $(this).on('click', function(clickEvent) {
          // Use Ajax to load form.
          var ajaxPath = '/views/ajax';
          var view_info = {
            view_name: 'myview',
            view_display_id: 'page'
          };

          var ajax_settings = {
            submit: view_info,
            url: ajaxPath,
            event: 'click'
          };

          Drupal.ajax(ajax_settings);
        });
      });
    }
  };

})(jQuery);

I got this working:

gotchas:
1. Had to load ajax_view.js, added this code snippet to theme file, check your view source to make sure ajax_view.js is loaded.

use \Drupal\views\ViewExecutable;
function customthemename_views_pre_render(ViewExecutable $view) {
  if (isset($view) && ($view->storage->id() == 'community_plan_update_news_feed')) {
    $view->element['#attached']['library'][] = 'pager-view';
  }
}

Had to write my own jquery once function in Drupal Behaviors file:

(function($, Drupal, drupalSettings) {
    'use strict';
    // turn off scrolltoTop
    if (Drupal.AjaxCommands) {
        Drupal.AjaxCommands.prototype.viewsScrollTop = null;
    }
    // Write your own jquery once function
    $.fn.once = function(processed_class) {
        if (typeof processed_class == 'undefined') {
            processed_class = 'processed';
        }
        return $(this).not('.' + processed_class).addClass(processed_class);
    };

    Drupal.behaviors.pagerFragments = {
        attach: function(context, settings) {
            var pager_links = $('.tab-content .pager__items li a').addClass("use-ajax");
        }
    };

    Drupal.behaviors.linkClick = {
        attach: function(context, settings) {
            $(".pager__items li a", context).on('click', function() {

                var ajaxObject = Drupal.ajax({
                    success: function(response) {
                        var viewHtml = response[1].data;
                        Drupal.settings.views = response[0].settings.views;
                        Drupal.attachBehaviors();
                        if (response[1].data !== undefined) {
                            $('.tab-content').html(viewHtml);
                        }
                        var ajaxPath = 'views/ajax';
                        var view_info = {
                            view_name: 'community_plan_update_news_feed',
                            view_display_id: 'general_plan_news',
                        };
                        var ajax_settings = {
                            submit: view_info,
                            url: ajaxPath,
                            cache: true,
                            event: 'click',
                            async: true,
                        };

                        Drupal.ajax(ajax_settings);
                        ajaxObject.success(response, "success");
                    },

                });
            });
            // reload sharethis icons
            if (__sharethis__ && __sharethis__.config) {
                __sharethis__.init(__sharethis__.config);
            }
            Drupal.behaviors.animate = {
                attach: function(context, settings) {
                    $(document).ajaxStart(function() {
                        $('.tab-content').fadeTo(200, 0);
                    });
                    $(document).ajaxSuccess(function() {
                        $('.tab-content').fadeTo(200, 1.0);
                    });
                }
            };
        }
    }
})(jQuery, Drupal, drupalSettings);


How to make nice content manager approval page? The client wants to allow users to upload files but only publish the ones that are approved by the content managers. The content managers want a nice way to flip through pictures and quickly accept or reject pictures.

I created a view where someone can flip through unpublished pictures.

Is there a way to add a check box that corresponds to the the published checkbox in the add content? Basically be able to edit the content within this simple view, but all they would need to edit is published/unpublished.

Any Ideas. Hopefully there is a way to do this without another module, but I'm not picky at this point.

I guess Views Bulk Operations (VBO) may help you here. Here is a quote about it (from the module's project page):

  ... This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.


How can I filter sensitive data being recorded in calls to Watchdog I have sensitive data that is sent to a Drupal instance and I don't want it to be logged. I can filter out sensitive values with simple string replacements for my own calls to watchdog(), but for PHP errors and other modules making watchdog() calls, the data may be logged and this needs to be filtered too.

Assuming you're dealing with the dblog module, this is a workable solution:

Disable the dblog module
Copy dblog_watchdog into your own module's hook_watchdog implementation
Wrap each of the appropriate database field entries with your function to sanitise the string, e.g.

Database::getConnection('default', 'default')->insert('watchdog')
  ->fields(array(
    'uid' => $log_entry['uid'],
    'type' => mymodule_sanitise(drupal_substr($log_entry['type'], 0, 64)),
...

If you have other watchdog modules in use, you'll need a copy/edited hook_watchdog version for each of them too.


Adding content to a specific view I have views in a dropdown which hold my content lists, the issue is I cannot add specific content to a specific view.

I have 2 views; Current affairs and Education, I want to add content to a specific view; lets say to the Discussions view but when I add content it is added to both my views here are snips

I decide to add "PK Chishala Bana Mulenga" and "Child Labour, How can we alleviate it?" but I find them in both the Current Affairs view and Education view anyone who knows how I can solve this issue?

A View is basically a query builder. You need to provide it with a filter that includes the content you want to show, and excludes the content you don't want to show.

There are many different different ways to solve it, here are a few of the common ones:

Use different content types for the different types of content, and filter by "Content type" in the Views
Add a Vocabulary, "Post Type" or something, with "Current Affairs" & "Education" as terms; attach a term reference field for that vocab to the content type, filter on that instead in the Views
Add a boolean/text/numeric/whatever field to the content type, set that to a value on a node-by-node basis, use that to filter the Views.


How to access a node's menu link title in Views? I'm surprised to not be able to find anything about this seemingly simple or routine request.

Suppose I have nodes that have long titles. They have menu items created the usual way, with short form titles.

I want to make a view of nodes that uses the menu item title of the nodes instead of the full title. However:

There are no fields I can see that relate to the menu item,
I can't see any available relationships that would access the menu item and make it available.

As a workaround I'm creating a custom field "subtitle" specifically for the views titles, but it's a bad workaround. Is there no way for Views to see the menu item of a node?

Out of the box, there isn't a way.
The only thing that may possibly help you is the
Menu Node Views

The Menu Node Views module provides Views integration for nodes
assigned to the menu system. This module is in alpha development.

Else, a workaround is the only way.


How to issue 404 from a KernelEvents::REQUEST event I'm trying to issue a 404 from a KernelEvents::REQUEST event, but it's resulting in the following error:

Fatal error: Maximum function nesting level of '256' reached, aborting! in /var/www/vendor/symfony/http-foundation/HeaderBag.php on line 162

Here's my class

<?php

namespace Drupal\my_module\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;

class MyClass implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['my404Check'];

    return $events;
  }

  public function my404Check(GetResponseEvent $event) {
    // Do some logic here to check if it should be a 404.
    throw new NotFoundHttpException();
  }

}

I'm guessing I can't throw exceptions here, but can't see any other documentation on how to issue the 404.

You can set a response early in a request event:

 public function my404Check(GetResponseEvent $event) {

    // only return a response for a master request
    if (!$event->isMasterRequest()) {
      return;
    }

    // Do some logic here to check if it should be a 404.

    $response = new Response('', Response::HTTP_NOT_FOUND);
    $event->setResponse($response);
  }

The event dispatcher checks if a response is already set and returns this response without executing any more code to build a Drupal response.


Is it possible to hide a field on a form without writing code? there are good instructions on hiding a field using a hook.

Is there a simpler way of doing this? I would like to hide a term reference field on a node edit form but use the default value for it.

If you simply want to hide the field and have the default value saved, you should be able to simply hide the field with CSS. Find the ID of the wrapper surrounding the field and set it to display: none;.  Here is a working example from my D6 site:

#edit-field-vendor-sort-order-0-value-wrapper {
  display: none;
}


Page not getting redirected properly I'm only using i18n and not Entity Translation.

I've an English version of page set as front page( node/page1).

I've restarted working on my multilingual site after 2 months and previously it was working fine.
Earlier I had added French, German, etc translated version of this page.

So if I go to mysite.com/de or mysite.com/fr those translated pages are shown automatically(in short existing translated pages are getting redirected correctly).

But now (after 2 months) when I add translation for untranslated languages like "it" then mysite.com/it does not redirect to the Italian version of the home page.

I've Global Redirect, Translation Redirect enabled. I've also tried clearing all cache several times.

What could be the problem?

Your problem might be because of the "language detection" configuration.

So check this configuration via Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.


Use feature as module? Does anyone have experience with using a feature as a module?
The usage I am talking about is strictly placing hooks inside the .module file.
Can that trigger any sort of bug?

Of course, you can use a feature like a "normal" module.

Feature use .module file only for include a file, so after this include you could add your custom code.
And obviously you can add more files, directories, etc.

It's a great way to avoid to create too many modules.


yml settings file is just read on module install I have a config/install/module_name.settings.yml with some configuration values needed for my module. Now while developing the code I need to change or add values to the file. But for the script to be able to access the information I need to deinstall and install the module each time.

Is this normal?

I guess the yml file is just read on install; afterwards, the values are stored in database.

How should I store configuration data without needing to reinstall the module each time?

This is normal, because if the user modifies the settings, he doesn't expect that the changes are overwritten by a module update.

If you want to change the settings in an update hook, you can use the config API.

\Drupal::configFactory()->getEditable('mymodule.settings')->set('mysetting', $value)->save();

In development you can export the complete config of your site once to the sync folder. There you will find the yml file: /sites/default/files/config_hash/sync/module_name.settings.yml.

Edit the yml file in the sync folder and import the config as often as you want until you find the final version. After you've finished the development you can copy the final version of the settings yml in the module folder.

For export and import you can either use the admin configuration interface or use drush config-export and drush config-import.

Another option is to directly edit the config on the command line:

drush config-edit module_name.settings

After closing the editor the settings are imported in the active config. After you've finished the development open the settings one more time and copy and paste the end result in the yml file of your module.


Display Language specific content I created two languages

English and French

I am facing problem when content is not translated into french by default its displaying english content.

How to display only french content if i select french language

Try the below module.

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

Install the module and Add filter in view by selecting(content translation:select translation) field

And select this option : use current language ; if not available use original language


Adding multiple HTML pages as nodes as part of workflow I've just started using Drupal. I'm in the process of building my first web site (I'm not a web designer but have a reasonable knowledge of html, css and python and some comprehension of the DOM).

My workflow is to produce content in markdown and then produce html files locally before uploading to my site. I've looked at a few options to try and do this in Drupal but am struggling to make headway.

All I really want to do is grab a bunch of html pages at a time from a folder (in ubuntu linux) and add them in as basic page nodes with the filename as the node title.

I've tried the feed module and import_html and migrate but they all seem to be set up to take a SQL table rather than a simple html table. I don't need anything parsed or mapped other than full text to "content" as full html and file_name to title.

Any help appreciated. This is pretty fundamental to the way I work, and after three days of trying to crack it, I'm stumped.

adding that I have reviewed the following question

How to add multiple HTML nodes in Drupal and viewed the video and followed the link but the former doesn't cover html and my import doesn't show up as a node and the latter has several PHP code fragments and I'm not sure how to bring them together into a single script and where to put that script.

Tahnoon,
This is a very unusual task you are trying to perform. Typically we use Drupal to generate new content and manage how that content is displayed. As you have experienced, there are a couple mechanisms in place to import data from databases, spreadsheets, CSVs etc, but not an easy way to import existing HTML files from a specific directory.

What you are trying to do CAN be done but it will take a certain amount of PHP coding [not a whole lot] to write a custom module that would do this.

Since your request is not a common case, you will not find a tutorial for it that exactly meets your needs. Rather, you will have to learn PHP and Drupal Module development techniques and write code to find that directory, parse through each file in it, extract out all of the markup between  and  and place it in the body field, change the filter to FULL HTML, take the file name and use it for the TITLE.

I can't possibly use StackExchange to teach you all of this, so I'll just get you started.
1] get friendly with http://api.drupal.org this is where we store all of the documentation on the Drupal API
2] specifically look up the hook_menu implementation and create a page where your custom code will fire [for this purpose you're going to hardcode the directory rather than build a user-interface that asks for it.]
3] study up on the family of Drupal file functions. I don't think you'll need any generic PHP file functions, but it could happen.
4] download and install and enable the Examples for Developers module  There is one example in there that is FILE related and it saved me A LOT of work last month.
5] You also need to look at the Google results on how to programmatically create nodes http://goo.gl/A3hUP4 there are a few ways to do this.

Those 5 steps should get you where you want to be. Since you're somewhat new to PHP and Drupal this may take a long time, but it will be a tremendously great opportunity to learn!

If you can afford it, you may want to pay someone to build this OR to help you build it so that you learn in the process.

I hope you find this helpful! :-)


When does Drupal 5 run cron? What causes Drupal 5 to run a cron job?

I know about cron.php.  Are there any other ways in which cron is likely to be called?  For instance are there any core or commonly used modules that call it?

Poormanscron is the most common module used for calling cron within Drupal (integrated into core in D7).


How to create views tabs in D8? I can't get views tabs to work in D8, following the exact UI procedure that does work in D7.

To be more precise, in D8 at /mypage I see no tabs at all, and at /mypage/tab2 and /mypage/tab3 I do see tabs "tab2" and tab3" but no "MyDefaultTab".

In D7, I see all 3 tabs when viewing any of the 3 URLs.

The following procedure works to create a Views page with tabs in D7 on simplytest.me, but does not work for D8 beta 15:

Manage > Structure > Views > Add new view
View name = "Myview"; Show "Content" of type "all"; save and edit.
Add page display; name="MyPage"; path = "mypage"; menu = "Normal menu entry" with menutitle ="MyPage" and parent="" (its default value) and weight=0;
Add page display; name="MyDefaultTab"; path="mypage/defaulttab"; menu = "Default menu tab" with menutitle ="DefaultTab" and parent menu item ="Already exists";
Add page display; name="tab2"; path="mypage/tab2"; menu="Menu tab" with menutitle="Tab2" and parent ="" (its default value) and weight=0.
Add page display; name="tab3"; path="mypage/tab3"; menu="Menu tab" with menutitle="Tab3" and parent ="" (its default value) and weight=0.

Is this a D8 bug, or am I missing something?

Things I have tried (all made no difference, good or bad):

Selecting "MyPage" (the non default but sensible seeming value) in the "parent" drop down for tab2 and tab3 (there are more menu options available in D8 than D7).
Selecting "Normal menu item" instead of "Already exists" for the parent menu item of the default tab.
Configuration > Performance > Clear All Caches

Any suggestions?

I have just created a views page with tabs. Following are the instructions.
Add a views display of type page

Set its path to "/test"
Then its menu option: Select "Default menu tab" and on next screen    select "Already exist" under the "parent menu item".
Then adds another page display
set its path to "test/tab1"
and in its menu option: select "Menu tab" and save.

Visit the "/test" page and both tabs appear.
Hope it may help you.


Show node in view based on dropdown in seperated content type I have two content types. One content type is 'sport' and a other content type is 'teacher'. I collected the content type 'teacher' with views and I display the fields in a block (this is important for my site set-up).

My content type 'sport' is seperated from the content type 'teacher' (this is also important for my site set-up). My content type ‘sport’ is the content type where my block ‘teacher’ is showing up.

My page is look like this:

If I create a new sport like basketball, the information of soccer changes into the information about basketball and the teacher should be Rob (choose from a dropdown when creating a page from content type 'sport').

I found a solution.

I followed the following steps:

I have created an entity reference (in the content type sport)
I have created a view with relationship to the entity reference
I have created a contextual filter, content Nid with the relationship I created before to the entity reference field.

Everything works now!


Adding a page to a menu with query parameters in the URL I'm trying to add a page generated by CiviCRM to my menu. The pages url is 'civicrm/contribute/transact?reset=1&id=6'. I've added the link to the drupal menu manually, and it goes to the page, but that menu item isn't set to active and the active-trail class is not set to it's parent items.

I tried using the full URL and also tried created a module that added a hook_menu function to create a url without query parameters. The hook_menu callback would redirect to the path above.

How can I add that link to my menu, and have the active and active-trail classes set?

Ah yes, this has plagued me for years.  I cheat and use "Global Redirect Module" https://www.drupal.org/project/globalredirect


How to mandate the password policy in custom form fields? I have custom form which has password field values and by using that user will be created in our website. So the requirement is to use password policy module functionalities to this form also. The form is able to show the policies below the password field and now those suggestions like use alphanumeric etc.. are not mandatory. But how I can mandate the password must contain alphanumeric etc etc... Please help me in this regard.

You can use the 'password_confirm" #type in your form to get the exact field Drupal uses.

Add this to your Form function.

$form['account']['pass'] = array(
      '#type' => 'password_confirm',
      '#size' => 25,
      '#description' => t('To set or change the password, enter the new password in both fields.'),
    );

This will give you the field, javascript and the validator without any extra code.


Title Patterns was printed in exactly its self Look at image:

If you look to image, you will find a [current-page:page-title] | [site:name] patterns was printed, not replaced to real site name & node title ...etc, I dont know what is wrong was happens...

Token module, Page-title module was enabled, also when i try to change
 PATTERN, its give me an error
 invalid tokens: [current-page:page-title], [site:name].  invalid tokens: [current-page:title]  invalid tokens: [site:name], [site:slogan]. (for front page)

Also, Im clear cach, and run a cron, and trancate table cashes from database manually ....

thanks a lot

I think you should use [current-page:title] instead of  [current-page:page-title]

Run cron manually and clear the performance cache. If it doesn't help then
Reload the same version of the Token module. If you use drush, command is:

drush dl token-[version]


Custom block automatically adds code when edited in admin I have written some HTML in custom block, but every time I open the editor in Drupal Admin UI some extra code is added to the block. Essentially, this means I have to remove the added code every time I want to edit the file which is becoming quite annoying. I am using Drupal 8 on the Acquia Cloud. Does anyone know what might be the cause of this?

Edit 1:

I'm using CKEditor

My HTML goes from this

Test

       <button>

       </button>

Sign In

Sign up

To this

Test

      <button></button>

      <button></button>

Sign In

Sign up

Edit 2:
I'm also getting the following code added to a second block

&nbsp;

<button aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarSupportedContent" data-toggle="collapse" type="button"></button>

The data-entity-type & data-entity-uuid properties are added with  WYSIWYG fields when you have the Track images uploaded via a Text Editor filter . This filter is designed to track usage of images as they are dropped into HTML body fields and update the fields accordingly when the image is updated.

To disable it, navigate to the Text formats and editors admin section and configure the format that's being used for your custom block. Untick the Track images uploaded via a Text Editor filter option and click the Save configuration button to disable the filter.


Change parent of multiple child pages I have a page with many child pages. And I have a task: there's needed to change parent for all of this child pages. I can move single page using "node hierarchy > Parent > Enter the title of the parent node." and write wanted node title there, but I can't use it for many pages. Is there solution for this problem? I tried to google it, but find nothing.

I'm assuming your parent-child relationships are done through an Entity reference field on the child node pointing to a parent.
As always there is more than one way of solving it in Drupal but one popular way is to use the Views Bulk Operations (VBO) module.
The module Views Bulk Edit helps to speed it up by showing the field options to update.
The procedure is to create Views where you can see all the child nodes among the results. It can be all nodes of that type, or you can even create it specifically for one parent node where its children nodes are automatically filtered.
VBO allows you to add a Field to your Views that shows up as a checkbox next to each result row. It also adds an Action you can trigger on the chosen rows.
With that configured you will be able to choose nodes from your results and edit them in bulk.


Make a field in a Views block visible ONLY to the acccount/profile owner The profile owner (currently logged in) sees this (contextual filtered Views block):

CURRENTLY, the other logged in users who visit test_user2's profile page see this:

What I want to achieve, is for the other logged in users who visit test_user2's profile page to see this:

In other words, I want only the account/profile owner to see the Edit field (/user/[nid]/edit) on their own page and to be able to edit his/her profile info. How to do this?

Create the block without the edit link. Then implement function hook_views_pre_render in your theme.

  This hook is called right before the render process. The query has
  been executed, and the pre_render() phase has already happened for
  handlers, so all data should be available.

  Adding output to the view can be accomplished by placing text on
  $view->attachment_before and $view->attachment_after. Altering the
  content can be achieved by editing the items of $view->result.

  This hook can be utilized by themes.

Within this you do a conditional check to see if currently logged in is the same as profile owner, then if so add the link to $view->attachment_before

I think you would get quite a lot of answers on this question as there are so many ways to do it.

If you want to do it without coding I think you might get it right with Views arguments in filters installed. You create the link field in an attachment to the block using the currently logged in user as contextual filter, then (via installed module referenced) do the conditional check in your filters section of views on this attachment.


Creating a new content type places random options on the content type page I've created a new content type with multiple radio buttons.

Like this:

  1) Is this your first survey?
      o yes   o no
      2) Is the color yellow?
      o yes   o no
      3) Tomorrow is friday?
      o yes   o no

But when I go to the content type page I see this:

  1) Is this your first survey?
      o yes   o no
      > Authoring information
      2) Is the color yellow?
      o yes   o no
      3) Tomorrow is friday?
      o yes   o no
      > Publishing options

The "Authoring Information" and "Publishing options" just appear randomly, and they don't exist in the "manage fields" area. Where are these options coming from?

Those options are shown to the administrator users by default; if you log in as a regular user, you don't see them. You can enable and disable them in permissions "node / administer content".


Add CCK field to panel / page (from page manager) Working in a D6 site, I was asked to add the CCK field that appears in all nodes, which is a taxonomy term reference, a tag, to a "Landing Page" created using page manager and panels. Is that even possible? If yes, how would I go about doing that?

In short, no. Pages are not entities (or nodes in D6) and so cannot have fields, CCK or D7 core, on them.

It's possible that FAPE does what you want, since it allows you to stick an Entity directly into a Page, but that's D7 only.


How to update multiple fields using ajax? In content type there are three field . Each field are node reference to different content. Here I want to restrict value and create dependency on these field.
For example: I have one auto complete field "Country". On change of "Country", select list(i.e. State) field value is updated. On change of "State", "county" field is updated.
Everything is working fine.

When I change value of "Country", "State" value get change But "county" value hold previous value. How should I achieve this. How should I reset value of county

My code snippet is like

function module_form_alter(&$form, &$form_state, $form_id) {
  $form['field_country'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => '_state_list_callback',
    'event'    => 'change',
    'wrapper' => 'state-list',
    'progress' => array('type' => 'throbber', 'message' =>  'Please wait...'),
);
  $form['field_country']['#prefix'] = '
';
  $form['field_country']['#suffix'] = '
';

  $form['field_state'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => '_county_list_callback',
    'event'    => 'change',
    'wrapper' => 'county-list',
    'progress' => array('type' => 'throbber', 'message' =>  'Please wait...'),
);
  $form['field_county']['#prefix'] = '
';
  $form['field_county']['#suffix'] = '
';
}

function _county_list_callback(&$form, &$form_state) {
  return $form['field_county'];
}

function _state_list_callback(&$form, &$form_state) {
  return $form['field_state'];
}

You can use ajax_command_replace() when replacing more than one element/field. Check this ans. The answer says as:

  Instead of returning the HTML of the single element to update, your
  ajax callback can return an array of ajax commands. So it can return
  two ajax_command_replace to replace each element.


How change widget of a "between exposed filter" to combo box? I have a view that has some exposed filters. One of the filters is on the price of the content type. I want to filter contents by price when price is between two known value. For example I want to filter all the content that their prices are between 0 and 5000. The other thing I want is a select box for this filter. So the filter is a select box with some options like below:

<option>0-5000</option>
<option>5000-10000</option>
<option>10000-15000</option>
<option>15000-20000</option>

I add a filter to the view and mark it as exposed filter, then change its operator to between. Now what should I do to change the widget from two text box to a single select box?

You're close. After you expose the filter, change it from Single filter to Grouped filters using the radios right below the expose checkbox. Then you can define what each option is and make it a select box.


Changing Field Display Properties I'm using Drupal 7, and I have a node type that has an image and body text.  I want the display for this node to display the image inline with the text (ie, apply float:left to the image).

Is there any way for me to do this through the frontend, or will I have to manually change the CSS for the image field's class?

Some themes can do this for you out of the box. See AdaptiveTheme as an example -- you can float an image field inline the body field.

I believe with DisplaySuite you can also show fields inline.


Removing all 'stable' theme's CSS from a Drupal 8 custom theme I would like to remove all CSSs automatically included from stable theme:

/core/themes/stable/css/system/components/*

I can remove them one by one inside the .info.yml file:

stylesheets-remove:
  - 'core/themes/stable/css/system/components/ajax-progress.module.css'
  - 'core/themes/stable/css/system/components/autocomplete-loading.module.css'
  - ...

Is there a way to remove all of them at once?

Something like:

stylesheets-remove:
  - 'core/themes/stable/css/system/components/*'

There's no wildcarding for the stylesheets-remove (FYI: there's a FR out there for it). However, you can use libraries-override to remove the library associated with the all CSS components you've highlighted:

libraries-override:
  system/base: false

It won't remove all CSS files in the stable theme, but it will condense removal of libraries that contain many CSS files.


Putting a form into a menu I've started learning Drupal (I'm starting with Drupal 7) and the best way to do that seemed to me to be in creating a custom theme from scratch.

I'm trying to create a menu in which the login form is displayed if the users are not logged in and the user menu if they are logged in. How do I go about doing this in proper Drupal fashion?

Drupal already has a login block, which displays the login form, which by default only is displayed for anynomous users. So all you really need to do is add a block with the User menu (all menus has a block with the items) next to the login block and have it show for only authenticated users.

This is one of the things where configuration will get you all the way.


Last modified using format_interval I would like to show interval time for nodes were last modified. I am using the following code:

<?php print "Last Modified" . format_interval($node->changed, $langcode, "short"); ?>

I am using $langcode as proposed here to display it in Arabic, but it is not working and I am not sure if I am using it the right way because I get this error Notice: Undefined variable: langcode in include()

Whenever I update any content; interval time still set to 0 sec, so what is wrong with the code?

Your code contains two errors:

You are using a variable which has not been initialized
You are passing the wrong arguments to format_interval()

The required arguments are:

$interval
It's not a timestamp, but the number of seconds until now. In your case, you should use time() - $node->changed.
$granularity
It's the number of units that are shown; if you pass 2 as value for $granularity and the interval is for 1 year, 3 months, and 2 weeks, format_interval() will return "1 year 3 months".
$langcode
It's the language code for the language to use. If you are hard-coding the language to be Arabic, you should use "ar".


Comparing a clicked views-row in a loop When I loop through my .views-row divs in jQuery, I need to 'grab' the one that is clicked on, needing to uniquely identify it and put only the selected fields from that particular div in my modal frame. Now I have the selected fields of all the divs within that loop in my modal frame.

I don't think I'm too far off with the following here below. I think the only thing that's missing is that I haven't been able to properly 'say' to drupal which div is being clicked and see to which views-row-number it corresponds to in order to display only that one in the modal frame.

obviously jQuery(".views-row .views-row-" + index).click() isn't the way but I'm sortof out of ideas which one that would be then.

jQuery(document).ready(function(jQuery) {

    row = jQuery(".views-row");

    row.each(function(index){
        forModal = jQuery('.forModal');
        forModal.hide();
        jQuery(".views-row").click(function(){

                if (jQuery(".views-row .views-row-" + index) ==
                                jQuery(".views-row .views-row-" + index).click()){
                                 forModal.modal();
                }

        });
    });

});

I think you're making that a bit harder than it needs to be...if I understand you right anytime a row is clicked you want to identify that row, extract a field from it and display it in a modal?

If so something like this would be a bit simpler:

(function($) {
  $(function() {
    $('.views-row').click(function() {
      // Find the modal within this row and show it.
      $(this).find('.forModal').modal();
    });
  });
})(jQuery);

Sorry if I've mis-understood what you're looking for, I wasn't 100% sure.


exposed filter autocomplete suggestions sort I have more than 10 terms in vocabulary: car, red car, blue car, yellow car etc.
I know that 10 results is hardcoded value for autocomplete widget. My problem is that after typing "car", I only get various other terms, simple "car" is not in suggestions.

How does the autocomplete widget work?
Is there any way how to sort/alter results? Why it does not show the exact term first "car" and then all other terms containing "car"?

The filter handler class views_handler_filter_term_node_tid uses the autocomplete path admin/views/ajax/autocomplete/taxonomy and is driven by the callback views_ajax_autocomplete_taxonomy().

This autocomplete callback explicitly excludes the term typed in and doesn't do any explicit sorting (thus defaults to whatever your RDBMS does):

$query = db_select('taxonomy_term_data', 't');
$query->addTag('translatable');
$query->addTag('term_access');

// Do not select already entered terms.
if (!empty($tags_typed)) {
  $query->condition('t.name', $tags_typed, 'NOT IN');
}
// Select rows that match by term name.
$tags_return = $query
->fields('t', array('tid', 'name'))
  ->condition('t.vid', $vid)
  ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
  ->range(0, 10)
  ->execute()
  ->fetchAllKeyed();

If you'd like to alter the results or how it's sorted, the query is using tagging, thus available for altering via hook_query_alter().


Adjusting the month being viewed on the Calendar Block to match the month of the Day being viewed So, I am using Drupal 7 with the Calendar Module. I am using the calendar block as the primary calendar for viewing events daily events. Everything works great, except the calendar block doesn't change its month being viewed to match the day being viewed.

For example. The calendar block is visible and starts at the month of November (because it is November). You browse to December and click on a day to view that day's events. The page loads and shows the events for that particular day in December, but the calendar block defaults back to November. I want it to show December since I am viewing a day in that month

Is there a way to have the calendar block show the month that matches the day being viewed?

Have you tried to set "track current date in session" under admin/config/date/calendar?

This should do the trick...


How can I hide field labels without using any CSS style? How can I hide field labels from Drupal (without CSS)?

function clean_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "user_register_form") {
    $form['account']['name']['#title'] = Null;
    $form['account']['name']['#description'] = Null;
    $form['account']['name']['#attributes'] = array('placeholder' => t('Имя пользователя'));

    $form['account']['mail']['#title'] = Null;
    $form['account']['mail']['#description'] = Null;
    $form['account']['mail']['#attributes'] = array('placeholder' => t('mail'));
  }
}

I don't know how to write for password and date.

Go to "Admin > Content Type > Manage Display" and hide the labels as shown in the screenshot.


Currency resolver - Cache problem on platform.sh I'm using currency resolver (commerce) based on cookie to switch currencies in block (have a custom field for usd price in price variant). Locally everything's work fine (apache) but on platform.sh switcher block is not working.I think it has to do with some server caching (internal cache is disabled in drupal). I tried to add some yml config on platform.sh for disabling cache but without result. Did anyone have similar experience with this?

Thanks

Solution is to add cookie to routes.yml file in .platform folder and than push it to the platform branch. After that currency resolver will work.


Sending webform submissions to email with csv export of submissions I need help, because I dont know how to create csv file from submissions and send it as attachment in submission mail.

I have form with some field and after sending webform I need to create custom csv in specific format with values from webform and all this send it like attachment of normal submission mail.

Is there some modul for creating csv from webform, or I need to cook my own custom module to create it?
Thanks a lot

As tenken wrote, Webform module has a function for that, namely webform_results_export

Do you really want a single line of CSV e-mailed when a form is submitted, rather than periodic downloads?  You could modify your e-mail template to print each value, comma, value, but it wouldn't be an attachment.  If you absolutely need an attachment some custom code and/or Rules is the way to go.


How to make taxonomy term checkbox display multicolumn? I have about 20 items for checkbox. Drupal default checkbox is too long down. How to make it in to column like this?

[ ] list1  [ ] list4  [ ] list7  [ ] list10
[ ] list2  [ ] list5  [ ] list8  [ ] list11
[ ] list3  [ ] list6  [ ] list9  [ ] list12

You can accomplish this using CSS, specifically flexbox. The exact element you need to target with your CSS rules will depend on your theme. You will need to add the following CSS to the element that contains your checkbox items.

.container {
  display:flex;
  flex-direction: column;
  flex-wrap: wrap;
  height:20vh; /* You will need to set a height on the container
                  to get the look you want, this is an example height */
}

In my example, I'm using Drupal 8 and the Seven administration theme. On an add/edit node page, I have a taxonomy field (the default tags) using  checkboxes. You can see in the below image that each checkbox element is wrapped in a div and all of those divs are wrapped in a container div with the id edit-field-tags. So, if I apply the above CSS to that container, I get the results that match your goal:

You may want to play around with the alignment or spacing of the flex elements, for more information on that that I recommend checking out "A Complete Guide to Flexbox" on CSS Tricks.


Views: How to display the title and breadcrumb from taxonomy terms in URL? I have a Page display in a View. The page url is taxonomy/term/xx and I am trying to display the term as the page title and the breadcrumb.

I have tried to set the term as an argument Content: Has taxonomy term ID with the following settings, I checked Set the breadcrumb for the term parents but it did not work. Can someone help?

By default, taxonomy terms default view is disabled so you can enable it and see how it is working with the contextual filter.

You need to Configure contextual filter: Content: Has taxonomy term ID (with depth)


How to open product detail when user click on product image? I am new in Drupal and I am working on one commerce website using drupal commerce module.

The problem is arise in my website is-->

I am used views for display products with product image,title, price etc fields.

But I want to know that when user click on product image the new page will open and in that page display 3 related images of that product with detail information.

I want to give link for product image to open that clicked image product with detail.

Please help me to solved this problem...!

In view add "nid" fields before image field and make exclude from display.

Click on image field.
Go to "Rewrite Results" section.Check "output this field as link" .In the "link path" put the 'nid'. It will take you the details page of product.
...

You can also create tpl file for product content type details page.
Enjoy


Why can't I edit "Settings" on rules components in the Rules UI? When I click to edit a rule in the Rules UI, "Settings" is displayed in blue and upon clicking "Settings" the "Name", "Tags", "Active" and "Weight" options are presented.

However, when I click to edit a rules component, "Settings" is displayed in black and I cannot edit the name of the rule nor the arguments.

Before, I solved this problem by:

clearing the Drupal cache (twice)
clearing the cache in my browser and restarting it
switching to a different browser (e.g., from Firefox to Safari)

However, this time none of the above worked.  How can I edit the settings for rules components?

I had this problem when using entity-rc1.  Upgrading to entity 1.0 resolved the issue for me.


Reset button is not working after previewing the webform Reset button is not working after previewing the webform.
Means when we click on preview button on webform, then on edit button of webform and then if we click on reset button. it does not work at all. What could be the reason, kindly suggest any solution?
My code is as follows :

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

  switch ($form_id) {

    case 'webform_client_form_XYZ':
        $form['submitted']['reset'] = array(
            '#type' => 'button',
            '#value' => t('Reset'),
            '#weight' => 100,
            '#validate' => array(),
            '#attributes' => array('onclick' => 'this.form.reset(); return false;'),
        );
   }

Your code works as designed - resets form to a state it was at page load. After preview state JavaScript resets to is set to what user entered. That's not a Drupal issue, that's just how JavaScript and browsers works. Browser simply does not have that data any more - HTTP is a stateless protocol even if we work around it every day and don't even consciously notice that we do.

If you want that button to do something else, you need to use Drupal's AJAX and obtain values you want to reset to from the server directly. Alternatively, you can attach custom submit handler to that button, one that would not really submit anything, but clear data from $form_state['input'] and trigger form reappearing.


How to solve the apostrophe problem in node title? (' -> ') Node title includes ' (apostrophe) and it appears normal while viewing the node. But in page source it appears as &#039;.

And for the same reason when I want to share this node on Twitter with some custom code put into node.tpl.php (<?php print urlencode($title) ?>) it also shows the ' as &#039;.

How to solve this problem?

Your issue seems similar to what's written in issues such as this or this.

The solution appears to be to use decode_entities, e.g. something like this:

$node->title = decode_entities($node->title);


How do I provide one-time access to a downloads page to anonymous users? Our company wants to have a secured downloads area for software.  We want to send a link to a customer via email, after they have purchased a license for the software.  We don't want to create a site account for every customer; we just want them to click the link to get one-time access to the downloads page.  All the modules I have seen for one-time use links either assume that the link is something used for password reset, etc., or the module is not ready for prime-time.

Any ideas?

Thanks!

You need write a module to do this job,
I wrote a module that do something like this ( count download times )

<?php

/**
* Implements hook_menu();
*/
function bicuk_downloadounter_menu() {

    $items=array();
    $items['download/%']=array(
        'title' => 'increase Download counter ',
        'description' => t('callback url for increse Downloading count'),
        'page callback' => 'downloadcounter_tickup',
        'page arguments' =>array(1),
        'type' => MENU_CALLBACK,
        'access callback' =>true,

    );
    return $items;
}

/* call back function to increase counter
 * @param $fid , file id
 */
function downloadcounter_tickup($fid){

   if(!is_numeric($fid))
              drupal_goto();
   $file=file_load($fid);
   if(!isset($file->fid))
            drupal_goto();
   $acceptable_ext=unserialize(variable_get('bicuk_downloadounter_valid_extensions'));
   $file_path=file_create_url($file->uri);
   $pathinfo=  pathinfo($file_path);
   $extension=$pathinfo['extension'];
 if(!in_array(strtolower($extension), $acceptable_ext))
             drupal_goto();
   $query=  db_select('bicuk_downloadcounter_counter','bdc')->fields('bdc',array('count'));
   $query->condition('fid',$fid, '=');
   $count=$query->execute()->fetchField();
if($count)
{
    $query=  db_update('bicuk_downloadcounter_counter')->fields(array('count'=>$count+1));
    $query->condition('fid',$fid, '=');
    $query->execute();
}
else
  {
    $query=  db_insert('bicuk_downloadcounter_counter')->fields(array('name','count','fid'),array($file->filename,1,$fid));
    $query->execute();
  }
   drupal_goto($file_path);
}

/**
 *
 * @param type $fid fid
 * @return type int count
 */

function downloadcounter_get($fid){
   $query=  db_select('bicuk_downloadcounter_counter','bdc')->fields('bdc',array('count'));
   $query->condition('fid',$fid, '=');
   $count=$query->execute()->fetchField();
   return $count;
}

you can  get idea from this code to achieve your job,instead of counting download time try to check downlading time by IP and do your limitation


How to allow the banner to be editable via front end? In the BlueMasters 6.x theme, the banner is hard-coded inside page-front-tpl.php:

  <?php //print $banner;?>

 Event One

 Event Two

 Event Three

      1
      2
      3

How can I expose the above banner div such that it reads from a particular page's (Full-HTML) content, instead of hard-coded. Such that the user can change the banner without FTP/SSH access.

You have two ways without coding:

Use Nodeblock to create nodes for banners. Give users right to edit nodes and place them where you need them as a blocks.
Use Views to create a block displaying (random?) node of content type banner. Give your users right to create, delete and edit them.

You could also use Advertisement module, but for a simple case like this it's an overkill, I think.


How to reinstall Drupal? Can anyone tell me the best possible way of how to reinstall Drupal 7 from ubuntu 13.04? After googling came through many options that is making me confused!

You can do it with the following steps too :

Go to http://localhost/phpmyadmin
Select your database and drop all the tables
Go to http://yoursite.com/install.php

Or you can use : drush si

And done.. :)


How to use views to display different information sources On my home page I want to have a series of 'blocks'. Here is a graphic illustrating what I would like to achieve

The first two would be updated with the latest two blog post, the third would be the Facebook feed iframe, then the last three would be images promoting a different page on the site via a link.

I currently have each of these blocks prepared as separate views. Each of these are hard-coded into page.tpl with views_embed_view(). This isn't ideal as I want to be able to easily add and remove these boxes from within the Drupal admin.

How do I create a 'master view' to display on the front page that will hold these separate views?

It seems there are many ways to achieve the same result in Drupal. In the end I went for 'Context'. By using 'Panels', it does not appear to be flexible enough to easily add extra blocks when needed.

Set the condition to <front>
In reaction add blocks
Then drop in all the required views into content


Problem with Aggregate CSS files option and tmp directory This issue has been asked at lots of places and posts, but none of the solutions I found helped me.

I moved a dev site to a server where it is going to go live. Right away I was puzzled why I had to manually create a tmp directory at the site root to get it working at all.

On the dev site, I had been running with the Temporary directory set to /tmp (note the leading slash), but on the new hosting the site forces me to remove the slash, complaining about SAFE_MODE.

The main problem though is that - even though the tmp directory is there and is writeable - turning on the Aggregate and compress CSS files. option causes the site to go into plain, no-stylesheet mode. The Aggregate JavaScript files. companion works just fine on the other hand.

I made sure the encoding of the CSS files is UTF-8 without BOM, as one of the posts suggested. Still - no go. Does anybody have a clue?

As per Drupal PHP requirements, safe mode should be off.

It will interfere with file uploads and possibly email sending as well.

You'll probably find you need, in all the .htaccess places with:

Options +FollowSymLinks

to change to

Options +SymLinksIfOwnerMatch

In any case, if you can't disable PHP "safe mode" which, according to php.net is deprecated

  Safe Mode
  This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP
  5.4.0.

and the other options don't work - you may need to consider using another webhost.


Using Views and Date module in Drupal 7 - Limiting Filter Options I am creating an event calendar for a festival where user's can log into the site, click "Add new event" and create an event.  I have 2 questions regarding dates.

When the user creates the event, rather than a standard date popup, I'd like for them to be able to choose a range of days (Thursday - Sunday) and a time, rather than the calendar popup or Day/month/year hour minute drop downs.  Is there an easy way to limit this, of even prevent the user from selecting dates outside a certain range?
When showing the events list, I've created a table view.  I'd like to allow the user to select which days to display using an exposed filter.  If I choose "Event date" it only allows me to display a standard date field in the filter (Month Day Year).  I want the user to be able to select "All, Thursday, Friday, Saturday or Sunday" instead.  I was able to add "Day" as a field in the view, and group by the DAY, It just seems I'm not able to then filter by it.

I hope this makes some sort of logical sense.  Thanks in advance for any help.

currently "date" module doesn't allow to satisfy this needs

I see two solutions for the first question:

1) Develop a custom module in order to create this type of interaction.

2) A quick and dirty alternative is to alter the dropdown content using JS, but a custom module would be miles better.

Sincerely I'll suggest the first one.

About the second question you could expose the day filter and populate it substituting the form filter with a custom one, for example hiding the original form filter with CSS (display:none) and adding some hand crafted links with the URL parameters on the views header area.

Good work!