Problem with restricted download links (hook_file_download) On my site I have a bunch of files that require logged-in user for download access.
Well that's not about just display access, I also want to avoid passing download links around.

Having read about the performance implications of using private file system, I decided I cannot afford it so I thought I'd write a small module to control the download.

The code looks like the following:

/**
 * Implements hook_permission().
 */
function docwatch_permission() {
  return array(
    'docwatch download restricted documents' => array(
      'title'       => t('Download restricted documents.'),
      'description' => t('Download technical documents from secured directory.'),
    ),
  );
}

/**
 * Implements hook_file_download
 */
function docwatch_file_download($uri) {
  if (strpos(file_uri_target($uri), 'secure/docs') !== 0) {
    if (!user_access('docwatch download restricted documents')) {
      // Access to the file is denied.
      return -1;
    }
    else {
      return array('Content-Type' => file_get_mimetype($uri));
    }
  }
}

And I'm using this debug code to inspect what Drupal "thinks" of the link to the file it displays:

function MYTHEME_file_link(&$variables){
  $file = $variables['file'];
  $uri = $file->uri;

  if (strpos(file_uri_target($uri), 'secure/docs') !== 0) { // <-- part of the secure dir path
    if (!user_access('docwatch download restricted documents')) {
      drupal_add_js("console.log('no access')", 'inline');
      // Access to the file is denied.
      // return -1;
    }
    else {
      drupal_add_js("console.log('ok to download')", 'inline');
      // return array('Content-Type' => file_get_mimetype($uri));
    }
  } else {
    drupal_add_js("console.log('from unsecured')", 'inline');
  }
}

I then open a page where the link is displayed in two browsers, one with a logged-in status for that role, and the other - plainly anonymous. The console properly reports that difference, yet - despite that the anonymous browser is permitted to download the direct link to the document.

What am I doing wrong?

Having read about the performance implications of using private file system, I decided I cannot afford it so I thought I'd write a small module to control the download.

The performance hit from using the private file system is minimal.

IMHO, using the private file system to control download access to files is the only sane way to do this when using Drupal.

  What am I doing wrong?

You err in not using the private file system .

When you hand the direct link to the browser, it goes directly to that link.  It does not even see the PHP/JavaScript you've put in place to restrict download access.

To prevent unauthorised downloads, you must enforce that the downloads are managed by Drupal, and that this access control cannot be bypassed by requesting direct links served by the browser. This is what the private file system (aka private download method) does.

This download method stores the files attached to a node in a directory that is not accessible by the browser (preferably above the web-root). The only way to get to these files, are then through Drupal.


How to use Tokens [current page arguments]? I dont know how to use tokens to get arguments from url.

I have url: site/country

On this page i have links to terms, i want them to have in alias first argument from current page /country/term-name.

But instead of this my terms have alias /batch/term-name
Can i have a little help and show me a little example of how to use tokens of current

If you want to use tokens with taxonomy terms urls you have to enable token, pathauto and Chaos tools module. You can do it by runing drush command
drush en pathauto -y
After these modules are enabled go to admin/config/search/path/patterns

Hope this is what you asked about.


How to display custom content when viewing node? I am using the Biblio module and I like the display mode (e.g. full, teaser).  I would like to tack on custom text and information when a user views the content below the display.  How do I append my own custom text in the current display?  When I go to "Manage Display", the custom fields are not shown.  It might be hard coded in the module.  What Drupal API call should I be looking for? Or better yet, I am perfectly willing to write my own module.  I just do not know where to start in adding my own additions to an existing display.

An example is the comment module.  When someone leaves a comment, then you can see the comment someone has written that is tied to the specific node and/or content type.  I am not talking about creating a user input form or input HTML field.

I resolved it by using hook_node_view() to append to the $node->content object.


State: are they permanent? I'm using StateAPI to store some variables that shouldn't be exported as configurations.

These values are stored in the database, in the key_value table.

Is this a "secure" table? Are there tasks (cache-clear or other) that could automatically remove values from this table?

Is it a good idea to create a custom form to let users to set some states?
They could be simple strings, or url, and I think that create nodes for this information is too "heavy".

Is this a "secure" table?

Depends on what you mean by secure.

  Are there tasks (cache-clear or other) that
  could automatically remove values from this table?

No.

  Is it a good idea to create a custom form to let users to set some
  states?

This is kind of looking at it from the wrong direction. States are a solution to an issue. If you have something that is to be stored, for which states are a good solution, then they are good to use. In other words, if you have a form that does something that states would be good for, then use states. Deciding to use states then creating forms for them doesn't really make sense.


How to get rid of a style attribute so my nivo slider will show up? I am using the Nivo Slider and for some reason it has a style attribute in its div tag that says

style="width: 0px";

I am trying to get rid of this so my slider will appear. I am not sure where this is coming from. I have CSS injector installed, but none of it makes a width: 0px and a grep search throughout the directories doesn't come up with one that will effect the outcome.

Thanks for your help.

https://www.drupal.org/node/229348 Gives a lot of good information on the subject.


Do something in hook_node_load only when displaying node Is there a way to run a specific block of instructions in hook_node_load only when the node is loaded do be displayed and not when it's loaded in the edit form?

The only way I can imagine is analyzing the url and if the pattern is node/%/edit don't execute the code.

I know I can also use hook_node_view, but in this case I have to add render arrays instead of simple values

Yes, you'll need to examine the URL for this.

Loading a node is (correctly), completely de-coupled from displaying a node. node_load() doesn't know what you've loaded the node for; it doesn't care, its only responsibility is to prepare the node object.

So the context you're looking for doesn't conceptually exist when hook_node_load() is invoked, as that by definition has to happen before the object is passed to node_view(), and there's no way to signal your desired intent to node_load()


drupal 7 - views conditional not working I have a content type that has an External Link (field type: Link) which is an optional field. So users can either type in a url or not. I've created a View where I want to show the latest 2 content types.

I want to be able to display the nodes where its Title either links to the External Link or the url of the content. I already have Views Conditional enabled but I dont think Im setting it up correctly because the nodes arent using the proper url. The url is "http://localhost.test:8888/[path]. The 2nd node is correct though, it has http://yahoo.ca which is the External Link that I used.

If anyone has any clue why the settings arent correct, please let me know why. THanks.

If I correctly understand your point, you would like a view to display two latest nodes of a specific content type. While displaying these nodes the view should check:

External link is provided or not

If External link is provided then output that as a field of view, if External link is not provided then output the URL Path of the content.

I can achieve this with just Views without the need of the Conditional one, unless I am misunderstanding your questions. I have the following steps for you to achieve what I stated here,

Create a content type with link field and either Pathauto or custom URL supplied
Create a view with content type as the one created
Choose Field for Format Show and the select whichever field of the content type you are interested including the External Link & Path fields
Click on the external field link, once opened change the title to New Title or whatever fancy
You would need to use the NO RESULT BEHAVIOR settings of this field
In NO RESULT BEHAVIOR supply the placeholder for PATH which is [path] - The path should be included among the fields
Save and there you go the result, if the node is not having an External link then it will display the path as value of external field, otherwise it preserves the supplied external URL. Screenshot for more detail

Create content types as follow:

Configure view as follow

Configure the NO RESULT BEHAVIOUR as follow

There you go the result of your view, first content types does not have external URL and the second content types does have (don't forget to include the path as one of the fields or you won't be able to access it)


How to properly manage field types for a content type created by a module? I'm a bit confused about two different errors I get, which seem to contradict each other. I guess I didn't register my field types properly. The first one appears when I try to uninstall my module.
Drupal\Core\Field\FieldException: Attempt to create a field field_example that does not exist on entity type node. in Drupal\field\Entity\FieldConfig->getFieldStorageDefinition() (line 312 of core\modules\field\src\Entity\FieldConfig.php).

The second one appears as an error message within the UI when I try to fix it by introducing another module which should only create the field type.
Unable to install Helper, field.field.node.content_type_example.field_example already exists in active configuration.

In general, the module calls an external API and fetches data which is then used to create nodes with several fields. These are defined inside the config/install directory. Furthermore, inside src/Plugin/Field there are FieldType, FieldFormatter and FieldWidget classes, more or less as described here.
I used this module when I tried to fix the first error without a helper module. With its help, I removed the field types created by my module in the first place. Unfortunately, I don't know a lot about drush, which seems to be capable of solving the issue. On the other hand, it would be great if it was possible to "reset" the content type and the field types programmatically whenever the module is installed or uninstalled. So far, I tried the following code, without much luck:
<?php
// mymodule.install file
use \Drupal\field\Entity\FieldStorageConfig;

function mymodule_install() {
  if (FieldStorageConfig::loadByName('node', 'field_example')) {
    FieldStorageConfig::loadByName('node', 'field_example')->delete();
  }
}

Does someone know how I can fix the error and how I should manage these fields in the future? Thanks!

To properly manage fields added by a module, so that a field is added and removed when the module is installed and uninstalled, add an enforced dependency for your own module to the yaml file:
/config/install/field.storage.node.field_example.yml
...
dependencies:
  enforced:
    module:
      - mymodule

See https://www.drupal.org/node/2404447


Is it possible to translate the suffix of an integer field? Is it possible to translate the suffix of an integer field? The prefix/suffix settings doesn't appear under the translate section for the field. And I tried searching for the string in "Translate interface" with no luck.

The field is being used in a view where all the fields are in a list, any alternative solutions are also welcome.
Using Drupal 7.

I didn't find a solution to actually translate the suffix. Instead I added a rewrite of the field in the view where it was used, and rewrites show up in the translate settings in the view.

So the solution is, don't use a suffix. Instead add a rewrite option to the field where you use it, and translate that rewrite option instead.


Dump-dir specified in aliases.drushrc.php; not seen by drush? The remote and local directories I've specified in my aliases files exist and are owned by my user (drush is run under my user).

$aliases['dev'] = array(
 'parent' => '@parent',
 'site' => 'mysite',
 'env' => 'dev',
 //[user, host, ssh options, etc.]
 'path-aliases' => array(
    '%files' => 'sites/default/disk',
    '%dump-dir' => '/home/joe/drush-backups/mysite_dev',
    ),
);

$aliases['local'] = array(
 'parent' => '@parent',
 'site' => 'mysite',
 //[root]
 'path-aliases' => array(
     '%files' => 'sites/default/files',
     '%dump-dir' => '/Users/joe/Sites/mysite/tmp',
    ),
);

Yet I get a warning on sql-sync:

  drush -v sql-sync @dev @local Loaded alias @local from file
  /Users/joe/.drush/soa.aliases.drushrc.php
  [notice] Loaded alias @dev from file
  /Users/joe/.drush/soa.aliases.drushrc.php
  [notice] Local sql cache file does not exist.
  [notice] ssh -i "/Users/joe/.ssh/id_rsa" -p "6421"
  joe@arch-web-p01.its.utexas.edu 'drush  --backend=2
  --root=/var/www/html/dev  sql-query '\''SHOW TABLES'\'' 2>&1' 2>&1                                                                                [notice] WARNING:  Using temporary files to store and transfer
  sql-dump.  It is recommended that you specify --source-dump and
  --target-dump options on the command line, or set '%dump' or '%dump-dir' in the path-aliases section of your site alias records.
  This facilitates fast file transfer via rsync.

  You will destroy data in drupal_test and replace with data from
  server/mysite_dev.

  You might want to make a backup first, using the sql-dump command.

And if I continue, I get an error that indicates drush was trying to write to a different directory.

  Do you really want to continue? (y/n): y Calling system(ssh -i
  "/Users/joe/.ssh/id_rsa" -p "6421" joe@server 'mysqldump --result-file
  /private/var/folders/mr/c99kf6c11_bdsr62m242c59c0000gq/T/mysite_dev1WyWuk
  --no-autocommit --single-transaction --opt -Q  mysite_dev --host=myhost --user=mysite_dev --password='\''[pw]'\'' --skip-extended-insert --order-by-primary  2>&1'); mysqldump: Can't create/write to file
  '/private/var/folders/mr/c99kf6c11_bdsr62m242c59c0000gq/T/mysite_dev1WyWuk'
  (Errcode: 2) Database dump failed
  [error] Command dispatch complete
  [notice]

I've got all my drush commands working between remote directories run on the site. I am able to rsync between local and remote directories since specifying files path aliases in aliases.drushrc.php.

What am I missing?  I have the latest version of drush in both places, so I don't think I need the patch pointed to at How do I set the drush tmp directory?...

FWIW, I finally resolved the error by including the --source-dump option in the command line. I specified the same directory I had listed in my aliases file, and it created the dump file there flawlessly. So perhaps dump-dir is not being read in 6.0-rc2...


Is there a risk of having xmlrpc.php on my site? I recently noticed that all of my sites have the file xmlrpc.php.

Searching it led me to "Gain Control of WordPress by Exploiting XML-RPC", and also to "Drupal Core - Critical - Multiple Vulnerabilities - SA-CORE-2016-001".

I'm running Drupal 7.56.

Does this file pose a threat whatsoever to my site?
Should I just delete it to be safe?

If I should keep it, what added benefit does it give me?

You are save. At least to what we know now.

The first linked article is wordpress related. This is totally different code. Not drupal related at all!

  Drupal had a known security flaw in versions lower than 6.38 / 7.43 /
  8.04

So your version 7.56 is patched. Always make sure to update to the latest version and you're good.


Pinterest for Lightbox and/or Colorbox Does anyone know if there is a project going on to add Pinterest to Lightbox or Colorbox?

I've been searching for some way of integrating quick share on Pinterest from my website and can't find any modules that work well. Pin It doesn't even work as far as I can tell and Service Links is difficult to figure out.

Plus the solution for Pinning isn't really the same user experience as tweeting a page or sharing on FB. An overlay on an image in lightbox or colorbox would be huge.

I'm just looking for some decent Pinterest solution for Drupal and am surprised I can't find anything.

I used the hook THEME_image_formatter to accomplish this.  It would be fairly easy to create a module to do this I just haven't had the time.  Anyway here is what I did.

function THEME_image_formatter($variables) {
  $item = $variables['item'];
  $image = array(
    'path' => $item['uri'],
  );

  if (array_key_exists('alt', $item)) {
    $image['alt'] = $item['alt'];
  }

  if (isset($item['attributes'])) {
    $image['attributes'] = $item['attributes'];
  }

  if (isset($item['width']) && isset($item['height'])) {
    $image['width'] = $item['width'];
    $image['height'] = $item['height'];
  }

  // Do not output an empty 'title' attribute.
  if (isset($item['title']) && drupal_strlen($item['title']) > 0) {
    $image['title'] = $item['title'];
  }

  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = '';
    // I targeted the blog post image style to add to all blog photos.
    if($image['style_name'] == 'blog_post') {
      $output .= '
';

      $media = urlencode(file_create_url($item['uri']));
      $title = variable_get('site_name', '') .' - '. str_replace('+', '%2B', $variables['item']['title']);
      $path = $variables['item']['path'];

      $output .= '

';
      $output .= '';
      $output .= variable_get('site_name', '') .'
'. $variables['item']['title'];
      $output .= '

';
    }
    $output .= theme('image_style', $image);
    if($image['style_name'] == 'blog_post') {
      $output .= '
';
    }
  }
  else {
    $output = theme('image', $image);
  }

  // The link path and link options are both optional, but for the options to be
  // processed, the link path must at least be an empty string.
  if (isset($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = isset($variables['path']['options']) ? $variables['path']['options'] : array();
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
    $output = l($output, $path, $options);
  }

  return $output;
}

Just pay attention to the blog_post check and output that I created.  I have some javascript that shows and hides the button on hover but you can add that if you want.

Dont forget to add your pintrest JS to the head of your doc.

--Good Luck


How do I put registration form in panel in Drupal 7 I would like to know how to put a registration form or any other form to make a new content type in panels. I know the first thing to do is to put the registration form in a block. How can I do that?

fucntion YOURMODULE_block_view($delta = ''){
  switch($delta){
    case 'YOURBLOCKNAME':
    $block['content'] = drupal_get_form('user_registration_form');
    break;
  }
}

Or if you want to theme the block first, then register a theme hook in YOURMODULE_theme().

function YOURMODULE_theme(){
  $return['custom_user_reg']= array(
    'render element' => 'form',
    'arguments'=> array('form'=> null),
    'template' => 'templates/form--user-registration',
  );
  return $return;
}

function YOURMODULE_block_view($delta = ''){
  switch($delta){
    case 'YOURBLOCKNAME':
    $form = drupal_get_form('user_registration_form');
    $block['content'] = theme('custom_user_reg', array('form'=>$form));
 }

Then in form--user-registration.tpl.php:

print render($form['email']);
print render($form['name']);
print drupal_render_children($form);

Of course you can add as much html in your tpl file as you want/need.


Field help text is printed as input field title, not in separate field On Bootstrap theme add field Text, give it any Help text, save it and you get empty field, but if you hover on the field it shows the help text on mouse tooltip.

But if you e.g. make list field (text) and give it help text, it gets printed in separate help-block div under the field. How do I get that for Text fields or all/any fields?

Try to uncheck 'Smart form descriptions (via Tooltips)' in Appearance -> Bootstrap settings -> General -> Forms.


Drupal 7 - Show Child Taxonomies and content in current taxonomy I have a site that has multiple levels of "Category" taxonomies with varying content within each level.

I have tried for a couple of days but basically i wish to accomplish the following: When a user clicks on a Category view e.g.. /taxonomy/term/% they are presented with a list of child categories and also a list of content items (if any exist) within the parent category.

I have managed to create a view that will show the list of child categories however i cannot combine this with the default term view.

I have attached a mockup of what i wish to accomplish. Any help is greatly appreciated.

Thanks so much for your help.

There are a lot of disabled views that come bundled with Views module (check the list of views). One of those disabled views is a replacement for taxonomy/term/%. So, enable it and do all the modifications you need.

You can attach to the header a view with the list of subcategories, and that would fit your needs.


How to render URL ALIAS field on form? Is there a way to render the URL Alias field on the form separately from the print drupal_render_children($form);?

My plan is to render the URL Alias field on top of the form neatly (before the other fields), bcoz right now its in some sort of box like output that is generated by Drupal.

Any help would be greatly appreciated.

If i understand you in the right way you want to edit path alias when creating new content.
At first you have to give permission to create and edit URL aliases to some user role.

Then just add <?php print drupal_render($form['path']); ?> to your form template (EG. to the top of the form).


Programmatically setting an image field from hook_node_insert (drupal 7) I have a content type that has a file field (which accepts only .zip file) and a screenshot which is an image field and is not displayed on the content submission form.  Instead I have a module that unzips the .zip file from hook_node_insert.  At this point I would also like to set the screenshot to be a .png extracted from the .zip file.  So far I have had no success and I always seem to get an error like this:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '463' for key 'PRIMARY': INSERT INTO {node} (nid, vid, type, language, title, uid, status, created, changed, comment, promote, sticky, tnid, translate, uuid) VALUES (:db_insert_placeholder_0,

Since I was having trouble getting this to work, I tried what I thought might be simpler, I.E. trying to set the node to some image from the web using code like this:

  $image = file_get_contents('http://drupal.org/files/druplicon.large_.png');
  $file  = file_save_data($image, 'public://drupalicon.png',FILE_EXISTS_REPLACE);
  $node->field_screenshot[LANGUAGE_NONE]['0']['fid'] = $file->fid;
  node_save($node);

but I always get the integrity constraint problem listed above.  Could my problem be related to trying to do this from hook_node_insert?

node_save() actually invokes hook_node_insert() so calling it from inside that hook probably isn't the best idea (I'm surprised you don't get out of memory errors doing that actually).

Instead you might want to use hook_node_presave(), which is called before the node and associated data is committed to the database:

function MYMODULE_node_presave($node) {
  $image = file_get_contents('http://drupal.org/files/druplicon.large_.png');
  $file  = file_save_data($image, 'public://drupalicon.png',FILE_EXISTS_REPLACE);
  $node->field_screenshot[LANGUAGE_NONE]['0']['fid'] = $file->fid;
}

That way you won't have to call node_save() so you won't get the error, and the field data will save with the node as normal.

As hook_node_presave() is called for both inserts and updates, you might want to add a condition in there to check whether the node is new or not (checking $node->nid will probably suffice). Otherwise you'll end up doing this operation every time the new node is subsequently saved.


Add a limitations to anonymous user for node view I have to put a limitations on the number of nodes an anonymous user can view. So I have to set a limitations of 5 after that the anonymous user is made to login by redirecting to the login page.

So I have used hook_nodeapi and under view operation i maintains a counter in cookie for the no of times the user visits the node.So if exceeds the counts it redirects to login page. But some how it doent work and gets redirected randomly..i mean not after 5 but after 7,8,,or some number.Some times it doesnt even increments the counter.
So is it because the cache is enabled or is there some other reason to it.
below is my code used under hook_nodeapi:-

if($user->uid==0){
  if(isset($_COOKIE['anonymousquizview'])){
    $m = $_COOKIE['anonymousquizview'];
    $m++;
    setcookie("anonymousquizview", $m, 0,"/", "www.example.com");
  }
  else {
    setcookie("anonymousquizview", 1, 0,"/", "www.example.com");}
    if ($_COOKIE['anonymousquizview'] >=5) {
      drupal_set_message("To attend more challenges, kindly login.");
      drupal_goto('user/login');
    }
  }
}

If cache is enabled hook_nodeapi() is not always executed. The first time a node is viewed Drupal renders the page and save it in the cache. During this process, hook_nodeapi() will be fired. Next time the same page is viewed, Drupal will find the rendered copy in the cache,  serve this copy, and no hook_nodeapi() will be fire fired.

You have to do it in hook_boot. This hook is fired even for cached pages. You must first check if current path is a node path (you may use arg() function). Try to add lightweight code as it will be executed in every page petition.

Remember that this protection is easily bypassed clearing the cookies for your domain.

References

hook_boot()
arg()


drush devel-reinstall does not rebuild tables For some reason if a module is a dependency other another module, and I run 'drush devel-reinstall' on it, it does not delete and then rebuild the tables for that module.  Does anyone know why?

Apparently because the module can't be uninstalled because another one is dependent on it.


How to set up Drupal 7 on Apache/2 without .htaccess files ? I would like to improve Drupal 7 and overall server performance by setting apache/2 without .htaccess files. How to configure apache/2 httpd.conf to achieve this?

You should be able to take the contents of the .htaccess file, and place them in your httpd.conf.  Exactly where depends on how you have your site running in Apache.

If you are using a virtual host, you would place everything inside a <Directory> section that matches your DocumentRoot, inside your <VirtualHost> section for the site.

If you aren't using a virtual host, then everything would (probably) still go in a <Directory> section that matches your DocumentRoot, but I can't remember the last time I didn't use a virtual host, even for servers with a single website on them.

You may get better answers over on ServerFault, as this isn't totally Drupal specific.


Drupal 7 - Give permission to manage users but not permissions We have setup a site in Drupal 7 on which we would like certain users to have access to the user management page, and be able to create new users, assign roles, etc., but we don't want to give them access to the Roles and Permission pages.

Currently Drupal only has 2 permissions Administer Permissions and Administer users.

With the Administer users permission, the user has access to the User Management page, and can create new users but cannot assign roles to users.

If the user has the Administer permissions permission, he can assign roles to users and also access to the permission and role management pages.

How would you grant a user the right to assign roles to users, but prevent him from accessing the permission page?

I had the exact same requirement, and I was able to use the Roles Delegation module to build it to perfection :-)

Here is my scenario to give you more context -

I had a drupal site with roles - A, B, C, Admin, Maint
I wanted users with role Maint to be able to create new users and also assign them roles while doing so
I also wanted to limit Maint users to be able to assign only roles A, B, C to the new users and not the role Admin
All of it was just a few clicks with the Roles Delegation module

Hope this helps.


How can I update user data whenever a user account is saved in PHP? I need to do some processing (calculate a zodiac sign) on some user data after an account is saved.  (When saving a user account, I want to use a custom module to re-compute a field and save the new value.)

I have a function MYMODULE_calculate_zodiac() which returns the term ID of the user's zodiac sign.  I have used dpm() to confirm that the correct value is calculated.

Here is the function in my custom module:

function MYMODULE_user_update(&$edit, $account, $category) {
  global $user;
  $user = user_load($account->uid);

  $zodiac_sign = MYMODULE_calculate_zodiac($account);
  $edit['field_zodiac']['und'][0]['tid'] = $zodiac_sign;

  user_save($account, $edit);
}

However, when I save a user account with this code, my site just hangs and the user is not saved (error: Fatal error: Maximum execution time of 240 seconds exceeded).  What am I doing wrong?

The problem there is you're creating an endless loop.

user_save calls hook_user_update, your hook_user_update calls user_save.... you get the picture.

A better approach would be to use

hook_user_presave

to add the field, then you don't need to worry about saving the account, as the user module will do that for you after the field is added.

The downside is, the uid isn't available in presave (for new accounts), though for a zodiac sign, I assume that's not required.


How to override a module in sites/all/modules directory? Is there an easy way to override a module located in sites/all/modules directory? Like placing it's customized version into modules/ directory or create one under sites/default/modules?

Answering my own question here:

  Your installation will choose from the most specific one available
  (first /sites/sitename/modules (sitename typically might be - default), then /sites/all/modules, then
  /modules).

from Directory precedence and multi-site considerations.


How to retrieve a select box option and set the field's value to it? I have a a taxonomy term select box (called "product_keyword") in a node that gets its options populated via the Reference Field Option Limit module. There are 3 other taxonomy term reference fields in the node that are responsible for limiting the "product_keyword" option list all the way down to a single option, and this part is working beautifully.

The "product_keyword" field is set to Required, so when you actually go in to edit the node, the "product_keyword" field appears to already have this one option selected. However, with the use of the Devel module, I have discovered that this is not the case. There is no #value for the "product_keyword." I have created a custom module (my very first one ever, in fact) to set this #value, but I am having trouble determining how to choose the right properties to set this. This response by Clive is what I'm trying to wrap my brain around.

My module code is using a hook_form_alter function that involves the use of #after_build:

    //Declare the callback for after_build for page node form
function set_keywords_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'part_node_form') {
    $form['#after_build'][] = 'set_keywords_after_build';
  }
}

function set_keywords_after_build($form, &$form_state) {

The overall goal is to simply allow this field to be displayed in a view, but one complication is that these 7000+ nodes are being imported via the Feeds module, and the clients should not have to edit each node manually just to hit the Save button (which is the only way the problem can be solved now - VBO can't do it, nor can the Resave Nodes module). I'm not even sure if #after_build should be involved, and I am also ok with setting the field's #default_value instead of or in addition to the #value.

EDIT:

In the page array dropdown, for the keyword's select list options:

#options (Array, 1 element) 0 (String, 13 characters ) Inker Parts

But under '#value," I'm just getting:

#value (String, 8 characters ) - None -

Under another reference field, "Product Family," where things are functioning normally, I see:

#options (Array, 40 elements)
_none (String, 8 characters ) - None -
1401 (String, 5 characters ) AUTOZ

.......and so on

and for the #value:

    0 (String, 2 characters ) 1401
          $...['content']['system_main']['field_product_family']['und']['#value'][0]

In this example, "1401" is the tid, and "AUTOZ" is the term name.

This question looks a little old, but here is an answer for you.  Reading your comments you have

//Declare the callback for after_build for page node form
function set_keywords_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'part_node_form') {
        $form['#after_build'][] = 'set_keywords_after_build';
    }
}

function set_keywords_after_build($form, &$form_state) {
    $keyword = $form['field_product_keyword']['und']['#options'];
    $form['field_product_keyword']['und']['#value'] = $keyword;
    $form['field_product_keyword']['und']['#default_value'] = $keyword;
    return $form;
}

I applaud your efforts, especially that you are attempting to do this clean and proper with a hook_after_build.  The hook_after_build allows your value setting code to run after the Reference Field Option Limit has done its adjustments, so you are certain to be getting the value you want.
I see one mistake in your code, and that is that #options is an array of Label => Value so that the form can display language in the select field instead of raw values.  I think all you need is this one adjustment:

// remove the -None- option from the start, then set the next option
array_shift($form['field_product_keyword']['und']['#options']);
$keyword = array_shift(array_keys($form['field_product_keyword']['und']['#options']));
// this is safe because $form is not passed by reference,
// do not do this on $form_state

When trying to do things like this, I find it helpful to look inside what it is I am manipulating.  If you know the string of references that you need to access some data, you can print it on the form like this:

//Declare the callback for after_build for page node form
function set_keywords_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'part_node_form') {
        $form['#after_build'][] = 'set_keywords_after_build';

        // see what our options are, print them as text on the form:
        $form['some_text'] = array(
            '#markup' => '<p>'. $form['field_product_keyword']['und']['#options'][0] .'</p>',
            '#weight' => '-80'
        );
    }
}

As you have mentioned you are using the devel module, you could easily throw the #options array into a dpm() or krumo() inside the form alter and get it printed to your form page also.


How do I disable the default node creation form for a particular node type? I have a node type recipe, which should only ever be created via a custom route that causes it to be linked to a parent food type, ie. if the user visits node/add/recipe/1 they will see a recipe creation form that is linked to node 1 of type food.
Now I want to disable the /node/add/recipe route and prevent the recipe node from appearing on node/add. What's the best way to do this?
Note that this is not just a permissions issue - with my module it simply doesn't make sense for a recipe type to be created without a food that is linked to it, so visiting the node/add/recipe page simply doesn't make sense, even for an administrator.

A different approach would be to deny access by throwing an exception, which also affects admins:
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_recipe_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  throw new AccessDeniedHttpException();
}

The Form ID consists of ENTITY_TYPE_BUNDLE_FORM_MODE_form. This assumes you use for your specific recipe form a different form mode.  If not, you can check the reference field value in $form_state->getFormObject()->getEntity() before throwing the exception.
By the way, the hook name doesn't contain a form mode because nodes use the form mode default for the add form, which is omitted in the Form ID. The node edit form for example has the form mode edit, so the form alter hook would then be named mymodule_form_node_recipe_edit_form_alter.
Since this approach is not based on entity access permissions it doesn't remove the link from the node add list. You can do this in a separate hook:
/**
 * Implements hook_preprocess_HOOK() for list of available node type templates
 */
function mymodule_preprocess_node_add_list(&$variables) {
  unset($variables['content']['recipe']);
  unset($variables['types']['recipe']);
}


How to update record programmatically with ECK? I'm playing with Entity Construction Kit (ECK) on a Drupal 7 site. In a custom module I need to add, update and get ECK record.

By admin panel I created my entity "company" and his bundle "company". In my module I already built add and get method for the entity record (methods are working).

But  how can I update a specific record ?

Thanks.

After thousands of research, according to the page Creating and Modifying Entities this is the way to update an entity :

$entity = entity_load_single('entity_name', $entity_id);
$entity->title = 'new name';
$entity->save();

This will load the entity 'entity_name' with the id 'entity_id', then the title will be replace by 'new name'.

I hope its help.


Create a user profile on user creation in drupal 6 I have a problem and can't seem to find the answer.
I'm creating a user via a rest service and it's not creating a user profile along with it.
I'm not sure how to even create the profile.
our user profiles have custom fields that i can pull with my user_get, but when i try to create a user with just a blank profile, it doesn't like it.

any help would be appreciated

function user_services_create_user() {
    $user_name = $input['user_name'];
    //the users email address
    $email = $input['email'];
    if(array_key_exists('password', $input)){
        $password = $input['password'];
    }
    else {
        $password = user_password(8);
    }

    //set up the user fields
    $fields = array(
        'name' => $user_name,
        'mail' => $email,
        'pass' => $password,
        'status' => 1,
    );
    //the first parameter is left blank so a new user is created
    $user_account = user_save('', $fields);
    if(!empty($user_account) && $user_account->uid != '') {
        user_services_send_response('New user has been successfully created', 1, 200,    $user_account);
    }
    else {
        user_services_send_response('New user cannot be created. Please try again later', 0);
    }
}

Changed Code:

function user_services_create_user() {

//the user name of the new user
$user_name = $input['user_name'];
//the users email address
$email = $input['email'];
if(array_key_exists('password', $input)){
    $password = $input['password'];
}
else {
    $password = user_password(8);
}
user_services_check_user($input);
//set up the user fields
$fields = array(
    'name' => $user_name,
    'mail' => $email,
    'pass' => $password,
    'status' => 1,
);
//the first parameter is left blank so a new user is created
$user_account = user_save('', $fields);
if(!empty($user_account) && $user_account->uid != '') {

    $node = new stdClass();
    $node->uid = $user_account->uid;
    $node->type='profile';
    $node->title=$user_account->name;
    $node->name=$user_account->name;
    $node->field_receipt_suppress_name[0]['value'] = user_fill_value_from_request('receipt_suppress_name');
    $node->field_receipt_suppress_points[0]['value'] = user_fill_value_from_request('receipt_suppress_points');
    $node->field_phone_number[0]['value'] = user_fill_value_from_request('phone_number');
    $node->field_first_name[0]['value'] = user_fill_value_from_request('first_name');
    $node->field_last_name[0]['value'] = user_fill_value_from_request('last_name');
    $node->field_user_phone_number[0]['value'] = user_fill_value_from_request('user_phone_number');
    $node->field_points[0]['value'] = user_fill_value_from_request('points');
    $node->field_date_points_last_checked[0]['value'] = user_fill_value_from_request('date_points_last_checked');
    $node->field_last_reward_issued_store[0]['nid'] = user_fill_value_from_request('last_reward_issued_store');
    $node->field_last_reward_issued_date[0]['value'] = user_fill_value_from_request('last_reward_issued_date');
    $node->field_last_reward_redeemed[0]['value'] = user_fill_value_from_request('last_reward_redeemed');
    $node->field_last_reward_redeemed_store[0]['nid'] = user_fill_value_from_request('last_reward_redeemed_store');
    $node->field_last_reward_redeemed_date[0]['value'] = user_fill_value_from_request('last_reward_redeemed_date');

    node_save($node);

    user_services_send_response('New user has been successfully created', 1, 200, $user_account);
}
else {
    user_services_send_response('New user cannot be created. Please try again later', 0);
}

}


How to disable 'promote to front page' and 'sticky' options? Two possible methods that I have explored:

Use hook_form_alter to unset both options on node edit forms. But on the main admin content page, the options still appear under 'Update options' dropdown.

Use Override Node Options module. This provides granular control, but it means disabling the 'Administer content' permission. Users then can't see the 'Update options' at all, which they still need in order to bulk publish, delete, etc.

There are 3 places, where those options can be seen:

on admin/structure/types/manage/article, for the "Article" content type

on node/2/edit, for the node with ID equal to 2

on admin/content, between the "Update options"

If you need to remove the options from those setting/administrative pages, then you need to alter the following form builders:

node_type_form()
node_form()
node_admin_nodes()

node_admin_nodes() is the form builder for the node administration overview in admin/content, which includes the "Update options" field that allows the users with the right permission to promote/demote a node from the front page, and to make a node sticky. The field lists all the node operations implemented by modules; in the list of the operations obtained with $operations = module_invoke_all('node_operations'), those operations are represented from $operations['promote'], $operations['demote'], $operations['sticky'], and $operations['unsticky'].


How do I filter the "admin/content" page through it's url? As the content overview page ("admin/content") has filtering capabilities, I'm trying to allow my users to access the filtered content through an url.

For example, if I want to see a list of contents of type "Article", I would like to access "admin/content/article" or a similar url, and get the contents page with the filter already applied.

Is there any way to do this?

By default this is not possible.
Easiest I can see would be to create a view - if you have views module installed - that has the same path which will override the default Drupal content screen.

Then you can either create argument for the content type as part of url and/or expose filters and since the filters are being passed via get parameter, you will be able to construct an url to point to the filter selection.

Which is almost what administration views module does. You might want to extend these views with arguments, filters, etc...

Other option would be to create custom functionality that would "hook" into the default functionality.


How may I add a tab item in an OG that shows a Content Type related to that group? We have Drupal Commons 3 (on Drupal 7). In our groups, I'd like at add a tag near the group's title that links to a certain content types. I have a View ready to go. How might I add that view to an OG tab?

Update and screen shots:

So I have this view:

I had hopped to create a new tab here:

By playing with this setting:

Hope this will help you,

In Drupal 7, you can achieve this using creating a new MENU item via programmatically OR by VIEWS.

Programmatically:

Create a menu item

function test_menu() {
  ....
  //menu for shows a Content Type related to that group
  $items['node/%/og-content-type'] = array(
  'title' => 'OG content type',
  'page callback' => 'get_og_content_type',
  'page arguments' => array(1),
  'access callback' => 'og_content_type_access',
  'access arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'weight' => 5,
  );
  ...
  return $items;
}

Now give access to the tab

function og_content_type_access($etid) {
  if (access) {//check your condition. Based on this condition the TAB will show.
    return TRUE;
  }
  else {
    return FALSE;
  }
}

Now its time to embed your view

function get_og_content_type($etid) {//Im passing ID in case you want in views.
  $html = '';
  $html = views_embed_view('VIEWNAME', 'display_id', $etid);//embed view
  return $html;
}

Reference : views_embed_view

Using Views:

Just create a new VIEW, with path as node/%/YOUR_PATH, Contextual filters and Permission. Refer the images below

Create a NEW menu TAB now

Add Contextual filters, based on this filter the VIEWS content changes.

Final result

To create a custom permission in VIEWS, you can use PHP filter.

Go to admin > modules and enable PHP filter
Go to your VIEW >> Page settings >> Access and select PHP filter and add this code without PHP TAGS.

  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $entity_type = 'node';
    $etid = arg(1);
    if ($group = og_get_group($entity_type, $etid)) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

NOTE :

You can create you own permission using hook_permission and you can use that permission in VIEWS >> Page settings >> Access


500 server error on clear cache I am facing a pretty strange problem. I have installed Drupal 7 on my site. Whenever I install a module and tries to access the module's configure page after enabling the module, it leads me to simply /admin/config page without showing the option for that particular module configuration.

sometimes when I do a clear cache the problem gets resolved and then I can access the module's config page. but sometime after installing a module, clear cache gives Internal Server Error 500 .. also I tried to flush the cache manually by making a php file into / directory with the following code:

<?php
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_flush_all_caches();
?>

but this also gives Error 500.

When I disable the installed module, clear cache works as usual...
please help me.

As directed by aerozeppelin I got the following error:

  Fatal error: Allowed memory size of 50331648 bytes exhausted (tried to allocate 4096 bytes) in /home/htdocs/includes/database/query.inc on line 1857

So increasing the PHP memory limit is the cure; this link is useful for that.


How to overwrite /modules/user/user.module text? I am trying to override the text outputted on the user login block:

"A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail."

I have copied "/modules/user/user.module" to my site's theme folder and overwritten the text in question however I'm not seeing the change.

Any help greatly appreciated :)

Thank you,

Andrew

You can use hook_form_alter to change this text

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_profile_form':
    case 'user_register_form':
      $form['account']['mail']['#description'] = t('My text');
      break;
   }
}


Rewrite content of view field based on value On a business review page, I have a views block which shows each individual review submitted for the business. In the review form available to the user, I am using integer fields to allow the user to select their choices and to store the submitted information in the database. For instance, if a user selected in their review that the staff was "Very Helpful," then a 5 is stored in the database. This allows me to show the average value on the main business page and change the output based on php (using computed field). However, because of the way that the data is stored, the view block displays a "5" in the field for Staff Helpfulness instead of "Very Helpful."

So, the topic of the question, how can I rewrite text in a view field based on its value (i.e. replace the displayed "5" with "very helpful")?

you can rewrite the output of a field using "Rewrite the output" option in views.

In your case, you might also need php code:
ex:

   $selectedValue=5; // this you can get from the replacement tokens easily

   // this array can be populated using some db query too.
   $selectedText=array('1'=>'satisfactory','5'=>'Very helpful');

   $selectedDisplayTitle=$selectedText[$selectedValue];
   return $selectedDisplayTitle;

Hope this helps.
Let us know if you come across a better solution.


Preprocessed block not udpating after edit I am preprocessing a block which seems to get cache and not showing the updated content on front end after getting edit.

My preprocess code looks like:-

/**
 * Implements hook_preprocess_block().
 */
function mymodule_aboutus_preprocess_block(&$variables) {
  $act_on_blocks = array(
    'myblockid',
  );
  if (!in_array($variables['elements']['#id'], $act_on_blocks)) {
    return;
  }
  $block = $variables['elements']['content']['#block_content'];
  $body = $variables['content']['body'];
  switch ($variables['elements']['#id']) {
    case 'myblockid':
      $variables['myblock_data']['field_title'] = t('Credits');
      $variables['myblock_data']['field_description'] = $body;
      break;
  }
}

- On Twig template
<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {% include "@mytheme/myblock-partial" with {
      "title": myblock_data['field_title'],
      "content": myblock_data['field_description'],
    } only %}
  {% endblock %}
</div>

Drupal 8 caching background in breif:-

Drupal 8 has strong and awesome caching mechanism.

Basically any renderable array is now get cached by default and drupal provides cache API to manage in what context
(could be in context of user/route etc.)(cache contetx), when to invalidate the cache(cache tags) and till when it should
be cached could be Permanent cache(max-age=-1) or no caching at all(max-age=0)

So the renderable array Cache API works around

Cache Context
Cache Tags
max-age

The problem with my code was excessive preprocessing on block content and then avoid {{ content }} to print on block
twig template, so {{ content }} itself take care of '#cache' attribute but since I avoided it during preprocessing
and printed only my custom exposed variables drupal was never able to figure out when to invalidate the cache, and
blocks were permanent cached.

Solution:
I just made sure I am also passing the '#cache' attribute to my renderable arrays and then used the same on twig template

  // - Example during preprocessing

    /**
     * Implements hook_preprocess_block().
     */
    function cfr_world_aboutus_preprocess_block(&$variables) {
      $act_on_blocks = array(
        'myblockid',
      );
      if (!in_array($variables['elements']['#id'], $act_on_blocks)) {
        return;
      }
      $block = $variables['elements']['content']['#block_content'];
      $body = $variables['content']['body'];
      switch ($variables['elements']['#id']) {
        case 'myblockid':
          $variables['myblock_data']['field_title'] = t('Credits');
          $variables['myblock_data']['field_description'] = $body;
          // Added drupal cache attribute
          $variables['myblock_data']['#cache'] = $variables['elements']['content']['#cache'];
          break;
      }
    }

    // - On Twig template
    <div{{ attributes.addClass(classes) }}>
      {{ title_prefix }}
      {% if label %}
        <h2{{ title_attributes }}>{{ label }}</h2>
      {% endif %}
      {{ title_suffix }}
      {% block content %}
        {# Added to pass cache attribute#}
        {{ myblock_data| without('field_title','field_description') }}
        {% include "@mytheme/myblock-partial" with {
          "title": myblock_data['field_title'],
          "content": myblock_data['field_description'],
        } only %}
      {% endblock %}
    </div>


mytheme_preprocess_field is not called on add/edit node I have added the following function in my theme's template.php to test whether it actually gets called when adding or editing a node, but for some reason it is not!

function mytheme_preprocess_field(&$variables, $hook) {
    die('FINALLY!');
}

I have done everything I could think off, refresh cache (all of them), restart apache, restart server, no matter what I do, it is not called. As soon as I go to the frontpage, it is called.

Can someone give me some pointers where I might look next? Thanks!

I believe the theme functions are called on render (as in view) and not the add/edit pages.  If you want to affect the markup of the fields on the add/edit forms you would use a hook_form_alter or hook_form_FORM_ID_alter() and change the render array there.


Unable to post message to wall on facebook using facebook rules module I have following modules installed

FBOauth
Facebook Rules

I have installed its dependencies like Rules and Oauth library.

The settings implemented on the facebook app

Dashboard

TEST
This app is public and available to all users
App ID :
22321917809249
App Secret :
●●●●●●●●Show

In the below all the blurred value has been appropriately added.

Also in the status and review I have made following changes as shown in the image

In the facebook rules I have created a rule with following

Events
User logged in using Facebook connect.
User registered using Facebook connect, requires admin approval.
User registered using Facebook connect.

Action

Post an update on user's facebook wall.
Parameter: Message: Hello Facebook world!, Link to post: m2w.redcom.in

The api and secret key has been added on the facebook configuration settings page and I am able to retrieve the facebook details of the user on the  user details on the websites.
How can I post to the user's facebook wall using the above rules configuration?

All while facebook is logged in and i try to use the fconnect feature,
I get a message dialog box which has following text
"This does not let app post to the facebook"
How can I allow my app to post to the facebook. ??

Drupal Issue posted : https://www.drupal.org/node/2299375

The problem lies with proper permission.
You need to have permission "publish_actions" to post on someone's behalf. If you do need more permissions then follow the below link to get all the permissions provided via Facebook Graph API.

https://developers.facebook.com/docs/facebook-login/permissions/v2.0#reference-extended


Close webform modal and redirect to entity I have a webform that opens inside a modal. Everything works fine. Then I had the problem of closing the modal after the form was submitted. I fixed that to with the help of the following link: https://www.drupal.org/project/webform/issues/3002966#comment-12794056

I have a webform handler that creates a new entity in the postSave() method. After this entity is created, I want to close the modal and redirect to the entity detail page. What is the best/correct way to do this. I could use a RedirectCommand instead of the CloseDialogCommand but how do I get the entity id in the _CUSTOM_MODULE_webform_submission_form_submit_ajax() method. Using the AjaxResponse with a RedirectCommand in the postSave() method didn't work.

Any Suggestions would be great ;-)

Yes you are so close!
just move the creation of the new entity from your postSave()
to right in the ajax call back

example:

_CUSTOM_MODULE_webform_submission_form_submit_ajax(array &$form, FormStateInterface $form_state) {
 // At this point we have all access to $form_state->getValues();
 // the webform submission is all ready saved so we can use the values here.

 // Get the entity storage.
 $entity_storage = \Drupal::entityTypeManager()->getStoage('ENITYNAME');

  // Create New entity.
  $new_entity = $entity_storage->create([
   'field_whatever' => $form_state->getValue('some_field');
  ]);
  // Save entity
  $new_entity->save();
  $new_entity_id = $new_entity->id();
  // set the url.
  $url = "/where-ever/" . $new_entity_id;

  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $response->addCommand(new RedirectCommand($url);
  // Party.
 return $response;
}


Drupal Shurly before redirect I want  create to something like adf.ly script with Drupal. I am using shurly (developed by Jeff Robins) for URL shortening, and it works fine, but I want to display an advertising page for 10 seconds before redirecting to the final URL, which is not a feature provided by this module.

It has a hook called hook_shurly_redirect_before() which may help me, but I don't have enough knowledge to use it.

Can anyone explain how I should use this hook?

With a quick glance at the shurly code, I'd think this should work:

function yourmodule_shurly_redirect_before(&$redirect) {
  $redirect->destination = 'path/to/advert?somevar='. $redirect->destination;
}

And then you need to set up your advertisement page as path/to/advert and have it redirect to $_GET['somevar'] after the timeout.


Local Drupal 7 user in database I want to save a user's email and username when a button is clicked.
I assume I have to do this via PHP but I can find the user column at localhost/phpmyadmin. Where is the users' information being stored and which is the MySQL query to achieve that?

You should not use a direct MySQL query to update anything.

In this case you can use user_save(); which it is basically, load the user object -> change data -> pass it to user_save(); or even better user entityAPI and entity_metadata_wrappers

The default table where drupal saves user data is users, there you can find the email and username


How to find which pages use a certain view? I am working on a site that has a lot of views with multiple displays, and to make life easier for our team we are trying to document where views are in use; including view blocks.

In other words, I want a simple way to know which pages use a certain view for each view.  The site also has views that are enabled but not in use on any page, so it would be nice to be able to find out which ones may be candidates for deletion to make administration easier.

You can use the Devel module and enable the Web Profiler module that comes with Devel. This module will tell you which view is being used when you visit a page.

Alternatively, you could try the answers from here, Where are my views being used?


Two pagers for a single view I have a view with fields. In fields I have added two rendered node fields with two different view modes teaser and teaser1.

I want to add two pagers to this view. One for the first rendered node with view mode teaser and one is for the 2nd rendered node with view mode teaser1.

I have grouped the 2nd rendered node by a date field in template file.

The first rendered node is simple a list and the pager will add new content.

The 2nd rendered node is grouped by a date field. Content is displaying under each group date. The pager for this view mode will be different.

It will add new group dates along with their content not just only content.

I have looked up for contrib module but didnt find one. I think I have do this custom. But can someone guide me from Where I should start and can give me an idea.

If i understand correctly this is not possible out of the box with your current setup and views only. Could you split the view into 2 seperate views instead? Use the second one as attachment for the first. So you could define the pager for each view. You could also look into Views Field View Module. With node specific pagers created with the Entity Pager Module it could possibly work even with your current setup.


Install Drupal in a subfolder of an existing website I have a question about drupal installation in a subfolder: We have an existing website running on Magento. Now for some special functionalities we need to build some drupal pages, which all should be in a subfolder.
Example.
Main URL is (Magento): www.mysite.com
Drupal installation: www.mysite.com/specialpages
all other pages are still Magento as today, e.g. www.mysite.com/page1, www.mysite.com/folder1/page12 etc.

Is it possible to install drupal in this subfolder?

thanks for any help / information

Drupal and Magento both use .htaccess rules for functionality.   One slight quirk with Apache is that .htaccess is processed from a directory up through all of the parents.  This means that if your Drupal install is inside your Magento install, Magento's .htaccess may interfere with Drupal (a Magento directive may be applied after a Drupal one).  This is going to totally depend on your setup.  At very least, you will likely need to set RewriteBase in the Drupal .htaccess for things to work properly.  I have seen similar situations work perfecty fine, but others fail in bizarre ways.


Module for form submitting straight to admin section Can anyone recommend a module for a contact form to submit to the administrator (so the administrator can view/read it)?

Users should be able to anonymously submit messages; they should not first log in, or create an account.

You should use the Webform module.

  Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.


Drupal Commerce Title length I'm facing a problem with commerce product title length. I want to increase the lenght over 255. What I've tried so far is:

Change DB field from varchar to text
Change the maxlength of the form field
Change the formfield to a textarea

Any of the form changes lead to an error. Any idea how to increase the length?

I wouldn't increase the length of the field, but instead ask yourself why you are storing so much information in the title. There is a very good chance you simply need to split the information out into different fields or use a textarea to store ancillary information. You don't know how many assumptions commerce makes about the title field with regards to logic and formatting and the general Commerce wisdom is to not mess with the internals.


How to prevent node creation if blacklisted words detected in the body? I have a forum and when user creates new thread (which is some custom content type) and if the thread lets say has word 'loan' in it somewhere, in a title field, or a body field and etc. then the thread doesn't get saved and gives some warning or something like that.

Is there a module for that? Recently my forum got spammed with loans and there's about 1000 of those threads and all about loans. And those spams bypass all anti spam protections. So I came up with this 'brilliant' idea.

Please don't suggest Captchas and etc. I need something like I described with a blacklist.

I can't give you working code, but the basic approach I have used is:

Make a new Vocabulary.  Call it Naughty Words.  Populate it with all of your naughty words.
hook_form_alter() your submission form, and push on a new $form['#validate'] functions.
In your validation function, read in all of the naughty word terms into an array.  Then check the submitted element(s) against the naughty words.  form_set_error() if there is a match.

There are several ways to do the matching.  One is a simple loop with a strpos against each term; another is to explode the submission and then do an array intersection.  Play around with it in something standalone.


Adding javascript in html.tpl I am trying to add JavaScript in footer with drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/libs/jquery-1.7.1.min.js', array('type' => 'file', 'scope' => 'footer'));, but for some reasons, it is not getting loaded.

What is wrong in my code?

Consider what's at the top of the html.tpl.php file...a call to <?php print $scripts; ?>.

This would logically mean that all scripts added by drupal_add_js() in the current page call have already been rendered down into the $scripts variable, and printed to the page.

Thus, when you call drupal_add_js() inside html.tpl.php, it's too late to add new scripts with drupal_add_js().

This sort of code should never really be inside a template file anyway to be honest, it should be inside a preprocess function inside your theme's template.php file.

On another note, it looks like you're trying to insert jQuery 1.7 into the current page. This may cause you all sorts of problems as Drupal already loads its own version of jQuery into the page...you'll probably get conflicts.

The better way would be to install the development version of the [jQuery update][1] module, which has the option to use jQuery 1.7 throughout the site. I don't know the current state of this; the last time I checked (a couple of months ago) there were still some core JS elements that break using 1.7.

You can find a bit more info here: How do I update jQuery to the latest version I can download?


Why file field button disappeared while uploading file? I have installed fresh drupal-7 and create file upload field with manage field with 8M Maximum upload size. when i upload a file 25MB then it is showing error message and file field missing.
Before upload:

After Upload:

After long search i got some links
"exceeded the maximum file size" error even when uploading small files
File upload error "Files must be less than x MB" despite file being smaller than x
By these link my problem sorted out but my question. why the file upload field button  disappeared?.
My php.ini settings are

post_max_size = 24M
upload_max_filesize = 512M

Don't set upload_max_filesize larger than post_max_size if you are not using any library that takes care for such cases. Plupload integration with FileField Sources Plupload can get it managed for you.

Currently you are confusing your Drupal by allowing file upload larger than allowed data size. Given that data posted is file size + metadata size, both always equal to or greater than 0, it makes no sense and Drupal may fail.

Specifically, button disappeared because Form or Field API crashed, and it crashed because you mismatched sizes without providing appropriate handler.


Altering a URL alias without using a module Is there a way to alter a URL alias without using a module? Somebody told me to write a record into database table, but I don't know how to do it.

Drupal allows to add (and alter) a path alias using the user interface. Generally, there is no reason to alter a database table directly, especially when a Drupal core module allows to do what you are trying to achieve through an administrative page.

If you need to do it from code, then you can use path_set_alias() function as pointed out from tim.plunkett. Differently, Drupal user interface is preferable for such tasks.

The query used by path_set_alias() to update an existing alias is similar to the following (I simplified the query by removing the reference to the language field):

UPDATE {url_alias} SET src = '<alias>', dst = '<destination>' WHERE dst = '<old_destination>'

If your Drupal site is using table prefixes (e.g. dr6_) then you need to replace {url_alias} with dr6_url_alias; if your Drupal site is not using table prefixes, then replace {url_alias} with url_alias.
Replace also <alias> in the query I wrote with the path alias, <destination> with the path to alias, and <old_destination> with the old path (which can also be the same value used for <destination>).

If there isn't a path alias, then the query becomes the following one:

INSERT INTO {url_alias} (src, dst) VALUES ('<alias>', '<destination>')

<alias> and <destination> have the same meaning I reported before.


Altering commerce invoice mails fails I'm altering different emails from my hook_mail_alter(&$message) function. But for some reason altering the email sent by commerce invoice module is not working. I'm trying to do it like:
switch($message['id']){
    case 'invoice_confirmation':
      $message['subject'] = 'Some other title';
      break;

I found the code that sends that email in invoice module:
  public function send(InvoiceInterface $invoice, $to = NULL, $bcc = NULL) {
    $to = isset($to) ? $to : $invoice->getEmail();
    if (!$to) {
      // The email should not be empty.
      return FALSE;
    }

    $subject = $this->t('Invoice #@number', ['@number' => $invoice->getInvoiceNumber()]);
    $body = [
      '#theme' => 'commerce_invoice_confirmation',
      '#invoice_entity' => $invoice,
      '#totals' => $this->invoiceTotalSummary->buildTotals($invoice),
    ];
    if ($billing_profile = $invoice->getBillingProfile()) {
      $body['#billing_information'] = $this->profileViewBuilder->view($billing_profile);
    }

    $params = [
      'id' => 'invoice_confirmation',
      'from' => $invoice->getStore()->getEmail(),
      'bcc' => $bcc,
      'invoice' => $invoice,
    ];
    $customer = $invoice->getCustomer();
    if ($customer->isAuthenticated()) {
      $params['langcode'] = $customer->getPreferredLangcode();
    }
    $file = $this->invoiceFileManager->getInvoiceFile($invoice);
    $attachment = [
      'filepath' => $file->getFileUri(),
      'filename' => $file->getFilename(),
      'filemime' => $file->getMimeType(),
    ];
    $params['attachments'][] = $attachment;

    return $this->mailHandler->sendMail($to, $subject, $body, $params);
  }

}

and there I saw that id should be 'invoice_confirmation', but like my hook function is never reached when this email is sent?! How to alter this email title?

Solved the issue - id is actually 'commerce_invoice_confirmation'.
I was trying to print out $message['id'] and stop executing of code, but that never happened? So I assumed that my code was never called. Not sure why. So I used watchdog logger to log id value and found it out.


After updating to 7.27, updates don't work and Status says cannot verify Drupal core I upgraded my site to 7.27 using drush, and my website says that it is running 7.27 under the "modules" admin page.

However, when I get a status report, it says "No update data available.
No update information available. Run cron or check manually."

So I run the cron there, and it will turn green and read "Drupal 7.27" but if I try to run update my modules it just stops the page after saying "checking for updates" and the status report reads the above error again instead of reading "Drupal 7.27".

I've rebuilt the registry, and I am at a loss as what to do now.

Any advice is appreciated. Thanks.

I found the issue. It was a javascript error with the "Colorbox" library. Apparently the colorbox library was two years old and became incompatible due to the switch from .live to .on. All issues were solved when I updated my colorbox library.


Xdebug not working over Drush I'm using Drupal VM and the Drush Launcher (0.6.0). Whenever I try to Xdebug, PhpStorm notices, but it never actually reaches my Drush command. It stops at running Drush. This seems to have started recently.

My command looks like:

XDEBUG_CONFIG="remote_enable=On remote_connect_back=Off remote_host=192.168.90.1" PHP_IDE_CO
NFIG="serverName=example.wizonesolutions.com" drush -l example.com module:custom-command

From https://github.com/drush-ops/drush-launcher#xdebug-compatibility:

  Drush Launcher, like Composer automatically disables Xdebug by default. This improves performance substantially. You may override this feature by setting an environment variable. DRUSH_ALLOW_XDEBUG=1 drush [command]

So to make Xdebug reach the rest of your code, add DRUSH_ALLOW_XDEBUG=1 to the environment variables in front of your command.


Autocomplete results in a HTML listbox I am using autocomplete from drupal so that users can be guided into finding what they are looking for. For an even better user experience it would be great if autocomplete is returning the results in a listbox. I just started to learn drupal programming (and loving it :) ) but I can't find anything on this particular question.

At this moment when I start typing in a textarea, drupal will show a selection of approx. matches in a pulldown list. How do I get those matches in a html listbox?

I am using the code below for autocompletion

/**
* autocomplete helper
* $string = string for search
*/
function _complete_autocomplete($string) {
  $matches = array();
  $result = db_select('notebooks', 'c')
    ->fields('c', array('product'))
    ->condition('product', '%' . db_like($string) . '%', 'LIKE')
->range(0, 10)
    ->execute();

  // save the query to matches
  foreach ($result as $row) {
    $matches[$row->product] = check_plain($row->product);
  }
  // Return the result to the form in json
  drupal_json_output($matches);
}

Okay I got a bit working. But it only fills the select options after the textfield is losing focus. How can I make it so that while typing in the textfield, the select options is filled with data. Kinda similar as to autocomplete?

And another question, if i press enter I get an HTTP error . An Ajax HTTP request terminated abnormally. path: /?=system/ajax
status : text
responsetext:
ready/state:4

Any ideas why this is happing?

<?php

function dropdown_menu(){

$items['test/drop'] = array(
'title' => 'Fill select options from db',
'page callback' => 'drupal_get_form',
'page arguments' => array('select_dropdown'),
'access callback' => TRUE,
'weight' => 4,
'type' => MENU_NORMAL_ITEM,
);

return $items;
}

function dropdown_submit($form, &$form_state) {
//dpm($form);
drupal_set_message('Submit handler was called.');
}

function select_dropdown($form, &$form_state) {

$form['searchfield'] = array(
        '#title' => t('Search database and fill select options'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 115,
        '#size' => 55,
        '#weight' => 0,
'#default_value' => 'look for it',
'#ajax' => array(
  'event' => 'change',
  'callback' => 'search_db',
  'wrapper' => 'dropdown-second-replace',
),
    );

  // Get the list of options to populate the first dropdown.
$options_first = _drop_get_first_dropdown_options();
$selected = isset($form_state['values']['searchfield']) ? $form_state['values']['searchfield'] : key($options_first);
$form['dropdown_second'] = array(
'#type' => 'select',
'#title' => 'Options filled from db',
'#prefix' => '
',
'#suffix' => '
',
'#size'=>10,
'#options' => _drop_get_second_dropdown_options($selected),
'#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
);

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

  return $form;
}

function drop_dependent_dropdown_callback($form, $form_state) {
return $form['dropdown_second'];
}

function search_db($form, $form_state) {
return $form['dropdown_second'];
}

// normally pulling data from the database.
function _drop_get_first_dropdown_options() {
return drupal_map_assoc(array(t('empty')));
}

function _drop_get_second_dropdown_options($key = '') {
$matches = array();
$result = db_select('tabel', 'c')
->fields('c', array('product', 'xtra'))
->condition('product', '%' . db_like($key) . '%', 'LIKE')
// ->range(0, 10)
->execute();

// save the query to matches
foreach ($result as $row) {
$matches[$row->product] = check_plain($row->product) . ' xtra:' . ($row->xtra);
}
return($matches);

}


How call a block named Poll Recent from template? I need to call the block Poll-recent from template.  I have tried this code and not work for me.  I am working in Drupal 7.

<?php
$block = module_invoke('block', 'block_view','poll-recent');
print $block['content']; ?>

or

<?php
$block = module_invoke('poll', 'block_view','recent');
print $block['content']; ?>

What is my error?

Thanks for your help.

In D7, you will need:

$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);

In the case of recent poll:

<?php
  $block = module_invoke('poll', 'block_view', 'recent');
  print render($block['content']);
?>

Curiously, although defined in poll_block_info the delta is actually ignored in poll_block_view, perhaps as the poll module only provides a single block.


How to call different fields from different content in same view? I have content type Say "A" and for that i want to create view, in this view i want to add a field which is from different content type say "B", reason is here in the B content type i have fee category and assigning the rent value for each category, and this node of content type is referring in a content type A with entity reference, something like this in screen shot. as of now i created view for content type A,and added the field of content type B, but the values add in the content B are not displaying in the view of content A

To get the values of "cage rent per day" from B to A's view, you must add a relation in content A view with the "Fee category" field.

Then normally you should select in the "cage rent per day" field settings in view A, the relation you've just added.

However, the idea is to have some reference to content B in view A to access B's fields values. And this is possible with relations .


preprocess_node_webform is not working I wanted the error messages from the webform to be customised. So I wrote following piece of code in template.php of my theme.

function sandesh_preprocess_node_webform(&$vars, $hook) {
 if ($vars['node']->nid == "41" && is_array($_SESSION['messages']['error']))   {
 $errors = &$_SESSION['messages']['error'];
 $find = 'email';

 for($idx = 0; $idx < count($errors); $idx++) {
  if (substr($errors[$idx], 0, strlen($find)) == $find) {
  $errors[$idx] = 'Please enter the email field';
  break;
   }
 }

}
}

But this is not working. Is there something wrong in the code? Or is there  any other method to get customized error message in the webforms ? Thank you

You don't need to code to do this. Have a look at the answers to this questions to find more information: How to modify user messages without hacking core user module?


Tag users in a content field to create user-specific content listings I'm newish to drupal and it seems like this should be somewhat straightforward or at least possible with views and/or taxonomy.

I have an embedded video content type. I want to tag multiple users in a hidden field (as if they were taxonomy terms). The desired result is that a user can go to a URL like /videos/my-classes and it will list all the videos they are tagged in.

I've been reading the following thread, but there doesn't appear to be any applicable options when I try adding a views relationship. I'm looking for an option like "Video Embed: User" or something. I tried adding a user entity reference to the content type, but that didn't seem to help.

Thread: Display content with Taxonomy on User and Content matching

What I am trying to avoid is having the user go to /videos/username but instead /video/my-videos which displays different content for each user.

I'm not opposed to writing a code snippet for my theme, but it seems like there's a solution to this given the tools I already have.

This task can be done in the next way:

Download References module
Install User Reference module from this package
Add User reference field to your content type
It the view, that will display videos add a Contextual filter by created earlier user reference field
In the filter settings choose "Provide default value" -> "User ID from logged in user"


Should I call a function to query the database in a custom content type template? I am calling the following function inside a template for a custom content type, but my senior developer suggested that calling a function inside a template file is not Drupal standard.

function some_function($AA_tid = 0) {
  $dis_pt = db_select('some_tble', 'v')
    ->fields('v', array('title'))
    ->condition('some_fld', $AA_tid)
    ->distinct();
  $dis_pt->join('another_tble', 'ss', 'v.title = ss.type');
  $dis_pt->fields('ss', array('name'));
  $result = $dis_pt->execute()->fetchAll();
  return $result;
}

Should I call the function which will query the database from a content type template? Generally speaking, is it better to avoid such code in a template file?

Edit: function call is present inside the template & its definition is available in some module file.

I believe that depends on what you're doing with your query. According to this Drupal.org community doc you should "refrain from having complex logic in" .tpl files and "for all the conditional logic and data processing of the output, there is the template.php file". IOW template files are for theming/output manipulation while other functions or logic should go into your custom module. So if your query is part of a theming process, yes it should be in your template file. Otherwise in your custom module.

AFAIK other developers will not be looking for a non-theming function in a template, which is why I think the senior dev suggested that.


A little calendar icon to show when something was posted? I seem to recall trying a theme - I forget which; maybe Marinelli? - where each post on the from page had a nice little calnedar icon with the day and month of the pst.

Is that a module which I can use on other themes?

It's a simple theme modification, probably also easily done via .css. There is not need for a module for this.

Simply edit your themes node.tpl.php page in your theme directory/templates/

Find:

 <?php print $submitted; ?>

Wrap a simple tag round it like so:

      <?php print $submitted; ?>

Write your css:

.date_submitted {
  background: url("../img/icons/calendar_view_month.png") no-repeat scroll left top transparent;
}

You have to save the calendar image or create your own ->

You also probably need to do some simple formatting in the css like padding-left (to push the text to the right to stop it overlaying the image) etc ...

If you don't know what I am on about, read up about css3 and drupal themeing and learn some basics.


Switch to admin theme based on path using hook_init() or template.php in Drupal 7 I'm running a site that uses a separate admin theme. I'd like to include a couple additional pages that use the admin stylesheets. How can I apply the theme selectively to these pages. I'd rather do this in hook_init() or template.php. I don't want to add any more contrib modules to the site at this point. Thanks for any illumination.

The Administration theme module will do it, but given you'd like to do it yourself, it does cast some light on that path by suggesting the hook_admin_theme_check() and hook_admin_theme_info() hooks.


Access denied occurs after translate menu link I want to translate my menu, I have installed internationalization, variable and locale modules but on my menu items when I click on translate :

An access Denied page is displayed :

What am I doing wrong?

[EDIT]
Log :

You need to make sure the menu is translatable.  Do this by clicking on the "Edit Menu" option and clicking on "Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized."

The click "Save".

The path would be as follows: site/admin/structure/menu/manage/menu_id/edit


Commerce order rule save order I have a field in my orders which should be updated when an order is saved. I created a rule with the event "commerce order save", do the calculation for the field and at least save the order. But that logically gives me an endless loop.

How can I save the order without firing the event again?

You can use the 'Before saving a commerce order' trigger in Rules.  It's right there in the 'Commerce Order' section.  Then you don't need a save action since it's about to be saved already...

That should do it for you!


How do I get only node IDs from the search results? I'm using Search API Solr with custom searches in code, but I want to find a way to limit the return results to only the nid to save on bandwidth with our third-party solr server. I've tried $query->fields(array('nid')) but I receive the following error.

  SearchApiException: Trying to search on field nid which is no indexed fulltext field.

I am using the following code (simplified).

$index = search_api_index_load('my_index');
$query = $index->query();
$query->keys($search_terms);
$query->fields(array('nid')); // doesn't work
$results = $query->execute();
return $results;

How do I get only node IDs from $results?

This is because the fields() method of the SearchAPIQuery class makes the search in fields with datatype fulltext.

In order to get the nid in the result, you have to ensure that its value is being indexed by search_api. You can check that at /admin/config/search/search_api/index/my_index/fields (my_index is the name of the index in this case).

To filter using the nid field you might have to use the condition method instead. The following should work:

$index = search_api_index_load('my_index');
$query = $index->query();
$query->keys($search_terms);
$query->condition('nid', $val); // The third parameter "operator" defaults to "="
$results = $query->execute();
return $results;


how to style or theme organic groups How can i present groups on my group-list page similar to this site -
http://www.popsugar.com/community/groups . i want there to be a picture, group title, short description of the group and total number of members.

further, how can i go about giving groups an option to have profile picture? I presume i'll have to use views but am not sure how. i am using drupal 7 and zen sub theme.

checkout this awesome og video tutorial, it will show you most of the steps needed. To add a picture to a group you just add a field type "photo" to your group node.
And to display the list of groups you'll use views. I haven't figured out yet how to show the count of members that belong to each group. I posted that as a separate question.


Panels doesn't output views content pane title I have a panel named bar in which I added a view-content-pane named foo.For this view I created a template-override named views-view--foo--panel-pane.tpl.php in which I added, besides other things, a container for the $title like:

<?php print $title; ?>

The title of the view-content-pane is Foo.
To limit the moltiplication of divs I set to "No markup at all" the style of both the whole panel and the single pane.
Configured like that, the view shows with custom styles (which I setted in my custom theme-override) except for the title that doesn't display at all.
If I change the single pane style to "No style", the title is shown but using the panel default style (which breaks my layout).

It's there a way to output the view-content-pane title as configured in the template-override without this being rendered by the panel?

The $title variable for the views_view theme hook is added only for the administrative preview. Here is the section of code in template_preprocess_views_view() that adds the title: http://cgit.drupalcode.org/views/tree/theme/theme.inc?h=7.x-3.11#n85

If you want to add that variable to your template override, you can do so with an additional preprocess.


Rendering blocks inside node I am building a Drupal 8 site. The site will have basic pages (nodes) that have three fields: a title, a body and a list of embedded blocks.
The idea is to allow the editors to create content blocks by using the new functionality of Block Types in Drupal 8. Those blocks can be referenced and arrangaed inside the page by using an entity reference field.

I have built the necessary infrastructure and I can reference my custom blocks from the page and render them in the template. The trouble comes when I want to set a custom template for my blocks, for example I would like to have a custom template: block--image-gallery-block.html.twig that would be used when rendering blocks of type Image Gallery Block.

With Twig debug mode enabled I can see that Drupal is looking for a template for the entity reference field, and then starts to render the referenced block fields instead of the block itself, so I can not use any template for it (not even the default block.html.twig).

I've thought about using a custom template for my field and render here the block the way I like. Unfortunately my field can reference blocks of multiple types, so this solution won't work for me.

How can I make Drupal pick the proper template for the referenced blocks?

Edit: solution

I am explaining here the solution I've ended with after reading @ssibal and @4k4 answers.

I've built some new content-types that will represent the blocks.
I've modified my Basic Page content type to have an entity reference field that points to the blocks. This field simply references other nodes from the content types that I want (the ones I've made in the step 1).
In the display options of my basic page, I choose which view mode I want to use for rendering the blocks.
I use the view mode that I've set up in the step 3 to build custom templates for my block content types.
Since I do not want block content types to be accessed directly with a URL, I've implemented a hook_node_access to throw a 404 error when directly loading a node of my block content types.

Those blocks can be referenced and arrangaed inside the page by using
  an entity reference field.

These "block contents" should be a different content type, since you are not using (based on your writing) the block functionality at all. After that, you can define your own display for this content type, and also create a twig template for it.


Show all events that are active between two dates chosen from exposed date filter I have a problem in showing views results with an exposed date filter in D7 views 3.x.

problem

We have several events with a date field. It is required to fill in a start and end date.
We want a visitor to choose a start date and an end date with an exposed filter in a view.

wanted results

The results should show every event that occurs:

Events that occur between the two dates
Events that are already started. So the start
date is already in the past.
Events that are in the future but the end date is not between the chosen dates.

We have already tried to configure a startdate with "equals or greater than" and an end date with "equals or less than".

Am I overlooking something?

If you have configured your view to display all events that has start date >= x and end date <= x then what you have done show do the job.

In order to make it easy for others to help you, I recommend that you give description of your content types date fields, update your question with export code of your view so that others look and spot mistakes if any.

In the meantime, I have created a content type called event, and give it one field called i.e. date (I have configured the date field to collect both start date and end date - only year/month/day). I then setup a view and setup two exposed filters on start_date and end_date of this content type with operators as greator than or equal to and less than or equal to, and they seem to work without any problem. Follow is the export code of my view

    $view = new view();
$view->name = 'events';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Events';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Events';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['reset_button'] = TRUE;
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: date */
$handler->display->display_options['fields']['field_date']['id'] = 'field_date';
$handler->display->display_options['fields']['field_date']['table'] = 'field_data_field_date';
$handler->display->display_options['fields']['field_date']['field'] = 'field_date';
$handler->display->display_options['fields']['field_date']['settings'] = array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'eventsbydate' => 'eventsbydate',
);
/* Filter criterion: Content: date -  start date (field_date) */
$handler->display->display_options['filters']['field_date_value']['id'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['table'] = 'field_data_field_date';
$handler->display->display_options['filters']['field_date_value']['field'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['operator'] = '>=';
$handler->display->display_options['filters']['field_date_value']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_date_value']['expose']['operator_id'] = 'field_date_value_op';
$handler->display->display_options['filters']['field_date_value']['expose']['label'] = 'date (field_date)';
$handler->display->display_options['filters']['field_date_value']['expose']['operator'] = 'field_date_value_op';
$handler->display->display_options['filters']['field_date_value']['expose']['identifier'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
$handler->display->display_options['filters']['field_date_value']['group_info']['label'] = 'date (field_date)';
$handler->display->display_options['filters']['field_date_value']['group_info']['identifier'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['group_info']['remember'] = FALSE;
$handler->display->display_options['filters']['field_date_value']['group_info']['group_items'] = array(
  1 => array(),
  2 => array(),
  3 => array(),
);
/* Filter criterion: Content: date - end date (field_date:value2) */
$handler->display->display_options['filters']['field_date_value2']['id'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['table'] = 'field_data_field_date';
$handler->display->display_options['filters']['field_date_value2']['field'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['operator'] = '<=';
$handler->display->display_options['filters']['field_date_value2']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_date_value2']['expose']['operator_id'] = 'field_date_value2_op';
$handler->display->display_options['filters']['field_date_value2']['expose']['label'] = 'date - end date (field_date:value2)';
$handler->display->display_options['filters']['field_date_value2']['expose']['operator'] = 'field_date_value2_op';
$handler->display->display_options['filters']['field_date_value2']['expose']['identifier'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'events';

screenshot of the configuration page is as follow

If the above approach does not help you then have a look at this useful module https://www.drupal.org/project/views_between_dates_filter