How to set up drush aliases for a local server for rsync? I'd like to use drush to sync files from local server to production server. I have edited the aliases.drushrc.php file and placed inside /drush/aliases in both local and remote machines. Everything seems to work fine except that drush understands that both sites are in the same server since I do not know how to tell drush that local is in another machine in my local server.
I guess it's something to do with uri but I do not know what should I write there.

I've tried with this:

$aliases['local'] = array(
  'uri'  => 'mysite.localhost',
  'root' => '/home/user/www/mysite',
);

and this:

$aliases['local'] = array(
  'uri'  => 'localhost/mysite',
  'root' => '/home/user/www/mysite',
);

being mysite the name of the folder placed in /home/user/www in my local server, but none of them seem to work.

Anyone can tell me what am I doing wrong?

EDIT:

I have placed mysite.aliases.drushrc.php in my local sites folder.
However I didn't succeed with the following code in my local site:

drush rsync @mysite.live:%files @mysite.local:%files

This is what I get:

  You will destroy data from @mysite.local:/home/user/www/mysite/%files and replace with data from @carloscamara.live:/home/user/www/mysite/%files
  Do you really want to continue? (y/n): y
  The source and destination cannot both be remote.
  rsync error: syntax or usage error (code 1) at main.c(1166) [Receiver=3.0.8]

This is mysite.aliases.drushrc.php content:

$aliases['local'] = array(
    'uri'  => 'localhost/mysite',
    'root' => '/home/user/www/mysite',
    'path-aliases' => array(
      '%files' => 'sites/default/files',
     ),
     'command-specific' => array (
       'sql-sync' => array (
         'no-cache' => TRUE,
       ),

$aliases['live'] = array(
    'uri' => 'mysite.com',
    'root' => '/home/user/mysite';
    'remote-machine' => 'mysite.com';
    'remote-user' => 'myusername',
    'remote-host' => 'mysite.com',
    'path-aliases' => array(
      '%files' => '/home/myusername/mysite.com/sites/default/files',
     ),
  );

To set up to do a drush rsync or drush sql-sync to a remote machine, set up aliases for both sites on the local machine.  The alias for the local site should be as you have shown in your question.  For the remote machine:

$aliases['stage'] = array(
    'uri'  => 'staging.mysite.com',
    'root' => '/home/user/www/mysite',
    'remote-host' => 'stagingfqdn.myisp.com',
    'remote-user' => 'wwwadmin',
  );

'remote-machine' should be the fully qualified domain name of the machine that hosts the remote site.  This may or may not be the same as the 'uri' parameter.  You might need to edit /etc/hosts, but only if the remote machine is not resolvable in DNS (unusual).  The 'remote-user' should be the name of the user that owns the files at the Drupal root; usually this is not the user that the web server runs as.

It sometimes makes sense to sql-sync from local to remote -- for example, when bringing a site live for the first time.  Usually, though, you are going to want to rsync your code from local to remote (or check it out from a vcs), and sql-sync your database from remote to local (and never the reverse).  This will insure that you do not overwrite user-generated content. See the features module for one common solution for pushing configuration to the remote machine via copying files.

Edit: Made a typo: said 'remote-machine', but it should have been 'remote-host'.  Corrected above.

Edit 2: Originally I said "rsync your files from local to remote (and never the reverse), but I meant code.  Corrected above.  It is, of course, reasonable and customary to rsync %files from remote to local, as shown in your updated question.


Views 3 - Create an archive for a given type grouped by year, then split in to months I am trying to create an archive in Views 3 (Drupal 7) to use a filter for a given type to sort in to a list of nodes grouped in to Months, but then they are grouped in to Year:

Node Type
  |-Year
    |-September (node count)
    |-August (node count)
      ...
    |-February (node count)
    |-January (node count)
  |-Year
    |-December (node count)
    |-November (node count)
    |-October (node count)

I have looked at the default Archive view template, but that just groups by month (i.e. September 2012 (node count))

If anyone can help that would be great.

Thanks!

Have anyone figured out how to do this. I'd be interested in finding out how to do this as well using views.


Adding custom content to $form I have a page that is displaying a form, and I want to add some text to the top of it.

I create my own module for the form, and have it set up like this:

function hook_menu(){
  $items['page'] = array(
    'page callback' => 'form_function',
  );
}

function form_function() {
  $form = drupal_get_form('return_form');
  return $form;
}

function return_form(...){
  $form['element'] = ...
    .. ;
}

I want to add onto this form with a paragraph or two to go above the form.  I looked at the form api for something i could use from '#type' but I found nothing.  Any suggestions are welcome.

you could try using hook_form_alter()

For e.g.

<?php
function your_module_name_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'your_form_id'){
    //First element in the form.
     $form['element']['#prefix'] = '
Your paragraph before the form.
'
  }
}
?>


How to add a CSS class to fields in Drupal 7? I want to add a CSS class to the HTML output of each field in my field collection.

Please recommend me some module or method to achieve this. I have tried the Fences and Field Formatter Class modules but they did not work.

You could use hook_preprocess_field() in which you can define additional classes for your fields.

Check these to get some idea:
http://atendesigngroup.com/blog/adding-css-classes-fields-drupal
https://gist.github.com/1184302


Which events are invoked when an order is removed or cancelled? I have already an event subscriber class with commerce_order.place.post_transition defined. I need to remove nodes when an order is deleted or canceled.

What event could I use in that case?

$events = [
  // State change events fired on workflow transitions from state_machine.
  'commerce_order.place.post_transition' => ['onOrderPlace', -100],
  'commerce_order.cancel.post_transition' => ['onOrderCancel', -100],
  // Order storage events dispatched during entity operations in CommerceContentEntityStorage.
  // ORDER_UPDATE handles new order items since ORDER_ITEM_INSERT doesn't.
  'commerce_order.commerce_order.update' => ['onOrderUpdate', -100],
  'commerce_order.commerce_order.predelete' => ['onOrderDelete', -100],
  /* OrderEvents::ORDER_ITEM_UPDATE => ['onOrderItemUpdate', -100],
  OrderEvents::ORDER_ITEM_DELETE => ['onOrderItemDelete', -100], */

  'commerce_payment.filter_payment_gateways' => ['onPayment', -100],
  ];
return $events;
}


Creating an exposed filter on a view as a list with taxonomy terms I have categories of photographs and each photograph is categorised. So to expose the filter to the anonymous user they can click on a category and it shows that categories images.

How would I replace the select list or auto complete exposed filter with this so I can then style the list as a horizontal small menu above the view?

Better Exposed Filters would be helpful for that.  It allows you to replace the select/autocomplete with normal anchors that can be styled however you prefer.

After installing and enabling BEF, add your exposed filter and save it (you only have the standard options at this point).  Then, go to the views advanced settings and change "Exposed form style" to Better Exposed Filters.  Then you will have a BEF Settings option, this is where you will see the options below.

Advanced settings:

This is the setting you're looking for:


How to add a “Last Modified at” field in footer area? I'm fairly new to Drupal and in my research I've seen this question asked many times over the years but I have yet to see one relevant to Drupal 8 (if it's out there, please direct me!). Specifically, I'd like to add a small bit of text in the footer that displays the M/D/Y of when the content of THAT page was most recently modified. How can this be done?

Thank you!

You can add a View in views, create a block display, give it a contextual filter of node id from current URL, then output the Changed field and select a date format. You can change the label to "Last modified on" and you're done. Then just place that block in the right region.

Sorry I don't have code or pics, posted from mobile.

Edit:

You can add a last modified date in the footer area of page.html.twig:

{% if node %}

Last modified at {{ node.changed.value|format_date('custom', 'm/d/Y') }}

{% endif %}

This will work also, first is a no-code solution. Example, perhaps your requirement changes and you need to also show the time next to the date. That is just a simple update to the View, no twig edit + git + deploy + etc needed. Some prefer one way over the other.

Also, and I am going out on a limb here - you should know that node.changed only contains the last modified time on that node. If you changed other things on the page, like menu links in the header, or added new blocks, that date value won't change, because they are not part of the node object being viewed.


Advantages of using context for sitewide blocks? As far as loading time is concerned I haven't seen anywhere, including the documentation, if there is a real advantage in using the context module to display sitewide blocks over the Drupal default block page.

For D7, some say Drupal loads all blocks for every page but displays only those that are visible. If so, then using context could dramatically speed up a site with many blocks. Others say D7 only loads the visible blocks.

But, which is it? Is it worthwhile to switch to context for block display? Does any one really know?

Thanks. :)

Yes you should. It is worth while to switch to Contexts (Irrespective of your case about site wide context blocks)

Reasons

When you have blocks which appear only on a certain pages, the time taken for loading the block is saved.
In one page you can have a block in region A and on other page you can have the same block in region B.
When you change your themes you need not worry a lot about changing all the settings. You just need to make sure that they have common regions.
You can think on a page by page and then assign blocks.
Context has a simple and clean UI of its own, including drag and drop facility.
It is not path dependent. It means you can use conditions other than the path to set a context.
Can be extended with Context UI which can be a replacement for Panels and light weight too :)
In addition to placing Blocks there are many more reactions as well.
Contexts can be stacked meaning there can be multiple contexts for a single page. So you can have a site-wide context to place the headers and footers, then a node context which will perform something only on node pages and then one more context which will be active only on say node/33.
In short think of it like Rules module for the Layouts.


Drupal 8 block css add I am using a fresh D8 install. I have created a custom block with a token which I have added to a header. The block is themes from somewhere to float left. If I, through "inspect" in the browser, add an element to float right. All my spacing works out great. I dont want to change other site feilds. Just this block and/or content to float right

How do I add CSS to get this block content to float right? Specific files would be handy or ? Your advise?

The html I have copied from the inspect looks like this

Pro Safety

Thanks for Im sure a simple fix

The CSS changes are applied through a subtheme, but if you don't have access to that or only need to make small adjustment you can use the CSS Editor module to add your CSS.

The HTML you supplied doesn't seem to have a unique attribute you can use to target it reliably. Is there are wrapper div with an ID attribute around that code?

With classes you will likely style more than one component, this selector targets elements with both these classes:

.field--name-body.field--type-text-with-summary {
 float: right;
}

BTW you need to test your code in different browsers and browser window sizes to make sure you're not breaking the layout in some cases.


Undefined variables error I was working on transferring my website to a new folder. Same database, just a new folder. Worked a bit on the new address, etc.

When I went back to the old address, website is not working anymore. More precisely, it throws a lot of "undefined variables" alerts that clearly have to do with the theme, but I'm pretty sure I have not touched any files there...

Notice: Undefined variable: site_logo in include() (line 16 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: site_logo in include() (line 18 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: site_logo in include() (line 21 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: hgroup_attributes in include() (line 28 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: site_name_attributes in include() (line 31 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: tag in include() (line 100 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: primary_local_tasks in include() (line 102 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: secondary_local_tasks in include() (line 117 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).

are the kind of errors that I get. I'm using the theme Corolla. Can you please provide any lead as to what might be causing the error?

Thank you!!!

I managed to clear the cache by emptying all the _cache tables in the database. I then navigated to the theme (Corolla) settings page and clicked on save settings.

And gone. All errors now seem gone.

Thank you very much Patrick K, I wish I could vote your suggestion up! (Will do if you repost it as an answer rather than a comment.)
Cheers!


Trigger whenever a user uploads an image I would like to enable certain actions to occur whenever a user uploads an image, namely movement to s3 and adding an entry in the db for site and metadata purposes. What would be my first steps in accomplishing this?

If you're using a field field in Drupal 7, you could accomplish this with the use of stream wrappers, core-supplied file API hooks, and a file field.

See the file examples in the Examples for Developers module. Also read through the 'Stream Wrappers and You' post from Advomatic for some background.

For more advanced triggered actions, you could also consider using the Rules module to react to a file being uploaded to the site via a new node or other entity type.


Tags for content type and search by this tags i created a vocabulary called "Tags" and then a field on my content type using this vocabulary. I can create my content and add the tags, but then i search for the tags that im using and i get no results on the search. Somebody can help me? Thanks!
Drupal 7.44

You can try to use the Term Search module


How to remove an option from an exposed filter with a drop-down list? This is this drop-down list for the field field_gender on the view whose name is members:

M|Male
F|Female

I know the following callback is executed (tested with var_dump...), but it doesn't do what I think it should do: Provide only the option which value is "M" for "Male" (this choice is decided programmatically, Views UI won't work).

Here is the callback:

/**
* Implementation of hook_views_pre_...().
*/
// function mymodule_views_pre_render(&$view){
// function mymodule_views_pre_build(&$view){
function mymodule_views_pre_execute(&$view){
    if ($view->name == 'members') {

        // get our filters
        $filters = $view->display_handler->get_option('filters');

        // Force
        $filters['field_gender_value']['value'] = array('M' => 'M');

        // apply changes
        $view->display_handler->override_option('filters', $filters);
    }
}

You use hook_form_alter:

/**
 * Implementation of hook_form_alter().
 */
  function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
  case 'views_exposed_form':
    // Force
    $form['field_gender_value']['#options'] = array('M' => 'M');
    break;
  }
}


Concatenation with %keyword in mini-panels Someone posted another question How does one concatenate fields in title field in Panels (Pages)? but its not working for me.

I need to concatenate a custom text as prefix with %node:field_city_title keyword while adding a node field in min-panels.

I tried with Event in %node:field_city_title , Event in%node:field_city_title and searched a lot but nothing works for me.

If you any idea, let me know

I've figured out but not sure either it's a standard way or not but I believe override title field is not accepted "prefix or postfix" for %keyword like mentioned in the question.

Solution

1) Removed tag h1 from the attached image in the question.

2) Created new tpl named as panels-pane--event-node-title.tpl.php and added some code in it

<div class="pane-content">
  <?php if ($title): ?>
  <h1> <?php print $title; ?> </h1>
  <?php else : ?>
    // Here we can set any prefix or postfix within the tag
    <h1> Event in <?php print render($content); ?> </h1>
  <?php endif; ?>
</div>

$content variable will get content of the field along with its all settings (ID, class, tag etc.)

I hope this will help someone.


Sending an email blast only goes to certain users A little background on the problem:  I have been tasked with figuring out a problem in a Drupal site that I have no experience with.  I have done Web Development using PHP, etc. but never used Drupal.  I have a parent site with 3 sites underneath, and roles for each user (can be members of all sites or just one).  I have a rule that sends an email out to these users after certain content is submitted.  However, not all of the users receive the emails (about 150-180 users per email blast).

Does anyone have suggestions as to how I can go about debugging and figuring out this problem?  I have to fix this by tomorrow.  Here is what I have done so far:

-Made sure users were assigned to the role in the email rule.
-Unchecked the box "send only to active users"

Any help is appreciated!

Default PHP mailer has a lot of issues, and sometimes mails are not received or accepted by the servers as this a common method for sending spam.

A good practice is to use the SMTP module (https://drupal.org/project/smtp) for sending emails. You need to connect it to a server (eg. google) for authentification and then it replaces the default drupal php mailer.


Drush on distributed server architecture We have distributed cloud server architecture - storage, database and webserver. We have installed drush 8 on storage server, as there are project files. We do not have direct ssh to the database or webserver.

When I try to run e.g. drush cc all on this storage server, response is error: PDOException: could not find driver.

I suppose that problem is, that database server is remote (database is not on storage server), so drush cannot find SQL driver. Settings.php is configured correctly, site is running, only drush has problems.

I read more about drush aliases, or syncing, but I do not think, that this is the solution for my problem. Do you know how to solve this problem and how to use drush on this type of server infrastructure?

Thanks for your help.

If it is possible for your Drupal site to access the database, then it is possible for Drush to access the database. In fact, Drush uses Drupal code to bootstrap, so it should really work the same.

What appears to be the issue here is that you do not have all of the same extensions (esp. the PDO extension) available in php-cli as you do in php-cgi or php-fpm or whatever you are using for your web server. Another issue that can sometimes come up is permissions, if you are running Drush under  a different user than the web server.

Finally, it is also worth noting that not all Drush commands go through the Drupal bootstrap to access the database. The sql-* commands use the database commandline tools (mysql, psql, etc.), so these Drush commands may not work (e.g. if the database commandline tools are not installed).


How do I execute functions on a custom module? I am writing my first custom module and would like to test its functionality, but am not certain how to call functions to run them from within Drupal.  The module is installed.

You can call specific functions for testing using drush (drush ev "command();") or using the devel.module block/page (at /devel/php or so).

However, apart from some quick tests, in 99% of the cases, Drupal is going to take care of calling the functions of your module, through hooks and callbacks.

E.g., to have your module display something in your site, you need to implement hook_menu(), define a page callback then simply visit the defined path.


How can I write users table data in custom file? I have a number of users in my site,I have developed custom module for drupal mail functionality.

But I want to write test cases for custom module.

then here is the problem is how can I get the (db_select) users table data and write down in .test file.

for example in .module file we use like this:

$select = db_select('{users}', 'users');
$select -> addField('users', 'name', 'users_name');
$select -> addField('users', 'uid', 'uid');
$select -> addField('users', 'mail', 'users_mail');
$select -> addField('users', 'created', 'users_created');
$select -> addField('users', 'access', 'users_access');
$select -> addField('user_relationships', 'requester_id', 'requester_id');
$select -> addField('users_roles', 'rid', 'role_id');
$select -> addField('users_user_relationships', 'mail', 'users_user_relationships_mail');
$select -> leftjoin('user_relationships', 'user_relationships', "users.uid=user_relationships.requestee_id");
$select -> leftjoin('users', 'users_user_relationships', "user_relationships.requester_id=users_user_relationships.uid");
$select -> innerjoin('users_roles', 'users_roles', "users.uid = users_roles.uid");
$select -> condition('users.status', 0, '<>');
$select -> condition('users_roles.rid', array(
  '4',
  '5'
), 'IN');
$subresult = $select -> execute();

and i have wrote .test file like this

<?php
class BiTestMailsTests extends DrupalWebTestCase {
protected $privileged_user;
public static function getInfo() {
  return array(
    'name' => 'Test Mails',
    'description' => 'Tests for the mail module.',
    'group' => 'Test Mail Group',
 );
 }
public function setUp() {
   parent::setUp(array('mails'));

   }

public function testmail() {
    // Create an administrative user.
    $account = $this->drupalCreateUser(array('administer actions'));
    $this->drupalLogin($account);

      //database files
    $results= db_select('users','u')->fields('u',array('uid','name','mail','created','access'))->execute()->fetchAll();
    if($results){
     foreach($results as $res){
     $user_fields = user_load($res -> uid);
     $this->verbose('language:'.$language);
     $string= 'uid:'.$res->uid.' ,name:'.$res->name.' ,mail:'.$res->mail.',created date:'.$res->created.',Access:'.$res->access.'\n\r';
     $this->verbose($string);
    }
    }
    }
    }

but temporary user created and that values are getting.
i don't want temp values,i want database USERS table values.
How can I write down users information(name and email) in .test file?

Your just need get your select put it in FOREACH and write down in file.(something like below code can help you_

$results= db_select('users','u')->fields('u',array('uid','name','email'))->execute()->fetchAll();
if($results){
     $fh=fopen(drupal_get_path('module',   'yourcustommodulename').'/usertest.txt','w+');
     foreach($results as $res){
     $string= 'uid:'.$res->uid.' ,name:'.$res->name.' ,email:'.$res->email.'\n\r';
    fwrite($fh,$string);
  }
  fclose($fh);

}


How to dynamically add css after image upload on node? I have used drupal_add_js() for my profile content type and modified CSS using jquery .css() function. in this content type i have image upload field but when i upload image the image preview display is changed. my question is how can i apply the style for image preview field which is added after image upload.

If you use drupal behaviors to modify the css, it should run after the ajax too.

eg.

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).css('backgroud-color', '#ff0000');
    }
  };
})(jQuery);

More info at: http://drupal.org/node/756722


Copying field values from one EntityForm to another on submit I'm using Drupal 7 and the Entityform module to build a form for people to fill in on my website.

This form will be filled in by a parent and contains some data about his child. There will be 2 buttons:

1 for submitting the form data (default submit button/function)
1 for submitting the form data + opening a new form (of the same type) for a 2nd child (custom submit button/function).

Since this 2nd child will have a lot of data (address, last name,...) that's the same as the first child I'd like to already have those fields filled in in the 2nd form (by using field values from the first form). The same can be repeated for a 3rd child, a 4th child,...

This is my code so far:

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

    if ($form_id == 'generiek_inschrijvingsformulier__entityform_edit_form'){
        $form['submit2'] = $form['actions']['submit'];
        $form['submit2']['#value']='Inschrijven en ook een broer inschrijven';
        $form['submit2']['#weight']=100;
        $form['submit2']['#submit'][1]='extra_inschrijving_default_wp_submit';
    }
}

This code added another submit-button and attached a submit handler (this works).

function extra_inschrijving_default_wp_submit($form, &$form_state){
   $values = &$form_state['values'];

   $prepopulates = array(
      'edit[field_entity_reference][und]' =>
            $values['field_entity_reference']['und'][0]['target_id'],
      'edit[field_1][und][0][value]' => $values['field_1']['und'][0]['value'],
      'edit[field_2][und][0][value]' => $values['field_2']['und'][0]['value'],
   );

   $form_state['redirect'] = array(
     'node/11',
     array(
        'query' => $prepopulates,
     ),
  );
}

Here I copy some field values from the form that will be submitted into the new form that has to be filled in. The parent should still be able to change the fields if he wants to.
Both the normal fields and the entity reference field (select list) are copied/prepopulated successfully, but if the parent changes the entity reference field on the new form it still contains the old, prepopulated value when he submits it (although visibly something else is selected in the list).

If you don't mind using query parameter for passing value. Prepopulate would be your choice.

Example code:

function extra_inschrijving_default_wp_submit($form, &$form_state){
  $values = &$form_state['values'];
  $prepopulates = array(
    'edit[title]' => $values['title'],
  );
  $form_state['redirect'] = array(
    'node/add/article',
    array(
      'query' => $prepopulates,
    ),
  );
}

$prepopulates is an array for query parameter which will pass the pre-filled values to the node add form. The array keys specify the fields prepopulate to. You can learn how to set the key from the handbook page.

At this moment, the latest stable version 2.1 has a known bug and it is discussing here. If you the module is not working on some field, you may need to add the patch in the thread. I don't recommend the older stable version because 2.1 has fixed an exploit.


Nodes appearing but when clicked "page not found" I recently migrated a site and some nodes don't appear in the content list but they do appear in Views I've created. When they're clicked however (example.com/node/123) it just returns a Page not found.

The node is in the database, both in the node table and the node_revisions as well as the relevent CCK tables.

What could possibly be causing this?

I had this problem, it only affected certain nodes. When investigated in db all values corresponded between node and node revisions tables so I initially assumed it wasn't related to values in those tables.
Checked url_alias table and all seemed well there too, site is multilingual so checked the variables table for discrepancies between multilingual paths auto values for custom content types and all was also well. Rebuilding the menu router didn't help either. I already tried resetting all node access permissions as suggested here. Honestly I was just about out of ideas, then thankfully I came across this post :D
The problem had come from where i had imported some node content from a custom module i wrote to ingest nodes from xml (which worked fine) but since the import was done the user account which had done the import had been removed. This meant all the multilingual imported nodes were still linked to that, now non-existent user account's uid.
A simple sql query in phpmyadmin set all my nodes to be owned by admin (uid:1)

UPDATE node set uid = 1;
UPDATE node_revisions set uid = 1;

This fixed my perplexing issue. I propose a patch so that if a user account is removed Drupal optionally checks all nodes belonging to that user and updates them to uid: 1 so nodes added by a deleted user account aren't suddenly inaccessible to the rest of the site including uid 1 (admin).
This was frustrating as a sensible sort would naturally assume that uid 1 will always have view/edit access to any node content on the site regardless of if it is, disabled, enabled or added by some mugwump.
I wish you good Drupaling!


How do I bulk update the alt and title tags of images Is there a way to bulk update image title and alt tags? Where do alt and title tags are saved in the database?

Rewriting the D7 code of How to bulk update image alt and title?

$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties(['type' => 'article']);

foreach ($nodes as $node) {
  $node->field_image->alt = $alt;
  $node->field_image->title = $title;

  $node->save();
}


How to parse current page URL query parameters to create link using l() function I have a view in D7 with a few exposed filters.  This view generates a URL/page like this:  example.com/node?location=XXX&check-in=XXX&check-out=XXX&lang=XXX.

I am looking to build a link passing in a couple of the current page's query parameters from above.  I am using the l() function and currently have the following:

print l("link_name","http://www.example.com/path", array('attributes'=>array('target'=>'blank'), 'query'=>array('lang'=>'en', 'currency'=>'USD', 'standardCheckin'=>$view->get_exposed_input(), 'standardCheckout'=>$view->get_exposed_input())));

I am looking to pass in the check-in and check-out parameter values from the views-generated page in to my link function's standardCheckin and standardCheckout keys.  What I currently have obviously does not work.  I'm using the view::get_exposed_input function to pull in the values that are in the exposed filter, but it is pulling in ALL of the query parameters.  This function does not seem to have any query parameters to limit the query.  I also looked at using drupal_parse_url and drupal_get_query_parameters, but can not get those to work either (again, getting all parameters - can not limit to just the two I need).

I can pull the values from either the URL or from the exposed filter.  My PHP is a bit limited, but what is the best function to use (and a nudge syntactically on how to limit the query would be appreciated)?  Or is there a better Drupal method for achieving this?

Maybe something like this would be sufficient?

$url = drupal_parse_url('example.com/node?location=XXX&check-in=XXX&check-out=XXX&lang=XXX.');
$desired_params = array_intersect_key($url['query'], array_flip(array('check-in', 'check-out')));

array_intersect_key() will return the values in the first array whose keys also exist in the second array, while array_flip() inverts the values in the array with their keys, actually generating something like the following (in my example):

array(
  'check-in' => 0,
  'check-out' => 1,
)

You can probably use the same approach or a very similar one with view::get_exposed_input, which is probably the best way of getting the data you need.

I didn't get that you also needed to rename the parameters. Then I don't think there's any advantage in filtering the parameters, just pull out the ones you need by hand.

$params = drupal_parse_url('...');
l("link_name","http://www.example.com/path",
  array('attributes' => array('target' => 'blank'),
  'query'=>array(
    'lang' => 'en',
    'currency' => 'USD',
    'standardCheckin' => $params['query']['check-in'],
    'standardCheckout'=>$params['query']['check-out']
   )
  )
);


Changing label on node edit form I want to change a label/string on a node edit form for a date field.

The label is, "Show end date" - I want to change this to, "Show end date (optional)", but I can't find where this is set anywhere. My guess is that it is some sort of theming change - I took a look at the node_form and saw nothing.

You can easily do this using hook_form_alter(&$form, &$form_state, $form_id) Alter

Hook_form_alter is working before your form shown
Use hook_form_alter in Your site theme template.php file.

Like your theme name is bartik,then use this function their

function bartik_form_alter(&$form, &$form_state, $form_id)
{
//Firstly get form id then use below code

if($form_id=='Your_edit_form_id'){
//here print $form and chek which field label you want to change and then alter that field //like

$form['date'][#label]='Date Field(optional)';
}

}

may this will help you.


Convert an exported rule to a programmatic rule I created a Rule through the GUI and it works fine.  I would like to convert this into a programmatic rule that I can include with my custom module.  This way I dont have to re import my rule every time I set up a site.  Is there any way to do this (other than manually)?

You can implement hook_default_rules_configuration()

  This hook is invoked when rules configurations are loaded. The implementation should be placed into the file MODULENAME.rules_defaults.inc, which gets automatically included when the hook is invoked.

and use entity_import() to convert the export string into something Rules will understand. e.g.

function MYMODULE_default_rules_configuration() {
  $items['my_rule'] = entity_import('rules_config', 'EXPORT STRING HERE');

  return $items;
}


Add views block to views header I want to have the views header elements after exposed filters, so i try to get the filters in the header. For that, i expose them in a block, and try to add that block to headers, but no success. I also tried to show the filters-block on the view's page (an admin path) via the block settings (show in content area, only on pages admin/content/myview), also no success.

To add a generic block to a views header via UI, there's the module
https://www.drupal.org/project/views_block_area

On the module page it says

  Blocks that are generated by views, can't be selected. These blocks can be inserted by views areas.

But i can't see how to do that. When i add a view area to my view's header, i have the view which generates the exposed-filters block, but the block is not listed, only the default and an attachment i have in that view.

The easiest way to do that is to modify your View template. Identify it in the third column (Advanced), section Theme : informations (by default views-view.tpl.php). Find it (usually in sites/all/modules/views/theme). Then you will just have to reorganize this tpl file. In your case, you just need to switch two sections like this :

<?php if ($exposed): ?>

  <?php print $exposed; ?>

<?php if ($header): ?>

  <?php print $header; ?>


Why isn't there a pager and it doesn't show two records per page? $query = db_select('node', 'n');
$query->condition('n.type', 'article', '=')
  ->fields('n', array('nid', 'title', 'uid'))
  ->extend('PagerDefault')
  ->limit(2);
$result = $query->execute();

while($record = $result->fetchObject()) {
  echo $record ->title."<br/>";
}

$output .= theme('pager', array('tags' => array()));

I put the above code in a page template file. Why isn't there a pager and it doesn't show two records per page?

The code is wrong: Once you extend the query object, you need to save it, or it will get lost. The correct code is the following one.

$query = db_select('node', 'n');
$query = $query->condition('n.type', 'article', '=')
  ->fields('n', array('nid', 'title', 'uid'))
  ->extend('PagerDefault')
  ->limit(2);

$result = $query->execute();

foreach ($result as $node) {
  echo $node->title . "<br/>";
}

In my case, the result is the following one.

  Appellatio Fere Huic MetuoLudus Vereor

See the note shown on Extenders:

  Note that $query is not altered in place. The new object is returned from extend(), and if it is not saved to a variable it will be lost.


Carry a field in WebForm I would like to carry a field (i.e. Name) entered on the 1st page of a multi-page WebForm and reflect that field on the Confirmation (Thank You) page.

How would I go about doing this?

I am using Drupal 7.

You can achieve it as follows:

Copy webform-confirmation.tpl.php from /webform/templates and into your theme's template folder
Rename it to webform-confirmation-{nid}.tpl.php to apply the template to a specific webform
Make sure you clear Drupal's cache after placing or renaming the template file
Add the following snippet

include_once drupal_get_path('module','webform') . '/includes/webform.submissions.inc';
$submission = webform_get_submission($node->nid, $sid);
// All the submitted values will be here, access the necessary values from this object.
// print_r($submission);

I tried this snippet, and it works. It was taken from Print submitted data on confirmation page.


Multiselect values not getting saved in hook_settings()? This is the code I have implemented in my module which is working fine!

/*
 * This is a helper()
 */
function MYMODULE_feeds($page_id = '') {
  foreach($pagefeed['data'] as $feedval) {
    $post_type[] = $feedval['type'];
    if ($feedval['type'] == 'photo') {
      if(array_key_exists('message',$feedval)) {
          $messageFeed[] =  $feedval['message'];
          if ($timeshow == 1) {
            $created_statmp = $feedval['created_time'];
          }
          $i++;
      }
      if($i == variable_get('no_feeds')) {
          break;
      }
    }
  }
  $post_type_unique = array_unique($post_type);
  $post_type_unique_serial = array_values($post_type_unique);
  variable_set('post_type_unique_serial', $post_type_unique_serial);
  return theme('MYMODULE_feed_theme', array('pagefeeds' => $messageFeed, 'time_stamp' => $created_statmp));
}

After that I have done this in my module's admin.inc file

/*
 * Implements hook_settings()
 */
function MYMODULE_settings($form, &$form_state) {
  $form['MYMODULE']['post_type'] = array(
    '#type' => 'select',
    '#title' => 'Select your post type(s) to show',
    '#default_value' => variable_get('post_type_unique_serial'),
    '#options' => variable_get('post_type_unique_serial'),
    '#multiple' => TRUE,
  );
  return system_settings_form($form);
}

Problem is that, I'm getting the values there, but when I'm saving that every field is saving the updated values, expect this field.

I'm not getting where I've made the mistake?

1) If variable_get('post_type_unique_serial') returns an array to populate the options, then it can not also be used for setting the default value, as this should be a single key within the array.

2) Generally it is good practice to use the same name for the variable as the form element if it is being used to set the default value eg $form['MYMODULE']['post_type'] and '#default_value' => variable_get('post_type'),


How do I remove a view? I installed Calendar and created a few views. I decided that I want to begin anew with fresh settings, so I disabled Calendar and removed it. The undesired view disappeared. I extracted a fresh copy of Calendar to sites/all/modules and enabled it, but the old view appears again.

Do you know how to delete them?

If you customized a default view provided by the calendar module, you can revert it back to the default by clicking on "revert" (Click on the pointer behind edit).


permission for user profile image I would like to give permission for user profile image to registrant users only. i.e. anonymous user who visit the site can see the default profile image only in the user list and registrant users can see the real image of the user.
How can I make it? Does it required changing the setting or utilizing view?
Thanking you in advance

The easy way then is to hard code this into your theme.

Open your template.php file in your theme's root folder. Add the following function in that file:

function MYTHEME_preprocess_user_picture(&$vars){
  if (!$vars['logged_in']) {
    // user is anonymous
    $path = variable_get('user_picture_default', FALSE);
    $style = variable_get('user_picture_style', FALSE);
    if ($path && $style) {
      $vars['user_picture'] = '<img src="' . image_style_url($style, $path) . '" />';
    }
    else {
      $vars['user_picture'] = '';
    }
  }
}

Replace MYTHEME with the machine name of your theme (similar to the MYTHEME in MYTHEME.info file). Then make sure you add a default picture at:

admin/config/people/accounts

The easiest is to just paste in this in the Default picture text box:

public://default-picture.png

and under the folder sites/default/files include the default-picture.png file. But that is obviously just a suggestion and you can put your picture anywhere.

If you don't see any default picture when viewing the site as anonymous then your default picture path is incorrect. Test it by creating a new user without a picture.


Sort the entity obtained from the Query class with values from the Statistics module I am using the following code to sort the published nodes basing on the value stored from the Statistics module.

$query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->range(0, 5)
      ->sort('totalcount', 'DESC' );

$result = $query->execute();

The code is causing the following exception.

  Drupal\Core\Entity\Query\QueryException: 'totalcount' not found in Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable() (line 316 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).

How do I sort nodes basing on the totalcount value stored from the Statistics module?

The code you are showing doesn't work because totalcount is not a property set for the node entity. That is a value saved in a different database table, not used from the node entity. See statistics_get(), which retrieves the value you are looking for.

  if ($nid > 0) {
    // Retrieve an array with both totalcount and daycount.
    return db_query('SELECT totalcount, daycount, timestamp FROM {node_counter} WHERE nid = :nid', array(':nid' => $nid), array('target' => 'replica'))->fetchAssoc();
  }

Since the entity query doesn't allow to join tables, you need to:

Add a tag to the entity query you are using
Implement hook_query_TAG_alter() to alter the queries with the tag you added (Replace TAG with the tag you added to the entity query)

node_query_node_access_alter() is the implementation of that hook done from the Node module to allow an entity query to return just the nodes the currently logged-in user has access. You can use its code as guide to write your own implementation.

For example, I would start trying with the following code.

$query = \Drupal::entityQuery('node')
  ->addTag('statistics_totalcount')
  ->condition('status', 1)
  ->range(0, 5)
  ->sort('totalcount', 'DESC');

$result = $query->execute();

function mymodule_query_stastics_totalcount_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->join('node_counter', 'nc', '%alias.nid = n.nid');
}


Listing Latest Blog Post in a Block This is my first time using Drupal so I'm not entirely sure if I'm asking the right questions. I come from a WordPress background so I may be approaching this problem in the wrong manner.

I'm attempting to create a list of the latest blog post in a block that I created. How would I go about doing something like this? Would I list it via PHP within the block editor or is there some type of module (?) that I should be using? Any help would be much appreciated.

The easiest way is to create a block view of nodes (of whatever type you are calling a post). You actually create the block in Views. Views are one of the things that separates Drupal from WordPress. If you have no idea what they are, check out this page.


Private filesystem does fire 403 on every role and file Like the title might expect I am not able to view any file that i am  delivering through the private file system. Only if I bypass the access check via role settings.
I tested it a minute ago with a fresh d8.9 installation. Here images are are delivered (statuscode: 200). I my main project I receive a 403. Why is that so ?
Drupal does create the private files and as admin (bypassing) I also can see the file. As non admin (authenticated user) I cannot.
How can I debug this issue?
A theory I have read said something about varnish setting... I searched  the whole project without finding any script mentioning "varnish". I spend now good 6 hours... checked roles, scripts and so on. I could now start a crazy adventure by deinstalling 80+ modules until it might work or somebody could give me a hint how I debug this madness?
Thanks in advance

Guests on the left | authenticated users on the right

If you need to debug access at the Drupal application level, then look at FileDownloadController::download; it's the controller method for the /system/files/{filepath} path; you can use your tool of choice to inspect the execution flow from request to the returned response object.
If the issue is outside the Drupal application level (e.g. web server, varnish) then it will require further stack troubleshooting.


What is the correct way to create a new ImageItem and attach it to a FileFieldItemList? I'm writing a custom module to pull in some images from an old D6 installation (the cck plugin is failing to connect images to the correct node). So I need to be able to create new ImageItem and add them to the field.

Can I simply create a new object like:

$field = $node->field_gallery;
$img = new ImageItem();
$img->setValue(array(
   "target_id" => 123,
    "alt" => "Alt text"
   "title" => "Title text"
));

$field->set($delta, $img);
$node->save();

Or do I need to do something with entityManager to get it linked properly?

You don't need any of that. You just set the values, everything else will be taken care of for you.

$node->set('field_gallery', [
  'target_id' => 123,
  'alt' => 'Alt text'
  'title' => 'Title text'
]);

If you want to have multiple items, use `$node->field_gallery->appendItem($values);


Users who just registered can login & change profile information, but cannot create certain contents until admin lets them Users who just registered can login & change profile information, but cannot create certain contents until an admin says they can. I know this can't be achieved using the Drupal Approved/Not arppoved scheme. Are there alternatives? Maybe with permissions?

If possible, I would also like to use a block(or other means) to let the logged in user of their status/permissions e.g. they can only change profile info, cannot create certain contents, etc.

As Sandesh suggested, give registered users permission to change their profile information, and remove the permission to create content. When an admin sees that a user is qualified to post content, they will give the user the permission. The permissions will be on an individual basis, so we use the User Permissions module.


How to fetch records from entity base on only Day and month? How to fetch records from entity base on only Day and month

Like In DOB need to return those user which has current day and month.

E.g:

$query = \Drupal::entityQuery('user');
$query->condition('status', 1);
$query->condition('field_dob', date('m-d'));
$entity_ids = $query->execute();

In anyone have idea how to do this?

Here we are doing a LIKE query as the question stated that it wants to fetch record on basis of current month and day only not a year .

 $query= \Drupal::entityQuery('user')
     ->condition('field_dob','%'.date('m-d').'%', 'LIKE')
     ->execute()


cck fieldgroup tabs appear but all fields in one tab I am using cck fieldgroup tabs to group various fieldsets under different tabs and I want them to appear in tabs to anonymous user.

Somehow the tabs are not working. The tabs are all there sitting above but all the fields within each fieldset are all shown on the same page and the tab links work as if they are internal links for the same page. You click on any link and you are moved down to the fields in that fieldset on the same page.

I looked into the generated page in firebug and it came out that the classes responsible for generation and grouping of tabs are all wrong in the div and ul tags. when I changed them to the correct ones using firebug , they all looked fine in browser.

Now I dont know how are these classes put into div tags in the backend so that i can rectify it. Can someone help please.?

Check the permissions to ensure the fields are available to the anonymous users.


copy image over image in Content body? I want to overlay an image over another in the Content body. How do I achieve this? I do not know much about coding or themeing.

Could someone guide me please?

Thanks

You can add your own CSS classes to the images via the WYSIWYG editor. The code provided on https://stackoverflow.com/questions/48474/how-do-i-position-one-image-on-top-of-another-in-html should do what you are looking for:

.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
}
.image2 {
  position: absolute;
  top: 30px;
  left: 70px;
}


Using Drush to update Drupal 6 core on multisite installation I'm running multiple sites on a single Drupal 6 installation. I'd like to use drush to update Drupal core to the latest version without having to unlock update.php via settings for each site and then going to update.php for each of the different urls (there are over 10 sites).

Is there a drush command to update drupal core and run update.php for all sites at once?

There's no one single command to do it but we use a bash script that follows this pattern:

ls sites folder for all directories
pass resulting output to drush -l $variable sql-dump > /home/user/backup/$variable.sql
pass resulting output to drush -l $variable updb --yes

Hope this helps.


drupal  shows empty content because of memcache I have a Drupal (pressflow 6.22) website and I am using memcache as a caching level for my website/server. Sometimes some node (articles) that has been published on my website shows empty content when browsed (Specially with IE).

When I do below on the server that has memcache

$ telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
flush_all
OK
quit

and refresh the page using the same browser, it is displayed properly. Has anybody faced the same issue?

Have you installed and configured drupal with the module for memcache - http://drupal.org/project/memcache ?

There is also a handbook page that will be able to help you http://drupal.org/node/1131458


Hook into Group module I'm creating a module for Drupal 8 that will auto fill some content in a add content page. Now I need to have a way to group different contents in one group. I found the Group module that does the job, but I cannot find a way to hook into it. Can someone help me with this?

I want to have a few check boxes, for every group, in my add content page. When the user select a group and create the content it will be added to that group. How can I create the checkboxes for the groups where the users has access for. Also how can I auto add the content to the selected groups?

Sure it is  possible but you'll have to write quite a bunch of custom code to accomplish this.

First let's take a look at how a node belongs to a group. This is done through the GroupContent entity.

Before we can actually relate a node to a group, we'd have to install the entity to the group type. This can be done by going to:

Groups -> Group types -> Set available content (can be found via the Operations action button).

First we want to add the possibility to choose one or many groups the node being created can belong to. So we'll have to determine if the node we are trying to add is first installed and then get the groups.

Here is a very simplified example on how to do that by using altering the node and then finding out which group types the current node type is installed to, finally getting the groups and exposing them as checkboxes.

It does not currently care about the user actually having access to that group yet.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_group_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();

  $groupPluginManager = \Drupal::service('plugin.manager.group_content_enabler');

  // Get the group types this node type is installed to.
  $plugin_id = 'group_node:' . $node->getType();
  $groupTypes = $groupPluginManager->getGroupContentTypeIds($plugin_id);

  // This node is not installed to any group types.
  if (empty($groupTypes)) {
    return;
  }

  // Normalize group type ids to just the type name
  $groupTypes = array_map(function($groupType) {
    return explode('-', $groupType)[0];
  }, $groupTypes);

  // Get groups...
  // @TODO: Sort, group the groups to its group type?
  $query = \Drupal::entityQuery('group');
  $query->condition('type', $groupTypes, 'IN');
  $groups_ids = $query->execute();

  // ugh... no groups though?
  if (empty($groups_ids)) {
    return;
  }

  // Create a checkboxes with all groups without any grouping of type
  $groups = \Drupal\group\Entity\Group::loadMultiple($groups_ids);
  $options = [];

  foreach ($groups as $group) {
    $options[$group->id()] = $group->label();
  }

  $form['groups'] = [
    '#type' => 'checkboxes',
    '#title' => 'Attach to group',
    '#options' => $options,
  ];

 foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'custom_group_submit_handler';
    }
  }

}

So we have a list of groups on the node form, how do we actually relate them to the checked groups? We added a submit handler custom_group_submit_handler Let's write that to, again very simplified:

function custom_group_submit_handler(&$form, FormStateInterface $form_state) {

  $node = $form_state->getFormObject()->getEntity();
  $groups = $form_state->getValue('groups');

  // Iterate through each submitted group
  foreach ($groups as $group) {
    $groupEntity = Group::load($group);

    // Assemble the type.
    $type = $groupEntity->getGroupType()->id() . '-group_node-' . $node->getType();

    // Create the relation.
    $groupContent = GroupContent::create([
      'gid' => $group,
      'entity_id' => $node->id(),
      'type' => $type,
    ]);
    $groupContent->save();
  }
}

This took a bit longer to write than I expected, so therefore there are some details you will have to implement yourself, like:

Take group access and permission under consideration
You'd most likely want to clean up the code and move to a more object-oriented approach
You want to handle both add/edit and deletion for the node relation to a group.
You want to make sure the node is not already related to the group.

etc.

Hopefully this is an start to get you further on your objective!


How to override output of checkout page in Commerce I want to override the output of the order completion page. I need to include custom markup, as well as data from the order. As a matter of personal preference (and for organizational purposes), I'd rather do this in code, in my module, rather than in Rules. Can anyone point me in the right direction?

It looks like using hook_commerce_checkout_pane_info_alter(&$checkout_panes) or hook_commerce_checkout_page_info_alter(&$checkout_pages) would be the best options. There are also hooks that allow you to create your own checkout panes/pages from scratch if necessary (hook_commerce_checkout_pane_info() and hook_commerce_checkout_page_info()). I would suggest reading more about them here and checking out the specific examples (about page/pane info hook implementations) that you can find in the Drupal Commerce submodule (mostly Checkout) files.


Display image field from nid I'm trying to print the image field from a node using the nid in the url.

$nid = $_GET['field_item_request'];

Is there a specific way to do this?

$nid = arg(1);
$node = node_load($nid);
$image = field_get_items('node', $node, 'field_item_request');
$output = field_view_value('node', $node, 'field_item_request', $image[0]);
print render($output);


Create series of Events I've got the following task:
i have a site which should be used as a kind of team calendar. there are lots of people in different roles (moderator, member) and moderators can create events (in my case ordinary nodes with time field) and members can now leave comments. there is not much more functionallity behind it, so no subscription, ... for events.

the problem i'm facing right now is the creation of events. normal events which occur once in a time are no problem, but there are much events that happen in a periodic time interval, e.g. every week.

so i need a possibility to create such a series but have them all as seperate nodes, to be able to edit individual dates. think about this scenario: the regular meeting x is scheduled every sunday from 10:00 to 12:00, but somehow it need to be changed in week 23 from 11:00 to 13:00.

is there a module for that?

Basically you need recurring meetings like in outlook.

I think you will have to create a rule based on flags. The flag could be something like daily, weekly, bi-weekly, monthly or yearly. Once an organiser selects the flag, rule should create nodes with meeting start time in future according to which flag was set.

Also give user an option to select # of events or end duration and you can put this check in your Rule as well to limit the events it creates.


How to convert a D7 db_query object to string? I am trying to perform the following:

$office_ids = db_query('SELECT OFFICE_ID FROM sage.OFFICE');
foreach($office_ids as $office) {
  ...
  $path = 'office-' . (string)$office;
}

However, I am getting the following error:

Recoverable fatal error: Object of class stdClass could not be converted to string in main() (line 31 of /var/www/drupal7/create_nodes_office.php).

How can I cast an object returned by 'db_query' into a string?

Thanks.

I can't see any benefit to doing that, are you sure you're not trying to get the OFFICE_ID value like this?:

$office_ids = db_query('SELECT OFFICE_ID FROM sage.OFFICE');
foreach($office_ids as $office) {
  ...
  // Depending on your database settings this might actually be lower case, i.e. $office->office_id
  $path = 'office-' . $office->OFFICE_ID;
}


How to use the $delta argument? How do I use the $delta argument in hook_block?

I have tried to used one, but there wasn't any effect.

What is the correct way to do this?

As noted elsewhere, $delta allows one module to return many blocks. It may also be easier to understand if you keep in mind that the $delta need not be numeric. It's simply an identifier.

You use the $delta first when responding to the 'list' $op. Each key in the $block array you return will be a $delta that can be used to configure or render that specific block.

switch ($op) {
    case 'list':
      $block['sidebar-links']['info'] = t('Sidebar Links');
      $block['footer-links']['info'] = t('Footer Links');
      return $block;

What this is telling the Drupal system is that the module in question has two blocks, one of which is identified by "sidebar-links", the other by "footer-links".

This will place two blocks on the admin/build/block config page. Should you enable both blocks, they will then be rendered by calls to the 'view' $op with the identifying key as the $delta:

    case 'view':
      switch ($delta) {
        case 'sidebar-links':
          $block['subject'] = t('Sidebar Links');
          $block['content'] = "super weak";
          break;
        case 'footer-links':
          $block['subject'] = t('Footer Links');
          $block['content'] = "super weak";
          break;
      }
      return $block;
  }

As an added bonus, using semantic keys for your blocks will result in easier to read CSS id's. :)


Loading nodes that are only available to the current user How do I programmatically load nodes that are available to the current user?
I used node_load_multiple(), but it seems to directly load nodes from the database, bypassing permissions.

You need to use the EntityFieldQuery class. The following is example code to load all the published nodes whose content type is Article.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED);

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

EntityFieldQuery returns only the nodes to which the currently logged-in user has access. In the case you would get all the nodes for which you know the author user ID, you should use the following code.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('uid', $uid);

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

That code returns all the nodes created in the site. To get only 10 nodes, it sufficient to add a call to $query->range(0, 10) before calling $query->execute().


Additional custom Omega breakpoint CSS files I'm looking to add my own custom wide, normal and narrow CSS files additional to the ones Omega will already look for. I'm aware that by default it'll already search for

YOURSUBTHEME-alpha-default-wide.css

etc

But I was wondering is there anywhere/anything I can set that will allow me to ask it to look for another set of wide, normal and narrow CSS files?

eg: custom-alpha-default-wide.css

And have these automatically be included within the default breakpoint configuration?

I know that I could manually declare all the stylesheets in the .info file, and then copy the media queries into each applicable CSS sheet, however I'm interested to know if it can be done by default

I found out how to do it, you can do it like this in the template.php file of your theme

// Adds the Delta responsive stylesheets
$theme = alpha_get_theme();
$layouts = $theme->grids['alpha_default']['layouts'];
$keys = array_keys($layouts);
for ($i = 0; $i < 3; $i++) {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . '/css/CUSTOM-' . $keys[$i] . '.css', array('group' => CSS_THEME, 'weight' => (120 - $i), 'media' => $layouts[$keys[$i]]['media']));
}

This will now look for your own CSS files called

/css/CUSTOM-narrow.css
/css/CUSTOM-normal.css
/css/CUSTOM-wide.css

And call them in the same way your other breakpoints are called, and if you're looking for the ability to add your own separate stylesheets separate to the normal ones, this'll do it.


How can I find all database schema changes introduced in a CiviCRM major version upgrade? I'm using CiviCRM with Drupal. When upgrading a site to a new CiviCRM major version, it's very useful to know all the database schema changes introduced in the new version, so that any custom code referring to database fields can be amended accordingly.

A case in point is civicrm_contribution_recur.next_sched_contribution -> next_sched_contribution_date in 4.3 -> 4.4 .

"You shouldn't be accessing database fields directly, you should be using the CiviCRM API", I hear someone say. Often that is the preferred approach but even so, API v3 is very closely tied to the database structure and the fields returned by an API call reflect the database field names, so the code would still need amending.

A really useful resource for CiviCRM would be an equivalent of Drupal's  Converting n.x modules to (n+1).x documentation.

One way to do it would be to pore through the CRM/Upgrade/ directory in the new version, looking for schema changes. However these are distributed across multiple files, depending on which alpha or beta version the change was introduced in. E.g. the next_sched_contribution_date change was introduced in this file:

civicrm/CRM/Upgrade/Incremental/sql/4.4.alpha1.mysql.tpl


How do I pass parameters from a form redirect to a controller? I feel like it should be easier to find this stuff out. I'm trying to pass some data from a form submission to a controller, and do something based on that data. What is the most Drupal way to do this (i.e. without accessing the request object directly)?

The form in a custom module that extends FormBase has this method.

public function submitForm(array &$form, FormStateInterface $form_state) {
    $var_to_send = $form_state->getValue('val_to_get');
    $form_state->setRedirect('my.route', [ 'sent_var' => $var_to_send ]);
}

In this case, my.route is configured like this.

my.route:
  ...
  defaults:
    _controller: '\Drupal\custom_module\Controller\MyController::index'
    ...

I have the following method in \Drupal\custom_module\Controller\MyController.php.

public function index() {
    $params = \Drupal::request()->query->all();
    $this->myfunc($params['sent_var']);
}

This page says that what I'm doing is highly discouraged. So how should I access URL parameters in a controller?

In a route callback like a controller you can pull the request with a typed function parameter:

use Symfony\Component\HttpFoundation\Request;

  public function index(Request $request) {
    $query_parameters = $request->query->all();

  }


How do I hide one block and show another in a template My page.tpl.php is set to use a particular block in the right-hand column.

However, I have one template page (created by a module) in which I don't want to display this block.

How can I hide the block ONLY on that page and show a different block instead?

Each block can have various visibility settings. Among others, you can configure that a block should only show up on a number of pages or everywhere except on a number of pages.

So go to the blocks administration page, click on the configure link for that block then make sure "All pages except those listed" is selected and insert the path for which you want to hide it. You can also use wildcards for something like "forum/*", which would hide the block when viewing a forum page.


How to display all the events in a week view of a calendar? I have calendar installed on my site.
I have created a content type named events.
The events content type has three fields title, event time(time only not date and its of type time) and day.

I have modified the block of the calendar view. I have selected the week from calendar format settings so that it should display the week view.

Now I want to list all the events under the monday which have the monday selected in the day field, all the events under the tuesday which have the tuesday selected in the day field and so on.

Format:

Mon              tue                 Wed                 Thu    Fri                 Sat                 Sun

event1          event2

Monday        Tuesday

2:30              2:30

Calendar module creates a node for each day.So all you need to do is create a field of type date in your content type and then create nodes.

Alternatively,you can try using jquery fullcalendar plugin(http://code.runnable.com/UfNTSnKMU1ZgAACt/how-to-add-calendar-using-jquery-and-fullcalendar) and provide data for each day programmatically.


How can I promote content by number of hits (reads)? I would like to create some kind of an algorithm to my website like Reddit might have or even other websites. The algorithm, probably powered by the Rules module, should be able to promote content to the front page by number of hits (reads or visits), or comments a node receives.
I can't seem to find any solution with the Rules module. Any help?!

The near defacto solution for this is the Radioactivity module:

  This module provides a field type which can be used as a hotness
  metric or a regular view counter for entities and for much much more.
  In essense, entities receiving attention (views or actions defined by
  Rules) are heated while inactive ones slowly cool down.

As opposed to straight pageviews, this uses an algorithm to take activity-over-time into account.  With straight statistics / counts, an old page with low activity per day can perpetually stay at the top of lists because it slowly accumulates statistics.

Radioactivity takes time into account, so that your newer pages can appear at the top when appropriate, and then roll off at the appropriate time.  It relies on Rules, but integrates nicely with Views, for building the lists of things (either pages or blocks).


How to translate Groups in a multilingual site? I have created a new grouptype and added some fields to have a "site". And then created a new group with this grouptype. I edited the overview site with some information. Now I would like to translate the site, because I have an multilingual site. Unfortunately I can't find out how to do so.

Is it possible to translate a groupsite on a multilingual site?
Or do I have to create two groups for that?

Your question appears to be somehow related to this issue, which is closed and fixed. That issue contains an image which looks like so:

So check if the version of the Group module that you're using, includes the patch included in that issue.

If you don't have it included, it's probably why you don't have a "group content type" translation option in /admin/config/regional/config-translation. And if you do have it included, go checkout that translation option to see what happens.


How can I stop js script from running on mobile? I need some help with a Zen subtheme using responsive-sidebars.css
I have some javascript that I only want to run if the screen is bigger than 480px.
The javascript is:

(function ($) {
        jQuery(document).ready(function(){
         $('#selllink').trigger("click");
       });
    })

I am not sure how I would restrict this.
Many Thanks
Julie

You can deetect the screen size in Vanilla JS or jQuery. In jQuery you can use height() and width() to get screen size. So you can try this

jQuery(document).ready(function(){
  if($(window).width() > 480){
    $('#selllink').trigger("click");
  }
});

You could also use resize() to check for window resize event.


Help implementing Supersized.js in Drupal 7 I am trying to add Supersized.js into my Drupal 7 site. I have updated Drupal to use the latest version of jQuery, I added scripts[] = js/supersized.3.1.3.min.js to my .info file, and in my html.tpl.php file i added:
<script type="text/javascript">

        (function($){
            alert('test');
            $.supersized({
            alert('test2');
                //Functionality
                slideshow               :   1,      //Slideshow on/off
                autoplay                :   1,      //Slideshow starts playing automatically
                start_slide             :   1,      //Start slide (0 is random)
                random                  :   0,      //Randomize slide order (Ignores start slide)
                slide_interval          :   3000,   //Length between transitions
                transition              :   1,      //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
                transition_speed        :   500,    //Speed of transition
                new_window              :   1,      //Image links open in new window/tab
                pause_hover             :   0,      //Pause slideshow on hover
                keyboard_nav            :   1,      //Keyboard navigation on/off
                performance             :   1,      //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
                image_protect           :   1,      //Disables image dragging and right click with Javascript
                image_path              :   'img/', //Default image path

                //Size & Position
                min_width               :   0,      //Min width allowed (in pixels)
                min_height              :   0,      //Min height allowed (in pixels)
                vertical_center         :   1,      //Vertically center background
                horizontal_center       :   1,      //Horizontally center background
                fit_portrait            :   1,      //Portrait images will not exceed browser height
                fit_landscape           :   0,      //Landscape images will not exceed browser width

                //Components
                navigation              :   1,      //Slideshow controls on/off
                thumbnail_navigation    :   1,      //Thumbnail navigation
                slide_counter           :   1,      //Display slide numbers
                slide_captions          :   1,      //Slide caption (Pull from "title" in slides array)
                slides                  :   [       //Slideshow Images
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/quietchaos-kitty.jpg', title : 'Quiet Chaos by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/wanderers-kitty.jpg', title : 'Wanderers by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/apple-kitty.jpg', title : 'Applewood by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'}
                                            ]

            });

        })(jQuery);

    </script>

I am stuck here. I am not very experienced with Drupal, Javascript, or jQuery.
Edited to include Bob's change to the wrapper.

There are a few issues here.

It's not in Drupal best practices to add a script to html.tpl.php
That being said, there are two ways to do it. (a) You can add it to your theme's .info file and call a .js file script from there (i.e. "scripts.js") in your theme folder, ideally in a "js" or "scripts" sub-folder if you need this site-wide (b)  If you don't need it site-wide or you can call it with drupal_add_js in your theme's template.php file to target only specific pages / paths
The way Javascript gets called has changed in Drupal 7

The main new thing is to include something like:

(function ($) {
//needed for drupal 7
Drupal.behaviors.myTheme = {
attach: function(context, settings) {
// end drupal 7 syntax

... at the top of your script.

so a clean version should work like so:

(function ($) {

//needed for drupal 7
Drupal.behaviors.myTheme = {
attach: function(context, settings) {
// end dtupal 7 syntax

            $.supersized({

                //Functionality
                slideshow               :   1,      //Slideshow on/off
                autoplay                :   1,      //Slideshow starts playing automatically
                start_slide             :   1,      //Start slide (0 is random)
                random                  :   0,      //Randomize slide order (Ignores start slide)
                slide_interval          :   3000,   //Length between transitions
                transition              :   1,      //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
                transition_speed        :   500,    //Speed of transition
                new_window              :   1,      //Image links open in new window/tab
                pause_hover             :   0,      //Pause slideshow on hover
                keyboard_nav            :   1,      //Keyboard navigation on/off
                performance             :   1,      //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
                image_protect           :   1,      //Disables image dragging and right click with Javascript
                image_path              :   'img/', //Default image path

                //Size & Position
                min_width               :   0,      //Min width allowed (in pixels)
                min_height              :   0,      //Min height allowed (in pixels)
                vertical_center         :   1,      //Vertically center background
                horizontal_center       :   1,      //Horizontally center background
                fit_portrait            :   1,      //Portrait images will not exceed browser height
                fit_landscape           :   0,      //Landscape images will not exceed browser width

                //Components
                navigation              :   1,      //Slideshow controls on/off
                thumbnail_navigation    :   1,      //Thumbnail navigation
                slide_counter           :   1,      //Display slide numbers
                slide_captions          :   1,      //Slide caption (Pull from "title" in slides array)
                slides                  :   [       //Slideshow Images
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/quietchaos-kitty.jpg', title : 'Quiet Chaos by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/wanderers-kitty.jpg', title : 'Wanderers by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/apple-kitty.jpg', title : 'Applewood by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'}
                                            ]

            });

//ending drupal 7 specific calls / syntax
}};
}) (jQuery);


Probably corrupted database by deleting records from node / node_revision I did something where everybody said never ever do it: some weeks ago I deleted records from the node- and/or node_revision tables manually (DELETE FROM TABLE ...), and thought it won't harm.
But now I see that it definitely did harm, as my search function doesn't work anymore the way it should be.

Is there something I could repair or very hard to recover?

Many thanks for help.

Oh dear, as you suspect that's not great. The outlook is probably quite bleak I'm afraid, a few vague possibilities:

If you know exactly what you deleted manually, restore it manually.
If you're able to restore a backup to another database, and cherry pick the records you deleted from that to be restored manually to the original DB, and depending on what damage those missing records have done in the meantime, that would possibly be an option.
If restoring the whole database from a backup is an option, do that.
If you know the IDs of the nodes you deleted, stick some dummy data with the appropriate IDs into the node/node_revision table, then call node_delete_multiple with the IDs so the system deletes them properly (clear the cache first).

The main problem with deleting straight out of the node table is that you leave a lot of orphaned data elsewhere - Drupal has no enforced referential integrity apart from some 'soft' checks in code for certain operations.

The most important thing to take away from this is never touch the database unless you're 100% confident what you're doing is safe. But I reckon you've probably learned that already :)


Image styles not creating files I am seeing a problem on my Drupal 7 site relating to image styles.

A bit of background - This site was built by migrating the content and config from a previous site, using the Migrate and Features modules, after the previous site fell victim to Drupalgeddon. The new site seems now to be 99% working. (After fixing a lot of stuff that wasn't properly copied across by Migrate and Features - whether that was due to my inexperience in using these modules, or shortcomings of the modules, I don't know.)

One thing that isn't working is uploading image files into fields of type Image.

The Image gets uploaded successfully and is accessible from /sites/default/files/.
But no files are being created in any of the subfolders below /sites/default/files/styles. So the thumbnails don't display.

I've tried a lot of the advice I've found while Googling - the UNIX file permissions seem to be OK, the Drupal permissions seem to be correct, I can't seen anything wrong in the .htaccess files, but perhaps someone out there can give me better guidance on what to look for here.

Have you tried deleting the styles folder? The folder and everything below it should be created automatically by Drupal.


Migrating sha1 user passwords into drupal 7 I have an old zend 1.8 cms site and I wish to import users into a drupal 7 site so that a user can login with their sha1 password without having to changing it. Once verified convert the submitted password to drupal 7 password in the users table. I would guess I would need to import users without their passwords into the users table and create a separate table to store their sha1 passwords in the database. I would be very grateful if someone can point me in the right direction to achieve this.

<?php
$str = 'password';//Users password

if (sha1($str) === '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8') {//from imported users table
    echo "Your password is valid";
    //let user into the site
    //insert into user.pass table password $str $S$DUygh2WJWU3caajVD3mgjIHShYgOTbaZnt9uC8lf6fMNo9lX50nr
}
?>

You can use the Migrate framework and easily import accounts into Drupal 7 and it will take care of this for you. Don't bother with separate tables and password lookups and all that.

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

https://www.jeffgeerling.com/blogs/jeff-geerling/migrating-drupal-7-users-site

I can't find an actual example of a class that handles users into Drupal 7,
but the Migrate docs are very thorough.

Edit - here is an example: https://cgit.drupalcode.org/migrate/tree/migrate_example/beer.inc#n212

But in your case you will want to define another database connection in settings.php and define that as the source of the migration.


How to access same name table fields in table join using db_fetch_object I've SNO in both A and B tables.

I do

db_query('SELECT * from A JOIN B on A.SNO=B.SNO')

Now how do I access both SNO fields of A and B using db_fetch_object?

You should name your fields in the SELECT, then you can use AS to rename them to something clearer:

SELECT fielda, fieldb, A.SNO AS thisone, B.SNO AS thatone, FROM... etc


How to use views hooks - specifically hook_view_data()? I am looking for details on the api to define my own view data, such as what values I can provide for the table I am defining, what values are available for the fields etc.

I have found a tutorial that gives me the basic info, but now I need more specific info.

I have found this page

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

but when I click on the link to

hook_views_data

I go to a page with virtually no information with one link which takes me back to the listing page I started at.

Is there somewhere I can find out information about what hook_views_data should define?

Views does have complete documentation for that hook, but it's not in the most obvious place.

If you install the Advanced Help module and go to http://mysite.com/help/views/api-tables you'll find the Describing tables to Views help page which contains extensive documentation and code samples.

You can also find the full Views' API docs at http://mysite.com/help/views/api with that module installed.

On top of that, the list of functions that implement hook_views_data() would also be worth a look. The aggregator, book and node module implementations look to be well commented at first glance.


How to customize the default search block form template? How can I customize the default search block form template, I now use below template to display a search form block, but this code doesn't allow me to edit and customize each part of this form separately and doesn't have any flexibility.

form--search-block-form.html.twig

<form{{ attributes.addClass('search-form', 'search-block-form') }}>
  {{ children }}
</form>

and then print in my theme by below code:

{{ page.search_box }}

Is there any better template name suggestion with more variables and flexibility in customization?

The search block is provided by the core module Search. If you install this module the block will be available in the block layout, when you place a block.

Probably you have already done this by installing the standard profile.

To customize the search form you can use a form alter hook.

For example put this function in mytheme.theme to change the search button:

function mytheme_form_alter(&$form, $form_state) {
  if ( $form['#form_id'] == 'search_block_form' ) {
    $form['actions']['submit']['#value'] = t('Search my Website');
  }
}


Why is settings.php in the web folder? In the default installation, settings.php is located at sites/default/. There are no recommendations in the official Drupal website about changing the location of this file. Doesn't it pose a potential problem of security? I have seen Apache webservers eventually failing to interpret PHP files, and serving the content of the PHP file in pure plain/text format, instead of the supposed HTML content. That would completely expose the database connection user and password, which is not even encrypted. Why does it work this way?

You are absolutely correct. I know for a fact that many developers/sysadmins do not take the risk that the PHP interpreter might fail at some point, and include the db password (and other sensitive data like API keys) from a file outside the webserver's docroot.

I'm surprised that this is not documented as a best practice anywhere - at least I couldn't find it on drupal.org either. I have no information why it works the way it does.


Run D6 and D7 instance on same domain? Client wants to have their D6 and D7 site run under the same domain. They're not ready to upgrade. Each has a similar theme so linking to the D6 site will 'look' seamless. How can this be done?

Put the D7 site under the root web directory. You should be able to go the site and see the D7 site. Then, put the D6 site under the root web directory in a new directory called 'd6' or whatever you want. Then, in the settings for the D6 site, put the root path as webdirectory/d6.

Then you can reference the d6 site from the d7 by directing users to the link "something.com/d6/someNode"

Otherwise, you really can't have both running under the same web root. It has to choose one or the other.


best practice for email validation in form alter drupal 7 What is the best recommended drupal way to validate an email is input on a new field I added in drupal settings page? Here is the code I have now:

function MYMODULE_form_uc_order_settings_form_alter(&$form, &$form_state, $form_id) {   $form['MYMODULE_uc_order_template_email'] = array(
'#title' => t('Template Email'),
'#default_value' => variable_get('MYMODULE_uc_order_template_email', 'test@example.com'),
'#description' => t("Template Email"),
'#type' => 'textfield',
 );

}

The function valid_email_address($mail) in D7 validates any email passed into it. If you need to validate a new email field from a form altered form, you can add a validation handler to your newly add email field to ensure that it is valid. Just append to the $form['#validate'] array the function you want called for validation.

function MYMODULE_form_uc_order_settings_form_alter(&$form, &$form_state, $form_id)
  //@TODO: Other form modifications
  $form['#validate'][] = 'MYMODULE_form_uc_order_settings_form_validate';
}

Then in your form validation function, check the value of the submitted field with valid_email_address($mail).

function MYMODULE_form_uc_order_settings_form_validate($form, &$form_state) {
  if (!valid_email_address($form_state['values']['MYMODULE_uc_order_template_email'])) {
    form_set_error('MYMODULE_uc_order_template_email', 'Not a valid email address');
  }
}


How to expire views cache in code or with rule? I have a view with block display that shows a user's picture and profile info. The view is cached for 1 hour.

How can I expire that cache when the user updates the profile?

I ended up using Views Cache Actions. It allows to use rules to expire a specific view or views displays when a certain event occurs (like user profile save).


Drupal 7 View display "Page not found" without contextual filter I have created a drupal view for my content type "Work", it has a relationship "Taxonomy terms on node" and a contextual filter "(term) Taxonomy vocabulary: Machine name". My path is /work/%.

When I go to work/sector, then it displays correctly all from content type work with the vocabulary sector. But when I go to just /work I get a "page not found".

Is there anything I need to be looking out for?

Click on your second argument, under Contextual Filter.

You should see an option - "When the filter value is not in the URL". That's where you specify what to do when the argument, i.e. "/sector" is not present. Provide the appropriate selection, and make sure Show "Page not found" is not selected.


How to add validation to Drupal commerce checkout submit? We have a requirement where user can do multiple registration for an event (i.e. for own and for other users). We want to restrict the user to do only N number of registration or less, where number N may vary from user to user specified on user profile. We are using 'Entity Registration' and 'Commerce Registration' module to do registration.

Drupal Commerce's checkout form uses button level validate and submit handlers as opposed to form level handlers. This means instead of just adding a handler to the $form['#validate'] or $form['submit'] array, you need to add it to the correct checkout button itself.

In your case, you'll add a handler to $form['buttons']['continue']['#validate'] via a form alter hook. Note that even if you prevent the form from advancing to the next page, though, that the checkout form is a special kind of form that validates and submits each fieldset independently of the form itself.

I'm not entirely sure how the registration module you're using interacts with the checkout form. However, it's possible what you may actually want is to alter the validate callback for a particular checkout pane via hook_commerce_checkout_pane_info_alter() to supply an alternate validate handler that checks your additional registration requirements and prevents that pane from submitting (which would also prevent the form from proceeding to the next page.


What is the proper condition to check for a select list value of none? I have a rule in drupal that populates an entity reference in a parent node with a child node.

Then I created a new rule that is applied "before content is saved" that will remove the child node from the old parent node if one wants to move it to a different parent node.

And it works as expected UNLESS one chooses -none- in the select list. How do I make it remove the child reference when none is selected. I tried Data value is empty and that doesn't work.

Here is an export of my current rule:

{ "rules_remove_job_from_client" : {
"LABEL" : "Remove Job From Client",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_presave--job" : { "bundle" : "job" } },
"IF" : [
  { "NOT data_is" : {
      "data" : [ "node-unchanged:field-client" ],
      "value" : [ "node:field-client" ]
    }
  },
  { "node_is_of_type" : {
      "node" : [ "node:field-client" ],
      "type" : { "value" : { "clients" : "clients" } }
    }
  }
],
"DO" : [
  { "list_remove" : {
      "list" : [ "node-unchanged:field-client:field-all-jobs" ],
      "item" : [ "node-unchanged" ]
    }
  },
  { "drupal_message" : { "message" : "Is this firing" } }
]
}
}

Make sure to add a Rules condition Entity has field (related to your field field-client as shown in your first Rules Condition). For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

If that doesn't help, you may want to do some Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


How can I design the standard user login form with twig? I want to change the labels "Username" and "Password" and delete "Create new account" link of the standard login form of Drupal 8. Is it possible to do this with twig?

I found the solution how to add user and password placeholders an modify user and password labels:

function THEMENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_login_form' ) {
    // Add placeholders.
    $form['name']['#attributes']['placeholder'] = t('User Placeholder Text Here');
    $form['pass']['#attributes']['placeholder'] = t('Password Placeholder Text Here');

    // Labels
    $form['name']['#title'] = t('User Label Here');
    $form['pass']['#title'] = t('Password Label Here');

    //Submit Value
    $form['actions']['submit']['#value'] = t('Submit Button Text Here');
  }
}

To remove "Create new account" and "Reset your password" links, just override block--user-login-block.html.twig file. Change

{{ content }}

to

{{ content|without('user_links') }}


How to change the referenced entity field value? I have a node that has a node reference to another content type. What I want is to update the referenced node field value on updating the node;

Let me clarify the issue.

For example I have a node of type "Basic Page" which having a relationship to a node of type "Article". I want to sync fields in two node let say I have a name field(Text) in both nodes.
On updating  basic page node I want to populate the referenced node Name field with that of the value in the basic page node Name field. How can I do that?

This is what I have done so far:

Event - After updating existing content.
Condition - Content is of type Basic page.
Action - Fetch entity by id(id from the entity reference field).
Action - Set a data value .

I am stuck at the fourth step I can't select the name field of the entity fetched in the data selector.

How can I populate the referenced node field with the value of the blog page node field?

Note: This is just for example In real case I want to map multiple fields from one node to another.

This is the exported rule:

{ "rules_on_updating_basic_page_nodes" : {
    "LABEL" : "On updating Basic Page nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "page" : "page" } } } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "node", "id" : [ "node:field-article:nid" ] },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      }
    ]
  }
}

You have to add a Condition to the rule of the class:
"Entity has field", and then a whole bunch of the referenced fields of the entity will appear.


Menu Block - stopping displaying children after a specific level So I am using Menu Block 7.23 and it is working awesome, I have it setup to start at 2nd level to show the children of the active menu, and if no children show active menu with max depth of 1 which has been working great.

I have been asked to make this navigation now, stop displaying the children after the 3rd level and I am not sure how to handle that in Menu Block configurations. I see there is a start level, but not a stop level. Here is an example of my heirarchy:

-Solutions
--Enterprise
---Profile Management
----Online/Offline

So essentially when going to Solutions it would show Enterprise, when going to Enterprise it would show Profile Management, but on Profile Management they do not want Online/Offline to appear, they want Profile Management to remain as the side menu. They want the breadcrumb to show the whole path on Online/Offline so I cannot just disable it from navigation, it needs to be part of the menu structure.

They want to just put reference links to Online/Offline in Profile Management page content, and on Online/Offline it would keep the Profile Management side menu.

Any help would be most appreciated.

You could use 'display:none' in the css as a solution.  I think using Nth-child would help achieve what you need http://css-tricks.com/the-difference-between-nth-child-and-nth-of-type/