Save values from Commerce Profile to User Profile with Rules? The response to this question indicates that the solution is to save values from the Commerce Profile into the required field(s) of the User Profile using Rules. I can't figure out how to do this!

I created a new Rule, triggered by event "After saving a new commerce customer profile" (though I might well need to integrate this rule into the Commerce Profile creation rule for it to work with required fields. For now, I've just removed the requirement.) Here are the actions that I've picked out as looking like good candidates for doing what I want:

Data

Add a Variable (Does this mean save a variable with a value, or just instantiate a variable? Where?)
Add an Item to a List (What list? Where?)
Set a Data Value (How is this different from "Add a Variable"?)

Entity (Are User profiles Entities?)

Create Entity (Use this to create the new User profile?)
Save Entity (Will this save values to the Entity?)

Are any of these going to do what I want? Am I on the wrong track entirely?

Thanks.

In order of asking:

Data

'Add a Variable' saves data to the {variables} table in the database, to be used with the standard variable_get() method.
'Add an Item to a List' will let you pick an entity and list-type field in the next step to initialise/add another item to (this might include a field with multiple values allowed, say).
'Set a Data Value' will let you set the value for a single, arbitrary field/property (usually as part of an entity). It's different from 'Add a Variable' in that it set the data value on the entity, and doesn't add it to the {variables} table.

Entity (profiles provided by the core profile module are not entities, if you're using the Profile2 module, then they are).

If you're using Profile2, yes.
If you're using Profile2, you'll be able to use it to save the entity after you've used the 'Set a Data Value' to set the value.

Looking through the profile.module and user.rules.inc files I can't see any built in support for the profile module; it stores its data in custom tables and I can't find any glue code that would suggest support's been added for rules (it's worth double checking this though, I could easily be wrong).

If it's not too late on in the build it might be worth having a look at Profile2; as each profile is an entity you'll get rules support built in automatically.

The other thing you could do is write the profile rules functionality yourself (implementing hook_rules_action_info() etc.) but that would be quite a bit more complicated.


How to get fields of media_entity? We have a view that returns a Media_entity (Drupal\media_entity\Entity\Media) using the following in a hook_preprocess_view_views hook. When we try to access the field_media_type variable, I get a NULL. field_media_type is a custom field (taxonomy field) on all the Media bundles.

How do we get the fields from a Media_entity?

use Drupal\media_entity\Entity\Media;

function mymodule_preprocess_views_view(&$variables) {
  $results = $variables['content']['#view']->result;
  foreach($results as $row){
    $media_entity = $row->_entity;
    ksm($media_entity->get('field_media_type'); // returns null.
  }
}

I also tried the following:

use Drupal\media_entity\Entity\Media;

function mymodule_preprocess_views_view(&$variables) {
  $results = $variables['content']['#view']->result;
  foreach($results as $row){
    $mid = $row->mid;
    $media_entity = Media::load($mid);
    ksm($media_entity); // null
  }
}

content array

iterator contents

An alternative solution I found was to use get the target_id and use Term::load($term_id)->getName() to get the value we wanted.

use Drupal\media_entity\Entity\Media;
use Drupal\taxonomy\Entity\Term;

function mymodule_preprocess_views_view(&$variables) {
  $results = $variables['content']['#view']->result;
  foreach($results as $row){
    $media_entity = Media::load($row->mid);
    $media_target_id = $media_entity->get('field_media_type')->target_id;
    $media_type_name = Term::load($media_target_id)->getName();
  }
}


Is there a drush script to disable all caches? I mean all of the caching options under admin/settings/performance. I frequently use drush sql-sync to keep my development copy up-to-date with the server. However, the server must have all of the caches turned on, obviously.

So I wonder: must I visit admin/settings/performance every time I update my db? Or is there a Drush script for that?

You need to set several variables to turn off caching on your dev site...

 drush vset cache 0
 drush vset preprocess_css 0
 drush vset preprocess_js 0
 drush vset page_cache_maximum_age 0
 drush vset views_skip_cache TRUE

It's even easier if you have conditional config in your settings.php file. Then you can refresh the DB and the changes will stick!

$conf['cache'] = 0;                       // Page cache
$conf['page_cache_maximum_age'] =  0;     // External cache TTL
$conf['preprocess_css'] = FALSE;          // Optimize css
$conf['preprocess_js'] = FALSE;           // Optimize javascript
$conf['views_skip_cache'] = TRUE;         // Views caching

... though if you just turn off various caching through the admin UI and clear cache once then you can theme away without turning off the rest... since script it less likely to change.


How do I print individuals fields in block.html.twig when is a node in a block? How do I print individuals fields in block.html.twig when is a node in a block?

The template is working fine. I can hard code some random text and it is displayed. I just can't display the field values.

I have already tried

{{content.my_field.0}}
{{content.my_field[0]}}
{{node.my_field.0.value}}
{{ content.my_field }}

But, after clear the cache doesnt work

You have to set "node" in the twig-variables of your block. I.e. you can do this in a template_preprocess hook like so:

function mytheme_preprocess_myBlock(&$variables) {
  $variables['node'] = Node:load(50);
}

Then you can access the "node" in your template like {{node.my_field.value}}.

The hard part is to find which node to load in the preprocess function :-)


Taxonomy: allow "All values" choice, visible as "All values" in results I'm looking for an "All values" choice in a taxonomy vocabulary.
It is about mobility regions, and some "contents" might be able to be tagged as "All regions". That is coming up new in the project and I already set up a taxonomy vocabulary before to categorize by regions.
Is there any simple way to do this?
In the results list, it should be refered at "All regions", and not region 1 - region 2 - etc.

Uncheck the Required option from exposed form field settings. Then there will be one more option - Any - will appear in filter dropdown. It will work same as All values.

You can also change - Any - value in to All Values by using hook_form_alter.

*EDIT :*

So the good structure is :
- Create a taxonomy vocabulary for the values ;
- Create a level 1 with an "All values" term ;
- Create a level 2 with all individual values ;
- Add the taxonomy relationship in the views and load the field taxonomy terms for each result ;
- Add the taxonomy as an exposed filter with depth ;
- In the settings of this filter, define a depth of -1, so every individual value chosen will also return the parent value.
As an example, a chosen region (as a taxonomy term) will return content indexed for "all regions" parent term.


Adding repositories in contrib module composer.json? Is it possible to add repositories from a module's composer.json instead of a project's composer.json? I've got the following set up:

Commerce Recurly (sandbox)  - and its composer.json
Recurly module fork (sandbox) - and its composer.json
Recurly API fork

I'm developing Commerce Recurly and am declaring a dependency on the Recurly module. However, the Recurly module uses API v2, and I am using API v3 in Commerce Recurly. Since the namespacing of the two APIs are different there are no conflicts when running them concurrently, so I created a fork of the API v2 to allow both to be added to my project. The result is that I am able to get both recurly/recurly-client and mrweiner/recurly-client-php-v2 concurrently installed to vendor.

Composer picks up all of the require dependencies correctly from both modules' composer.json files, as well as the patches from the Recurly Fork. It doesn't seem to pick up the repositories sections, though.

I'd expect to be able to just add the Commerce Recurly repo to my project's main composer.json like so and have everything install when running composer require sandbox/commerce_recurly:

    "repositories": {
        "0": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        "commerce_recurly_sandbox": {
            "type": "vcs",
            "url": "https://git.drupalcode.org/sandbox/mrweiner-3131465"
        },
    }

This doesn't work, though. I need to add repository entries for all three repos to my project's main composer.json to get composer require sandbox/commerce_recurly to correctly install everything, like so:

    "repositories": {
        "0": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        "commerce_recurly_sandbox": {
            "type": "vcs",
            "url": "https://git.drupalcode.org/sandbox/mrweiner-3131465"
        },
        "recurly_fork_sandbox": {
            "type": "vcs",
            "url": "https://git.drupalcode.org/sandbox/mrweiner-3131471"
        },
        "recurly_api_v2": {
            "type": "package",
            "package": {
                "name": "mrweiner/recurly-client-php-v2",
                "version": "2.12.13",
                "type": "vendor",
                "source": {
                    "url": "https://github.com/mrweiner/recurly-client-php.git",
                    "type": "git",
                    "reference": "c9f67565"
                }
            }
        },
    }

Is there some way to get composer to pick up the repositories defined in the modules' composer.json files? Having these extra entries isn't a huge deal for me right now, but when I move Commerce Recurly from Sandbox to a full project, it's going to be inconvenient to force people to add extra Repos to get things running.

Comments above pretty much answer this. No what I was looking to do is not possible.


How to print node embed field in field collection In one of my content type i am using field collection(Title, Image, Body).
I am using node embed to embed node titles of certain content type in one of my content type.
The issue i am facing is that whenever i am embedding a node it is not showing title instead of it displays [[nid: 2]].

I am printing individual field collection item, to print body i am using

 $section_desc =  $field_section_content_info[$section_content_id]->field_section_body[LANGUAGE_NONE][0]["value"];

i want node title to be displayed instead of [[nid: 2]].
what code should i write to display node title in field collection.

You are accessing the raw value of the body field in your code. I guess the functionality of replacing [[nid: 2]] comes from a text filter?

Try rendering the field with field_view_field instead. In the example below the label is also hidden by defining $display and passing that variable along to field_view_field.

$display = array('label' => 'hidden');
$section_desc = field_view_field('field_collection', $field_section_content_info[$section_content_id], 'field_section_body', $display);


Is there any security risk to use getenv() inside settings.php to populate databases variable from a .env file? I am using the Drupal composer project, which doesn't use getenv() by default.  I wanted to use the following code inside the settings.php file in a production site.

  $databases['default']['default'] = array (
   'database' => getenv('MYSQL_DATABASE'),
   'username' => getenv('MYSQL_USER'),
   'password' => getenv('MYSQL_PASSWORD'),
   'prefix' => '',
   'host' => getenv('MYSQL_HOSTNAME'),
   'port' => getenv('MYSQL_PORT'),
   'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
   'driver' => 'mysql',
);

I read somewhere we shouldn't use getenv() in production sites. What are the downsides of it? Is there any security issue?

If the .env file is outside the server document root, using getenv() is similar to putting the hash salt in a file and reading it with file_get_contents() as the following comments in the default.settings.php file suggest to do. (The same comment is present in the default.settings.php file for Drupal 7, so it's not a matter of which Drupal version is used.)

/**
 * Salt for one-time login links, cancel links, form tokens, etc.
 *
 * This variable will be set to a random value by the installer. All one-time
 * login links will be invalidated if the value is changed. Note that if your
 * site is deployed on a cluster of web servers, you must ensure that this
 * variable has the same value on each server.
 *
 * For enhanced security, you may set this variable to the contents of a file
 * outside your document root; you should also ensure that this file is not
 * stored with backups of your database.
 *
 * Example:
 * @code
 *   $settings['hash_salt'] = file_get_contents('/home/example/salt.txt');
 * @endcode
 */
$settings['hash_salt'] = '';

If that is considered enhanced security, the same can be said for reading some values using getenv(), if the file containing the values of the environment variables is not in the server document root.

Keep in mind that, if somebody would be able to write a PHP file on the server, it would also be possible for them to read the environment variables and the file containing the hash salt.


pages accessible only by specific groups I have made those pages on my Drupal 6: Alpha, Bravo, charlie, Delta. At time of writing, those pages are visible by anybody.
I need that those pages are visible only for limited groups, for example:
Alpha is visible only for group One and Two
Bravo is visible only for group Two and Three
Charlie is visible only for group Two and Three
Delta is visible only for group Three.
I have other nodes and other groups on the Drupal installation that needs to stay untouched, I need to change permissions only for those four pages, and of course their menu links need to reflect that (so each group will see only the menu links that they have granted access)
How can I do that?

Try the Nodeaccess module, here is a quote from its project page:

  ... is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.


Can I specify 'greater than' with db_delete()? I am new to Drupal 8.
I can use the following code to delete a record where salary == 45

$salary = 45;
$num_deleted = db_delete('test_table')
  ->condition('salary', $salary)
  ->execute();

Is it possible to specify a condition like "salary >= $salary" with db_delete() or I should use db_query()?

You can see document Conditional clauses for 7 (need update document) or you can see the documentation for QueryInterface, in particular for QueryInterface::condition().

  @param $operator  Possible values: - '=', '<>', '>', '>=', '<', '<=',

  'STARTS_WITH', 'CONTAINS',
  'ENDS_WITH': These operators expect $value to be a literal of the same type as the column.
  'IN', 'NOT IN': These operators expect $value to be an array of literals of the same type as the column.
  'BETWEEN': This operator expects $value to be an array of two literals  of the same type as the column.

. In your case you can use:

$salary = 45;
$num_deleted = db_delete('test_table')
  ->condition('salary', $salary, '>=')
  ->execute();


How to show the uploaded managed_file in the edit page? I am able to successfully upload files using managed_file. The file is saved in the correct directory and the record shows up in the file_managed table.

$form['image'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#default_value' => (isset($foo->image->fid) ? $foo->image->fid : ''),
    '#upload_location' => 'public://foo_images/'
);

But when I edit the form, it still shows the Upload button, similar to the Create page before I have uploaded a file. How do I make the edit page look like I have already uploaded a file for that particular entity?

Inspecting the $foo variable showed that I was supposed to use just $foo->image instead of $foo->image->fid.

Probably because I have the following lines in my _form_submit:

if (isset($form_state['values']['image'])) {
    $file = file_load($form_state['values']['image']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    file_usage_add($file, 'foo', 'foo', $foo->tkid);

    $foo->image = $file->fid;
  }

Notice the part that says $foo->image = $file->fid;


problem with JOIN query I have tow custom fields field_city and field_priority for a user profile.
Now I want to fetch the priority for a city like chicago. ( all I want is max priority for a city but first trying to fetch all )

I am trying with following queries but they are not giving me any result, I am getting a blank array. it works when I remove WHERE clause but not with WHERE for a city.

$query = "SELECT p.field_priority_value, p.entity_id, b.field_city_value FROM field_data_field_priority p LEFT JOIN field_data_field_city b on p.entity_id = b.entity_id WHERE b.field_city_value='chicago'";
    $result = db_query($query);
    $res = $result->fetchAll();

Tried following code with drupal query function.

$query = db_select('field_data_field_priority', 'p');
    $query->join('field_data_field_city', 'd', 'p.entity_id = d.entity_id');
    $query->fields('p');
    $query->condition('d.field_city_value','chicago','=');
    $result = $query->execute();
    $res = $result->fetchAll();

In the original query, you're using LEFT JOIN, so that will return results for the priority table, even if there is no successful join to the city table.

To match that query, use ->leftJoin instead of ->join

https://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3AleftJoin/7.x

Otherwise, your query should be correct and you don't have a priority for chicago.


Use mysql SET variables in db_query How can I use mysql SET variables while using my PDO queries?

db_query('SET @x := 5,SET @y := 6, SELECT * from mytable')->fetchAll();

I have tried this and many variations of this statement with and without ':' etc, but it doesn't work.

There are 2 points here.

SET @x := 5,SET @y := 6, SELECT * from mytable" should be "SET @x := 5,SET @y := 6; SELECT * from mytable

as

SET @x := 5,SET @y := 6;" and "SELECT * from mytable

are 2 separate MySQL statements.

You can not execute multiple statements together using db_query(). Since the PHP functions mysql_query() and mysqli_query() can only execute one SQL statement, the db_query() wrapper can also only execute one SQL statement.

What you can do here is, divide that into two part and run it.

db_query('SET @x := 5,SET @y := 6;')->execute();
db_query('SELECT * from mytable')->fetchAll();


How to use hook_form_alter with commerce checkout The module "commerce_checkout_buttons" alters the buttons in the commerce checkout process as seen below in using HOOK_form_alter. In this code, only the review form is being altered, but the changes seem to be global in the checkout process?

For example, the site I'm working with has a one-page checkout, and the Review pane doesn't include anything. Yet, the buttons are altered.

Can anyone explain how this works?

function commerce_checkout_buttons_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form_checkout':
    case 'commerce_checkout_form_shipping':
    case 'commerce_checkout_form_review':
      if (isset($form['buttons']['back']['#value'])) {
        $form['buttons']['back']['#value'] = t('Back');
      }
      if (isset($form['buttons']['continue']['#value'])) {
        $form['buttons']['continue']['#value'] = t('Continue');
      }
      if (isset($form['buttons']['back']['#prefix'])) {
        unset($form['buttons']['back']['#prefix']);
      }
      if (isset($form['buttons']['cancel']['#prefix'])) {
        unset($form['buttons']['cancel']['#prefix']);
      }
      break;
  }
}

If you remove the code shown below, it would only affect the review pane.

case 'commerce_checkout_form_checkout':
    break;
case 'commerce_checkout_form_shipping':
    break;


Why do the exposed filters in my view return to previous values after I change them? I have a catalogue list organised as a table with 4 exposed filter criteria set up. The page can be found here. An export of the view can be found here.

When a user runs the filter it works fine, but if they change the value of one of the filters and run it again, the search returns the results of the previous search and reverts to the previous value of the filter.

I know that if I enable a 'reset' button and the user resets the search that this works, but it is rather strange that if the user only wishes to change one of the filter criteria and keep the others the same that they cannot. They have to reenter all the criteria again.

Is there a configuration option that I am missing somewhere? I am running Views 7.x-3.0-rc1

Update: I have just noticed that even with the reset button that things do not work as they should.

If I hit 'reset' the query string at the end of the url is removed and the filter text boxes become blank. If I then add new criteria and hit 'apply' the querystring reflects the new filters, but the filter text boxes and the results reflect the original filter values.

You can select under each exposed filter, if Views should remember the selection or not. Remembering the last selected value will be stored as a session variable and persist until the user logs out etc.


How to write hook_field_placeholder_info() for the link module? The contributed project
Field placeholder
lets one use HTML5 placeholder attribute.  The project page says:

  By default, this module integrates text, number and mail modules,
  but any other widget type can be added through
  hook_field_placeholder_info().

I've tested this with a “Text” field, and it works as advertised.

I want to add hook_field_placeholder_info() for the
Link module.

According to field_placeholder.api.php, this hook should return:

  An array whose keys are the widget names and whose value are the
  widget item where the placeholder will be attached.

So far I've tried this:

/**
 * Implements hook_field_placeholder_info().
 */
function mymodule_field_placeholder_info() {
  return array(
    'link_field' => 'value',
  );
}

This puts the widget for the placeholder settings on the admin page
where one manage the link file, but setting a placeholder value has no
effect when I create a new node with a link field.

I believe the problem is “value”.  According to the documentation,
it should be the “widget item where the placeholder will be attached”.

I am not sure what that is.  So far I've tried “value”, “link_field”,
 “link”,  and “url” (clearing the cache before testing each in
turn), but none of these work for the link field.

So: How to write hook_field_placeholder_info() for the link module?

There is a feature request to add support for the link module. Unfortunate that patch has not been committed yet, but you can use/apply the patch in #5 and use

/**
 * Implements hook_field_placeholder_info().
 */
function mymodule_field_placeholder_info() {
  return array(
    'link_field' => 'url',
  );
}


How do i generate token for each user they submit my custom form? I have a created a custom module with simple form with only three fields ( Url, title & email ) , where user has to enter all the fields for submission.

I am able to send the mail to the user from my custom module but i need to create and attach a validation link (possibly with unique token for unique email) how do i generate a token so i can store it in database and use it for validating the user later.

(you may also help me with your own approach)

1.Declare custom tokens using hook_token_info()

2.Create custom tokens using hook_tokens()

3.You can use your custom tokens using token_replace()
that is call the token_replace at the place where u need to send the email.

4.Create a seperate file inside your module with .tokens.inc extension and include the hook_tokens_info() and hook_tokens() inside it.


How to Extract Label of a Field, which is inside FieldCollection? I have a field collection with the name 'field_stk_fld1'.

Inside this field collection('field_stk_fld1') there is a field with name 'field_fld_stk_ques1'.

I wanted to extract label of the field ('field_fld_stk_ques1'), Any idea on how to get it?

Note: This field ('field_fld_stk_ques1') is used in multiple places and in each place it has its own label associated.

This should do it:

$entity_type = 'field_collection_item';
$bundle_name = 'field_some_field'; // Field name the collection is attached to
$field_name = 'field_some_other_field'; // Field name within the field collection

$info = field_info_instance($entity_type, $field_name, $bundle_name);

if ($info) {
  $label = $info['label'];
}


Views PDF : class not found I am running Drupal 7.56

I have been using Views extensively for some months now. I want now to create custom pdf pages from some Views.

I have installed jQuery_update, then Views PDF Display Module, then copied fpdi and tcpdf libraries into the Libraries folder (via FTP).

Now, when I want to add a PDF Page to a View, I get the following error message :

  Fatal error: require_once(): Failed opening required 'sites/all/libraries/fpdi/fpdi2tcpdf_bridge.php' (include_path='/home/my_hostname/www/www/sites/paroisse/civi_extensions/nz.co.fuzion.cmcic-master/:/home/my_hostname/www/www/sites/paroisse/civi_extensions/nz.co.fuzion.extendedreport/:/home/my_hostname/www/www/sites/paroisse/civi_extensions/org.civicrm.sms.twilio/:/home/my_hostname/www/www/sites/paroisse/civi_extensions/com.drastikbydesign.stripe/packages/:/home/my_hostname/www/www/sites/paroisse/civi_extensions/com.drastikbydesign.stripe/:/home/my_hostname/www/www/sites/default/fpdf:.:/home/my_hostname/www/www/sites/all/modules/civicrm:/home/my_hostname/www/www/sites/all/modules/civicrm/packages:.:/home/my_hostname/www/www/sites/all/modules/civicrm:/home/my_hostname/www/www/sites/all/modules/civicrm/packages:/home/my_hostname/www/www/sites/all/modules/civicrm/vendor/tecnickcom:/home/my_hostname/www/www/sites/all/modules/civicrm/vendor/phpseclib/phpseclib/phpseclib:/home/my_hostname/www/www/sites/all/modules in /home/my_hostname/www/www/sites/all/modules/views_pdf/views_pdf_template.php on line 22

I suspect that this is due to a bad installation, but find no clear and up-to-date installation tutorial.

I must say that :
- I am not a programmer,
- I use civicrm, a big Drupal Module, which explains the big include path

Any help is welcome

I went back to fpdi-1.6.2, and the error disappeared (the internal fpdi folder content has completely changed between the two versions).


Using Views "Rewrite the output of this field" tokens I have a field which allows a user to upload 3 photos called field_prodshots. To any Views experts out there, is it possible to display just the first value of that field instead of all 3 while using "Rewrite the output of this field" tokens? After all, I only need the one image to use as a thumbnail.

Typing in [field_prodshots] in the textarea for rewriting the output results in the display of all 3 images. I only need the first one.

There's a simple way to show only the first image in a field that allows multiple image uploads.

In the Configuration screen for the field, there's a dropdown called "Multiple Field Settings." Expand that, and you should see options for how many items you want to display, and which item in the list to start with. Change "Display __ value(s)" from all to 1. You shouldn't need to change the separator in your case, as you're only displaying one image.

See below for screenshot. This setting should work fine alongside "Rewrite the output of this field" tokens (I haven't had it not work).

http://img585.imageshack.us/img585/8644/multipleimagesshowonlyo.png

In a field with several images uploaded, I'm correctly seeing only the first as you can see here:

http://img713.imageshack.us/img713/5479/resultzc.png


Which drupal function can you use to invoke a function stored in contrib module (e.g. in an .inc file)? Which drupal function can you use to invoke a function stored in contrib module

You can use module_load_include

  // Load node.admin.inc from the node module.
  module_load_include('inc', 'node', 'node.admin');
  // Load content_types.inc from the node module.
  module_load_include('inc', 'node', 'content_types');

Then you will be able to call the function that is in those files.


Theming custom entity created with Entity API: accessing entity's fields in template file First of all let me say that this is my first project in Drupal and I am still confused, I apologize if my question is stupid.

I created a custom entity in Drupal 7 using Entity API. The custom entity represents a golf course.

I used this tutorial: http://www.sitepoint.com/series/build-your-own-custom-entities-in-drupal/
Then I tried to add a custom theme, to do so I followed this: https://www.drupal.org/node/1238606

My callback function looks like this:

function view_my_entity($id) {
  $entities = entity_load('my_entity_type', array($id));
  $entity = $courses[$id];
  drupal_set_title($entity->name);
  $output = entity_view('my_entity_type', array($entity));
  $output += array(
    '#theme'     => 'my_theme',
    '#element'   => $output,
    '#view_mode' => 'full',
    '#language'  => LANGUAGE_NONE,
  );
  return $output;
}

And this is my hook_theme():

function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my_theme' => array(
      'variables' => array('element' => null),
      'template' => 'my_template',
    ),
  );
}

The problem is that in my_template.tpl.php I can only access the golf course variables this way (in this example I will access the address):

render($element['my_entity_type']['The Name of my Entity']['address']['#markup'])

As you can see, in order to access the address I have to use 'The Lakes Golf Club', (which is the name of the currently displayed golf course), as a key, but obviously that name is going to change every time I display a different golf course, so my question is:

How can I access the golf course attributes without having to use the golf course name as a key?

EDIT

the docs for entity_view() (http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.module/function/entity_view/7) say the following:

  Return value

  The renderable array, keyed by the entity type and by entity
  identifiers, for which the entity name is used if existing - see
  entity_id(). If there is no information on how to view an entity,
  FALSE is returned.

So how do I avoid that the array is keyed by the name of the entity? If it was keyed by the id it would be OK because I have the $id variable in scope.

This can be easily solved by including this snippet at the beginning of your template file:

// my_template.tpl.php
<?php
$keys = array_keys($element['my_entity_type']);
$my_entity_name = $keys[0];
$my_entity = $element['my_entity_type'][$my_entity_name];
?>

Now you can easily print values like so:

<?php print render($my_entity['address']['#markup']); ?>


variable_get/set not working right I am using drupal 6. I have a variable in a function which I saved with variable_set. I called variable_get in a different function and it keeps giving me the default. Why wont it save the variable? I know that the variable has a value because its used in sql query.

here's my set:

    $staff_action = $_GET['staff_action'];
$first_name = $_GET['first_name'];
variable_set('first_name', $first_name);
$last_name = $_GET['last_name'];
variable_set('last_name', $last_name);
$email = $_GET['email'];
variable_set('email', $email);
drupal_set_message($email . " in first function");

here's my get in second function:

$first_name = $_GET['first_name'];
$last_name = $_GET['last_name'];
$email = variable_get('email', 'none found');
drupal_set_message($email . " in second function");

In your code where you are setting the value move the last line above variable_set() function

Change this code:

 $staff_action = $_GET['staff_action'];
$first_name = $_GET['first_name'];
variable_set('first_name', $first_name);
$last_name = $_GET['last_name'];
variable_set('last_name', $last_name);
$email = $_GET['email'];
variable_set('email', $email);
drupal_set_message($email . " in first function");

To this:

 $staff_action = $_GET['staff_action'];
$first_name = $_GET['first_name'];
variable_set('first_name', $first_name);
$last_name = $_GET['last_name'];
variable_set('last_name', $last_name);
$email = $_GET['email'];
drupal_set_message($email . " in first function");
variable_set('email', $email);

Then it should work.


Create Forms in Drupal and process them i am new to Drupal and i want to implement training / seminar program in my Drupal site. I want to know how to implement the following features:

The administrator will be creating a seminar / training session program from a form in admin panel, with details like name, date and description. How to add a form in admin panel and save its details in a new table in database ? Do i need to create a module here?
The training sessions and seminars created by admin can be viewed by the users in the front end with a scrollbar div block. How to show this information in front end ?
When they click on the name of a program in the block, it will lead to a separate screen, where the user can view the program details (name, date and description) and a button to register... how to create a new screen in drupal?
When the user clicks on register button, he will be enrolled in the program (saved in database with inactive status). Now the admin must be able to view the programs he created, in admin panel, and when he clicks on a program name, the registered users in that program will appear. Then he can click on a user's name and a small screen to 'Accept' him in the program and save his status to 1 in the database. How to implement this ?

Basically i want to know how to create forms in Drupal and how can i show them in the front end. Any help is appreciated.

I'm assuming that you're using Drupal7.  I will provide some pointers but you'll have to look up the details on your own.

Sounds like you might want to create a new Content Type.
Views can generate a list of a specific Content Type (in your case, list only seminars).
Views typically links each item in the list to the actual node with the full info
The Webform module will allow you to create sign up forms but there's likely more that you'll have to do to tie everything together.


Panels vs template performance Sorry for rather newbie question. I am reading an Panel CookBook and how to create different layouts for homepage and other landpages. Apparently it is possible to achieve the same result with Panels models and template sub-theming and overriding. So my questions are:
1. When to use one of the above methods?
2. Performance issues Panels vs Theme overriding?
Thanks.

I think the thing to keep in mind here is how the site is going to be used.  If users are not going to log into it, it almost doesn't matter in terms of performance because you use Boost.

http://drupal.org/project/boost

You can also use caching features in panels.  I've never really noted a large hit for using panels on a website, as long as the layout is reasonable and the site does not have an excessive amount of modules on it.  Panels exposes a lot of functionality, and you can pry it out of my cold dead hands.

If you've not used Boost before, do yourself a favor and commit to doing so!

NOTE: In your other question you referenced D7.  Boost may not be ready for D7 just yet but you should keep it in mind.


Is it possible to make only one field in a content type language neutral? If you have a text field, that you do not want to be translated (i.e. language neutral) as in a field for an email address, how do you set just that one field to be language neutral, while leaving the rest of the fields in the content type multilingual (enabled, with translation under workflow settings)? I've tried toggling the checkboxes under "Content Translation" but I think that's just for the Translation Management modules translation jobs handler, not for the actual field settings itself.

The idea is to not have to enter an email address twice in both, for instance, English and Spanish since the value will be the same in both language. Otherwise you have to enter the value in each language to get it to show up in that language.

I don't believe that it's possible to configure the language type of fields and translate per field. Not in Drupal 6 anyways.

This shouldn't be a problem anyways. When you translate a node, drupal makes a copy of the original node, which means the e-mail address will be pre filled with the correct value.

The does require some extra work when editing, but if you really wanted to, you could create some custom code, or maybe setup a rule, to keep that field in sync with the other translated nodes.


Changing a plain text field to enable rich editing In Drupal 8, I set up a plain text field and now I have no way to change it back to rich text editing.
I could take the approach of just setting up a new field and copy the field data from the old one to the new one manually, but I have hundreds of records. What are some other solutions?

There is no official solution. String and text fields have different structure (text has an additional format column), you could try to convert it by hand, but you also need to update Drupal's internal information about the field and resulting database schema.
Your easiest option is probably to create a new field and then write a simple script that loads all nodes of that type and assigns the value of the old field to the new. If there are too many nodes to load for a single run, you'll need to split it up or do a batch.
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'yourtype']);
foreach ($nodes as $node) {
  $node->newfield->value = $node->oldfield->value;
  $node->newfield->format = 'plain_text';
  $node->save();
}


Theming a menu - removing a whitespace between the last  and I want to alter the HTML of the main menu. I have a manu set up with text-align: justify.
Now in Chrome, the whitespace between the last li and ul is rendered as 4px, making the last item not aligned to the right margin. See this stackexchange post. I want to remove the whitespace or replace it with and html comment.
I am a bit lost ;-). What should I be overriding? theme_menu_tree?
I am using the Omega 3.

Because it sounds like your question is really about how to manipulate the main menu markup in Omega, I guess I'll focus on that. That said however, the "whitespace" issue from the post that you reference is quit strange, as I'm not sure I understand how a newline between an closing li and ul tag would influence any visible alignment behavior. I'm also not sure that Omega even adds any such newlines to the menu output by default. Still, it sounds like you've isolated this as a cause already.

If you are using the main menu that's automatically inserted within the page by Omega (as opposed to displaying your main menu via a menu block or similar), then I believe the most specific theme hook that applies is 'links__system_main_menu'. Check out the omega/omega/templates/region--menu.tpl.php theme file to see how this is ultimately called.

It's important to note however that 'links__system_main_menu' is not necessarily a hook that you'll find an existing theme function for, it's just a suggested pattern. See this post for more on that. Chances are the theme function that's actually getting used currently is theme_links(), or in the case of Omega (which already has an override setup) omega_links().

So if you want to target an override that's specific to just the main menu you could use the code from omega_links() as a template for your own override called MYTHEMENAME_links__system_main_menu(). Then within this new function you could adjust the output to tweak the way "whitespace" is added before and after any ul and li tags as you deem necessary.


Module that allows visitors to suggest modifications on a node I'm looking for a module (or some other way) that allows users to send suggestions about how to edit a certain node. I'll explain:

There is a node type with the following fields: name, description and phone number. One node contains these values:
Name: "Lulu's Restaurant"
Description: "A very good restrurant"
Phone number: "123456790"

A visitor notices that some values are incorrect, clicks on a link "send suggestion" and he's brought to a form where the fields are filled with the node's data. The visitor edits the fields

Body: "A very good restaurant"
Phone number: "1234567890"

And clicks on "send", this will memorize the data on drupal (on a different place than the node, but this has to be linked with the node) and notifiy registered users of this new suggestion.
Registered users should be able to see a comparison view of the original node and the suggestion (possibly with highlighted text, like your typical diff checker application) and then edit the node accordingly.

Registered users should also be able to change the status of the suggestions (pending, accepted, not accepted, spam).
Another feature i need is that visitors (unregistered) should be able to subscribe to nodes and receive notifications whenever the node is edited.

I think some basic features can be done with normal drupal features (like a node that can be created by unregistered users) or the rules module for notifications, but i was wondering if there's a specialized module to do this.

Apart from the notifications, Workbench along with Workbench Moderation seems to meet most requirements.

Drupal only has two states for nodes: unpublished and published. With Workbench Moderation, you can define your own custom states, e.g. pending, accepted, not accepted, spam.
You can then authorize anonymous users to edit nodes (make suggestions). These edits will create new revisions which will NOT be published until authorized users actually publish the changes.

Workbench Moderation also works well with Diff which allows you to compare different revisions to see the actual changes per field.

Finally, following nodes and notifications can be realized with the Flag and the Rules module.


Return single value via AJAX Background

I have a Drupal 7 module that is making an AJAX call via jQuery.ajax() to a menu callback that I've defined in my module. The purpose isn't to return markup, but rather just a single string value.

This is all working as it should, but the method by which I'm passing the value back to jQuery seems messy to me.

I'm using:

// $condition is a simple string value.
print($condition);
drupal_exit();

My Question

Is there a cleaner, more standardized way of doing this? This just feels hackish and messy to me.

Thanks, Drupalers!

That will work, but here is how I would do it (in D7). You can set up the ajax callback server side like this:

$response = array('value' => $condition);
drupal_json_output($response);
drupal_exit();

Then your value will be available as data.value in your success callback:

$.ajax({
  url:example.com/some/path
  success:function(data) {
    alert(data.value);
  }
});


Invoking Drupal core tests from within a custom module .test script I am writing a simpletest test script, where I would like to enable my module, and then invoke a Drupal core test to ensure that my module is producing core-compliant results (in particular, I render a pager alternative to core's, and would make sure that, at its minimal setup, is equal to core's one).

Is there a way to do that?

Thanks for help

mondrake

So... I found a solution that's working, at least for my case.

It has to do with the fact that test cases are actually PHP classes that can be extended. So I tried to leverage inheritance, with a caveat...

I want to run a test on the pager, Drupal 7, after I have enabled a module that replaces the core pager.

The core pager test class is defined as

class PagerFunctionalWebTestCase extends DrupalWebTestCase {

now, my problem was that the core test would not be caring about my module to be loaded before running the tests.

I created my module test class as an extension of the core one, like

class MyPagerTest extends PagerFunctionalWebTestCase {

This is OK, but the point is that if I call parent::setUp() at this stage, the core setup will be run and I will still miss my module from loading before the actual test.

So the caveat is that instead of calling parent::setUp, I will call directly the 'ancestor' DrupalWebtestCase::setUp function, with my setup, and skip the call to parent.

Like this:

...

public function setUp() {
  // Enable required modules.
  $modules = array(
    'dblog',
    'mypager',
  );
  DrupalWebTestCase::setUp($modules);

  // Insert 300 log messages.
  for ($i = 0; $i < 300; $i++) {
    watchdog('pager_test', $this->randomString(), NULL, WATCHDOG_DEBUG);
  }

  $this->admin_user = $this->drupalCreateUser(array(
    'access site reports',
  ));
  $this->drupalLogin($this->admin_user);

}

....

That's all - class inheritance will do the magic and bring the rest of the test functions in.

Anybody sees other options?


Access one field from another when using entities On my Drupal 7 website, I have used Entity Construction Kit to create an entity that contains two fields: field_body_image and field_image_position.

This entity is then attached to a node.

I want to be able to access the value of field_image_position from inside field_body_image. How can I do this?

Steps I have taken to solve the problem:

I know that if you have the fields placed directly on the node (ie. so not using ECK) you can use field_get_items

However, this doesn't seem to work when ECK is involved.

Here is the code I am using in my template.php file

function [THEMENAME]_field__field_body_image(&$variables) {

    //Load the value of field_image_position
    $field_image_positon = field_get_items('node', $variables['element']['#object'], 'field_image_position');
    $image_positon       = $field_image_position['und'][0]['value'];

if ($image_positon == 'image_position_bottom' ) {
print 'Successful' //This is just a test to see if it works, the actual code will be different
}
 However, this does not work.

If I use Devel and do:

function [THEMENAME]_field__field_body_image(&$variables) {
kpr($field_image_positon);
}

Then I can see field_image_position located in the following:

$...['element']['#object']->field_image_position['und'][0]['value']

and

$...['element']['#items'][0]['value']

So how can I access it?

(using     $field_image_positon = field_get_items('node', $variables['element']['#items'], 'field_image_position'); causes a White screen of Death. )

You mentioned you are using ECK to create a new entity, whereas in your code, you are using 'node' instead of the machine name of your entity.

I am referring to the line:

$field_image_positon = field_get_items('node', $variables['element']['#object'], 'field_image_position');

Change node in this line to your_entity_machine_name.


How to create content type programmatically with fields and vertical tabs I'm creating a module using Drupal7.26 and want to create content type with different type of fields like radio/checkboxes/drupdown and textfields.
I'm following the last comment by Jason Gray in THIS thread and is working pretty well except it is not creating Fieldset, Vertical Tab Group and Vertical Tab when the module is installed.

What I did is:
I have created a custom module to create new Content Type by following SITEPOINT tutorial.
And take the fields array by exporting of the node which I created manually using CCK with all fields that I want.
Now all the fields are showing in my newly created node by installing module, except (Fieldset, Vertical Tab Group and Vertical Tab) which I created by enabling Field group module.

NOTE:
When I export the content type using feature as (test) it gives me 3 files as bellow:
1 - test.features.field_base.inc (I take fields array from here)
2 - test.features.field_instance.inc (I take instances array from here)
3 - test.field_group.inc (it give me the bellow hook) which I'm not sure where/how to use it.I place it in both MYMODULE.install and MYMODULE.module files both didn't work.

    function test_field_group_info() {

    }

Any ideas would be appreciated.

Wooho :) here is the answer
I was missing hook_ctools_plugin_api() in my module


Logging in with email and not username I tried the module LoginToboggan to log in entering the email and not the username (that I use as Facebook ID). The problem is that the module allows to log in with either the email or the username.

How can I log in with just the email?

There is a module for that, try Email Registration, from module description:

  Allow users to register and login using only an email address. Users can then log-in using their email address and password for authentication.

  A username is generated and assigned based on the user name part of
  the email address and their user ID

is avilable in D7, D8


How to generate a Commerce order from a CSV? I'm using Drupal 7 with commerce. Is there a way to generate an order from a csv or similar? the idea is that users could upload a csv (sku and quantity for now) with the items they want and the system generate an order with that.

i'm trying with feeds and the entity processor but i can't import the line items and create de order in the some process (they have to be related with an order). If this is the way, it's not clear to me how to do that.

Im not sure how to make csv directly to order, but this should work:

create a node type, called "csv order"
use Feeds module to fetch the data from csv to this node type
install module hook_post_action
write a custom module, which after saving node "csv order" would take data from this node, and create commerce order with line items
remove the csv order node if neccesary


Drupal installed as composer package, Custom themes/modules folder I want a folder structure similar to:

-web
--app
---themes
---modules
--core

In composer I can specify installer paths to put required modules in the /web/app/modules directory and install drupal core in the /web/core.

Can I get Drupal to look for themes and modules in the /web/app/themes and /web/apps/modules directories so I don't have to put anything custom inside the core directory (so Drupal core can be installed as a package and not stored in my git repo).

I've seen similar set ups with Wordpress allowing you to specify a 'CONTENT_DIR' constant that means Wordpress will look for wp-content in a different directory. Is there a similar way for Drupal?

I found this on git which achieves something but it requires a custom script https://github.com/davidbarratt/drupal-structure

Drupals extensions discovery looks only in some specific folders (see http://cgit.drupalcode.org/drupal/tree/modules/README.txt for more information).

But, you don't have to put your own modules inside of the core folder. You should use /modules instead.

The Drupals default directory is not ideal for a development workflow with composer in mind. Take a look at https://github.com/drupal-composer/drupal-project if you have not already.


Text After Comment Form How I could put a block of text after my comment form (kinda like politics), I put comments separated from the content (different pages).

As megadesk mentioned its hook_form_alter you're after.

Depending on what your more comfortable with you can either add this to your theme in template.php or you can add it to a module. I'm going to assume from now on that you'r putting it into template.php. An infact rather than hook_form_alter we'll use hook_form_FORM_ID_alter.

/*
* Implementation of hook_form_FORM_ID_alter
*
* Adding text after the comment form
*/

function YOUR_MODULE_NAME_form_comment_form_alter(&$form, &$form_state) {

    //add an I agree to house rules checkbox to the form
    $form['markup'] = array(
                 //This is the text you want to add to the form, using the t() function allows it to be translatable
                '#markup' => t('You can leave us a message using the contact form below.'),
                //By making the weight 20 we insure that it appears at the bottom of the form
                '#weight' => 20,
        );
}

I havnt tested this but that should be what your after... Let me know if you need more.


How do I show a term's node count in grid format? I've been looking around for instructions on how to show the node count for taxonomy terms, and, while I did find instructions on Views and node count for taxonomy terms, it wasn't exactly what I need. The terms and their counts do show up next to each other quite nicely (Ex: Term A(13), Term B(2), Term C(17), etc.). However, they only show up as an unformatted list.

I need them in a grid form. Although I did play with the settings for quite a while, I wasn't able to get it work, and didn't find anything else on the web that fixed the problem.

Any advice would be much appreciated!

If you import the view proposed in that answer, you will get a table with 2 columns: term name on the left, number of nodes on the right. That's a block, not a page, but that's a good start for your needs, IMHO.

Read this to learn how to import views.


How to add element not appearing on the page via node_view_alter? Given the following code:

function mymodule_node_view_alter(&$build) {
  $node = $build['#node'];
  if ($node->type != 'podcasts') {
    return;
  }

  $build['new_section'] = array(
    '#weight' => 15,
    '#markup' => 'test injected data'
  );

  dpm($build);
}

In the dpm() output, I can see that my test data is in the array; however, nothing shows up on-screen.

Do I need to pre-define this new section or set it to allow any new sections?

hook_node_view_alter() documentation reads:

  This hook is called after the content has been assembled in a
  structured array and may be used for doing processing which requires
  that the complete node content structure has been built.

This means it is for logic that fires after the render array has been constructed, eg changing weights or items in the array you cannot control (items from other modules).

What you are looking for is hook_node_view(). That should allow you to add new sections into a render array.

The example from the linked resource:

function hook_node_view($node, $view_mode, $langcode) {
  $node->content['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}


How to change uploaded file name after save node? Hello and thanks for looking my question.

On Drupal 7 I use this hook hook_file_presave() for change file name.

function mymodule_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = $file->uid . $file->timestamp . '.' . $parts['extension'];
}

But how to do it on Drupal 8.1.x? Programmatically or module ways or something else?

hook_entity_presave?

Description from the DocBlock:

  Act on an entity before it is created or updated.
  You can get the original entity object from $entity->original when it is an update of the entity.


How to have Menu like apycom How can I create menus like Apycom Menus ?

Do I need to create custom module and then use it which will be available to whole site or I can just use css and js from the apycom menus?

If you have the source code, you can integrate it with your Drupal's templates. Otherwise, I don't see how you could do it.


How to rename a field with hook_ds_fields_info() In a contrib module I maintain, I define a DS field via hook_ds_fields_info().

Now it happens that I want to rename this field (the machine name).
(actually it is not about renaming but splitting the one field into multiple fields, but that's a detail)

The first step is trivial: Rename the machine key in hook_ds_fields_info().

Next step, in hook_update_N():
Every entity view mode that uses the field with the old name, should be updated to use the field with the new name instead.

How would I implement this second step?

It seems that the ds_field_settings and ds_layout_settings db tables are what I need to look at. But is this enough? Which API functions could I use?

I managed to implement this, thanks to @aspilicious.

See
- https://drupal.org/node/2190599
- http://drupalcode.org/project/views_content_ds.git/blob/refs/heads/7.x-2.x:/views_content_ds.install

The solution is to edit this directly in the database, with db_update() called from hook_update_N().

The tables are ds_field_settings and ds_layout_settings. Columns you need (same for both tables):

'id' is the primary key. Typical value: taxonomy_term|categories|full
'settings' holds the settings (field settings or layout settings), serialized.

Use drush sqlc + describe (table) to look at the table structure.

It also helps to implement the upgrade as a drush command, ideally with a downgrade option. This allows to quickly test this a lot of times, which is not that easy with hook_update_N().


Sort Criteria - sort by user role I have 7 roles in my project.
I arranged them by weight in admin/people/permissions/roles page
Add the sort criteria Global:PHP with code

return $row1->rid;

But users display with no sort on role weight on page.

Look for these solutions:

In Views, how can I show users with one role before all other users?

Role Weights

This way you can get your desired result. Hope this helps.


Get blank value if field value is not available I have following query on my D7 project

$query = db_select('payment_logs', 'p');
$query->join('field_data_field_frequency', 'd', 'd.entity_id = p.nid');
$query->join('field_data_field_maid_id', 'm', 'm.entity_id = p.nid');
$query->join('field_data_field_coupon_code', 'c', 'c.entity_id = p.nid');
$query->join('field_data_field_tip_amount', 't', 't.entity_id = p.nid');
$query->fields('p');
$query->fields('d', array('field_frequency_tid'));
$query->fields('m', array('field_maid_id_uid'));
$query->fields('c', array('field_coupon_code_value'));
$query->fields('t', array('field_tip_amount_value'));
$query->condition('p.section','booking','=');
$result = $query->execute();
$res = $result->fetchAll();
return $res;

this query returns data where field_tip_amount_value and field_coupon_code_value are available. I want to get all data with blank field values if not available. these two fields are optional other fields will be there always. so if tip or coupon is not there data must return blank for this field.

I was doing it with separate queries before but it was taking too much time with multiple loops. is there a way to get it done with join ?

You can change $query->join to $query->leftjoin.

This will cause the query to return a row, even if there's no entry in the joined table.

Hope this helps.


Way to display View block only when a specific option is selected in Facet I have a view block which I want to display on page only when a specific item in facet is selected (eg Year) .
I am struggling to get this done , I tried with contextual filter but it seems it doesnt work with Solr index .
Any pointer on how can i control the behavior of display of my view block on facet combo.

Thanks!
Carol

In common situation, when facet is active - you have GET params in your url. You can use it as condition for programmatically display view. For example

if (!empty($_GET['my_facet'])) {
  print views_embed_view('view_name', 'display_name');
}


Rendering the add to cart form Is it possible to render the add to cart form programatically? Something like:

\Drupal::formBuilder()->getForm('Drupal\commerce_cart\Form\AddToCartForm', $product)

Yes, possible and very easy.

Short version

You can use this render array.

This will render the Cart form if your product can be added to cart - if it has available variations bascially.

$combine = TRUE;
$langcode = 'en';
$view_mode = 'cart';

$build['add_to_cart_form'] = [
  '#lazy_builder' => [
    'commerce_product.lazy_builders:addToCartForm', [
      $product_id,
      $view_mode,
      $combine,
      $langcode
    ],
  ],
  '#create_placeholder' => TRUE,
];

Full example with a Controller

You can use a custom Controller to render your own Add To Cart form.

First, prepare the route in mymodule.routing.yml:

# Custom route to render Add to cart form.
mymodule.add_to_cart:
  path: '/mymodule/add_to_cart/{product_id}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CartController::addToCart'
    _title: 'Add to cart'
  requirements:
    _access: 'TRUE'
    product_id: \d+

Second, create your Controller:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for cart routes.
 */
class CartController extends ControllerBase {

  function addToCart(int $product_id) {
    $build = [];

    if (!$product_id) {
      $build['error'] = [
        '#type' => 'item',
        '#markup' => $this->t('Wrong product ID'),
      ];
      return $build;
    }

    $build['add_to_cart_form'] = [
      '#lazy_builder' => [
        'commerce_product.lazy_builders:addToCartForm', [
          $product_id,
          'cart',
          TRUE,
          'fr'
        ],
      ],
      '#create_placeholder' => TRUE,
    ];

    return $build;
  }

}

Finally, add a link to open a modal on front end, as follow:

Add product to cart

Clear cache

You should be good to go! :)


Is there a way to use $front_page in node.tpl? I'm aware that $front_page is a variable used in page.tpl, but is there a way to use it (or something similar other than a direct link) to print the index url in a node.tpl?

Absolutely:

function MYTHEME_preprocess_node(&$vars) {
  $vars['front_page'] = url();
}


How to limit drush tar-options="--exclude pattern matching to be specific and not recursive With the folder structure like so
/site_root
/site_root/images
/site_root/core
/site_root/core/modules/images
/site_root/libraries
etc

When doing a drush archive dump backup, from the inside site_root (usually it's public_html but in this case it's another folder), I use
$ drush ard tar-options="--exclude=images" --destination=~/.backups/[date].tar.gz

That way the archive dump skips the /site_root/images folder and the ard is much smaller.
Unfortunately for me pattern matching then causes all images folders throughout to be excluded due to recursivity.
So I would lose
/site_root/images
/site_root/core/modules/images
etc

I know in linux you can make tar-options look at the folder structure by making the pattern relative, like so
$ drush ard tar-options="--exclude=./images"
But that is not working for me via drush ard tar-options.

I also tried the home folder shortcut '~' (which works a treat on drush ard destination) like so
$ drush ard tar-options="--exclude=~/site_root/images" --destination=~/.backups/[date].tar.gz
But, for some reason, that does not work like it does on the –-destination switch.

What is the best way to limit the drush tar-options="exclude switch to either no-recursive or pattern match looking at relative path to working directory?

I've found that you can use the current working directory, as the starting point, to force relative urls. It was a matter of getting the syntax correct.

For example if you have your site root in public_html, and you are in that location cd ~/public_html, you can use drush:

[user public_html]$ drush ard tar-options="--exclude=public_html/images" --destination=~/.backups/[date].tar.gz

The key is to navigate to that starting point root folder first.

For example, if your site root was in a subdirectory subdirectory/siteone,
 go to that location first cd ~/subdirectory/siteone
and then use drush:

[user siteone]$ drush ard tar-options="--exclude= siteone/images" --destination=~/.backups/[date].tar.gz


In which cases should I not call user_access() in a form submission handler? Reading the code for user_register_form(), I see the following comment:

  Pass access information to the submit handler. Running an access check inside the submit function interferes with form processing and breaks hook_form_alter().

The code right after that comment is the following, where $admin is set to user_access('administer users').

  $form['administer_users'] = array(
    '#type' => 'value',
    '#value' => $admin,
  );

Looking at comment_form_submit(), I notice that user_access() is being used.

  if (user_access('post comments') && (user_access('administer comments') || $node->comment == COMMENT_NODE_OPEN)) {
    // Save the anonymous user information to a cookie for reuse.
    if (user_is_anonymous()) {
      user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
    }

    // …
  }

Is there any difference between the first case, and the last one? If there isn't any difference, what approach should I use in my code?

I did a little detective work to find when that user_register_form() code was committed and then traced the corresponding issue.

From comment #21 there:

  The problem is that you can't form_alter out the admin behavior without rewriting the submit handler from scratch.

So I guess the approach you use just depends on whether you want to allow your access checks to be altered by other modules without them having to override your submit handler.


How to record unique hits in node counter stats? Is there a way to only count the unique views in the core node counter stats?

I was using the Statistics Advanced module for Drupal 6 but there is no Drupal 7 solution. The quote below is from the Statistics Advanced module and what I want exactly is that.

  Only track 'unique' views of content: If you keep viewing a node over
  and over again, the "x reads" counter won't increase each time. This
  is applied on a per-user basis as well as a per session id for
  anonymous users.

The Node View Count module doesn't effect the core statistics, it creates a new table for itself. So this is not an option for me.

What I'm looking for is a solution that effects the CORE statistics, nothing else.

Node view count

You may want to use the Node view count module for this. Here is a quote about it (from its project page, bold markup added here):

  ... allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

  This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

Specific to the D7 version of it, this is what is included also on the project page:

  Also now we count node views for anonymous users.

Statistics Advanced

Be aware of the  Statistics Advanced (*) issue "Port Statistics Advanced Settings to D7", with current status = needs review.

My "recommendation" for anybody looking for a D7 version of it, is to review what is attached to Comment # 55 in that issue. And report any potential deficiencies in that same issue (confirmations that it works fine would be appreciated too, also via that same issue).

Other modules to consider

If the Node view count and/or Statistics Advanced (*) module doesn't fit your needs, then you may want to consider reviewing this shortlist of possible alternatives (quotes are from their project pages).

Visitors (*):

  Displays information about visitors, and integrates with the WhoIs Lookup module

Better Statistics:

  introduces a Statistics API, which allows for a way to collect, limit, and route custom access statistics and data.

Piwik Web Analytics:

  Adds the Piwik web statistics tracking system (free open source) to your website.

  Related module: Piwik Reports, which provides graphical reporting of your site's tracking data inside Drupal.

Chartbeat:

  ... to provide third party integration with Chartbeat, for real-time site monitoring statistics.

Stat Counter:

  ... provides an integration between Drupal and StatCounter web statistics.

Enough options to "explore"?

Disclosure: I'm the maintainer of the modules marked with (*).


Drupal 7 Rules : How to get Node Object (from Custom PHP) after a node event is triggered? In Drupal 7, i am setting up a rule. That rule is applying to trigger on the Node Save event.

After the node is saved [Condition] and the rule is properly triggered, then how can i get that saved Node Object ($node) from the Execute Custom PHP Code [Action]?

Because i put var_dump($node) (in the Custom PHP Code Box) but it doesn't work.

you can use watchdog("<pre>".print_r($node,true)."</pre>",'debug');then see the log in admin/reports/dblog
also you can define your own action use  hook_rules_condition_info().
This link may help.


Add user points for every up vote My drupal 7 site has an user rating system for authors content, but problem is, every up-vote and down-vote do not add point's automatically in users profile. But i think, it is possible by User Points module. From Userpoints Karma module page i have learned that vote/up down module allows a voter to add or subtract points to the author of a given node or comment, thereby awarding or punishing the author for what they wrote.So, i have configured vote/up down module successfully, here is a screenshot of a views of my website: Now my question is, How to add point's automatically for votes using vote/up down module and User Points module? So, if an user vote a content then the user points for that content author will be 10 + 5 = 15! {Here 10 is previous user point for the content author and 5 is the value for every up-vote!} I can't understand that How to do it automatically? Any ideas? Thanks

Theres is a module to add rules to voting api: http://drupal.org/project/voting_rules

Userpoints comes with native rules support.

I just set the whole thing up on my test environment, added a new Rule with

Event: User votes on a Node

Condition: User has role(s)
Parameter: User: [vote:user], Roles: authenticated user

Condition: Check the value of the vote
Parameter: Vote: [vote], Operator: is greather than, Data value: 0

Action
Grant points to a user
Parameter: User: [vote:user], Points: 5, Points category: General, Operation: Insert, Moderate: Use the site defaul

additional info:
you must enable userpoints and userpoints_rules as well as voting_rules

Here's the export of the rule

{ "rules_reward_voter" : {
    "LABEL" : "reward voter",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : [ "voting_rules_insert_node" ],
    "IF" : [
      { "user_has_role" : { "account" : [ "vote:user" ], "roles" : { "value" : { "2" : "2" } } } },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "operator" : "\u003E", "value" : "0" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "5",
          "tid" : "0",
          "entity" : [ "" ],
          "operation" : "Insert",
          "display" : 1,
          "moderate" : "default"
        }
      }
    ]
  }
}


Where are admin/config/user-interface/archive setting stored Where are these settings stored at. On the disk? In a database table?

Generally, configurations in administrative pages are saved into variable table.

The path admin/config/user-interface/archive is not a Drupal core path. It must have been provided by a module. If you want to get a definitive answer, you should provide more information.


How to change/set/assign parameter's value for an entity query? Say you have an entity query which you're going to use in a loop so that only parameter(s) value(s) changes on every iteration. Is there a way to prepare this query and change the value of the parameters?

There are some nice examples in the comments on the api documention page for Entity queries https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3AentityQuery/8.2.x

One example assigns a value to a variable, then uses the variable in the query:

$value = 'some value';
$query = \Drupal::entityQuery('entity_type');
$query->condition('field', $value);
$entity_ids = $query->execute();

In your loop you could re-assign the value as needed before executing the query.

Another example sets up some functions, so that might be an option and then your loop could call the function.

function someFunction($value) {

  $query = \Drupal::entityQuery('entity_type');
  $query->condition('field', $value);
  $entity_ids = $query->execute();

}

Or you could clone the part that stays the same in your loop and alter the rest.  Using your code as an example...

$base_query = \Drupal::entityQuery('taxonomy_term');
$base_query->condition('vid', 'some_vocabulary');

for ($i = 1; $i <= 10; $i++) {
  $query = clone $base_query;
  $query->condition('tid', $tids[$i]);
  $query->execute();
  //...
}


What's the best way to spell-check a complete Drupal site? I'd like to spell-check a complete site (some 300 pages) and my plan is this:

Spell-check complete site to collect all misspellings from all pages
Make a spelling dictionary to be shared by all editors
Rerun spell-check to get list of pages with misspellings
Install TinyMCE spell-check module over aspell, using spelling dictionary from 2
Get the editors to go over all misspelt pages and fix them

How can I run the complete spell-check in 1 and 3? I can hack it with wget, aspell and perl but is there an easier solution?
Can I present the misspellings from 3 in context, highlighted in the page?

I considered CheckDog but then hacked a quick perl script using curl & aspell:

#!perl

use constant SITEMAP => "http://www.example.com/sitemap.xml";
use constant MAX_PAGES => 10;

$npages = 0;
for (qx{curl --silent @{[SITEMAP]}}) {
  m{<loc>(.*?)</loc>} or next;
  $page = $1;
  ++$npages > MAX_PAGES and last;
  print "$page\t"; # here so if aspell crashes, we know which page
  $typos = qx{curl --silent $page | aspell --mode=html --home-dir=. --personal=dict.txt list};
  $typos =~ tr{\n}{ };
  print "$typos\n"
}

Add valid words to dict.txt, where the first line is:

personal_ws-1.1 en 500

As per @Berdir and @kiamlaluno suggestion, we'll also try TextReview. The following use cases would be of interest to us:

Differences: hopefully better than a module that displays raw html side by side
Spell check: showing misspellings in context will be wonderful!
Similarity percentage: maybe we can use this to warn on duplicate pages?
Manually configured blacklists and whitelists: eg to avoid UK spellings "customise" in favor of US spellings "customize"


Customize webform-fields error messages I'm using Webforms module and, in particular, a Date field. Using built-in validation and intentionally triggering the validation error, the message looks like follows:

The entered date must be 04/04/1914 or later.

Have no error here. What I need is to customize that error message (I need to show (1) a different message, and (2) in a different language).

Question: How can I alter the webform to override the message with my custom one?

Go ahead and download this https://drupal.org/node/1209450 module in zip. there are two zips you can download any one. here is the code can you use now

function modulename_message_alter(&$message) {

    if(isset($message->messages['error'])){
       foreach($message->messages['error'] as &$val) {
        if(preg_match('@The entered date must be \w+/\w+/\w+ or \w+.@',$val)){
            $val='This is not correct date';
        }
       }
    }
}


How to install a patch to drupal 7 I recently exprience one problem that requires a patch. I downloaded that file .patch, but have no idea how properly to install that to my hosted website.

If you can shell into the account, you

cd /var/www/somewhere/docroot/sites/all/module
patch -p1 < /path/to/the/patchfile

Depending on how the patch was rolled, you may need to adjust the number after the -p to get it to apply properly.  The man page can give you more details.

If you can't shell into the host, then you need to downloads the files(s), apply the patch locally and then upload them.  This question give guidance, or you can cut to the chase and check out TortoiseMerge.


Every link except home directes to 'Not found' page? I have created site directly on the shared host server by downloading fresh Drupal 8. Every think went Ok with installation and site installed properly. But whenever I click on any link of admin bar or my-accont/logout it directs me to Not Found page.

For example I clicked on Extend from admin menu and following message did appear.

Not found message

Any idea why this is happening and how to correct that. Very thanks.

You are missing (or having a malformed) htaccess file.

You can download a .htaccess file directly from drupal.org with the following link: https://raw.githubusercontent.com/drupal/drupal/8.2.x/.htaccess

If you want an htaccess file for a different disk version then you can change the version number in the above link.


Superfish Menu override CSS I am using superfish menu module with drupal 7.7 and I can't figure out how to override the CSS in space.css or any other superfish stylesheet.
If anyone knows how to, please share your input.

It supposed that the module has his own css, you need to edit those files but that is not a solution.

I recommend you to use some debugging tool like firebug and check what css you need to edit. Then write the css changes in your theme css file. With this logic if you update the module you will not loose all your custom changes.


What are Panes, in a Übercart context? I was wondering what are "Panes" - I found them while I was messing with source code of Ubercart module. It looks like they're building page with something like panes - which I'm totally new to. Code looks like:

  // Load through the cart panes...
  foreach (uc_cart_cart_pane_list($items) as $id => $pane) {
    // If the pane is enabled...
    if ($pane['enabled']) {
      // Add its output to the cart view.
      $build[$id] = $pane['body'];
      ...

So, are "panes" Ubercart concept, or some in-general thing? I searched with "Drupal Panes" but no luck.

Visit your checkout page (add product to cart, visit cart, then click Checkout), each fieldset (as in image) is a pane. It's not the same as for "panels" pane.


How do I insert the title of the block between two Views fields? A designer has sent me a very cool design, and I don't know which is the .tpl file I need to override.

Basically, I need to put the title of the block between two fields of a view. The view is already a header of another view, and it displays only one record.

Other (bad) alternatives I see:

Do some positioning tricks with CSS.
Create a custom text field and style it like if it was the block title, and then hide the block title.

You could try Views block area

  This module exposes all available blocks as a views area. This way you
  can add any block inside a footer or header from your view.

Also there is Views Hacks

Or i would do it with Views PHP by adding a field and print the block there with https://drupal.stackexchange.com/a/14354/4471


KML file upload on OpenLayers map When I tested modules in Feb I am sure I got this working but nothing works now; I want the user to be able to upload a KML file when creating a node, and for that to display on a map. I am not even trying to combine multiple, just display each node's KML on an OpenLayers map.

I have tried the following module combinations:

Geofile

This is giving me an error which may just be an issue with the latest OpenLayers version.
Issue on Drupal.org: EPSG fix is needed

OpenLayers KML Layer

The instructions on the module make it sound simple but I have not managed to get this to work.

Geocoder

Module home page suggests that you can set a field to geocode from an uploaded KML file, but I have not managed to get this to work and I do not see any errors.

Does anyone have this working?

Note: I know one can define a static KML layer in admin/structure/openlayers/layers, that is not helpful as I need a person to be able to upload a KML file on a node.

EPSG is fixed in Geofile 7.x-2.x
Geofile provides a map formatter for the file field. more instructions

If you don't want to use the new version of Geofile, then go to the module(sites/all/modules/geofile) folder, open geofile.openlayers.inc in a text editor. if 'projection' and 'displayprojection' are assigned just numbers '4326' or '900913' change it to 'EPSG:4326' or 'EPSG:900913'


How to show book information in search result page I want to show some extra book information in the search result page like node id, book id, book name etc.
I have added some code in search-result.tpl.php but its still not showing.

$node->book['bid']  //is added to show book id.
$node->node['nid'] //is added to show node id.

Let me know where i am doing wrong.

Finally managed it using search-result.tpl.php file which copied in theme folder.

 $url = $variables['result']['fields']['url'];

this variable gives search result urls from which i extracted book name and based in book name i printed book id.
@Anil, thanks for the help which guide me at right direction and got to know many more.


"no line items found" in user order I have installed Drupal Commerce (7.x.1.8 version) but in user orders section when I select an order only price and total is shown. In despite of order details the message "no line items found" appears. What can I do on here to show order datails?

I found a solution that worked for me via this article.

The author propose to change the Commerce view settings.


Assign menu programmatically upon saving node I'm using Superfish module for my menu. I have product parent menu where I need to display the 3 categories as sub-menu. Those 3 categories has been added to the menu with the help of Taxonomy menu module.

I would like to assign a menu automatically based from the nodes category.

For example:-

"Node 1" has "Category 1" term, then the node menu will be assigned to "Category 1". Something like below:-

-Product
 --Category 1
    ---Node 1
    ---Node 2
  --Category 2
    ---Node 3
    ---Node 4

Please try this

/**
 * Implements hook_node_insert().
 */
function YOUR_MODUEL_node_insert($node){
  create_node_menu($node, 'insert');
}

/**
 * Implements hook_node_update().
 */
function YOUR_MODUEL_node_update($node){
  create_node_menu($node, 'update');
}

function create_node_menu($node, $action_type){
  if($node->type == 'YOUR_NODE_TYPE'){
    $category = $node->field_category[LANGUAGE_NONE][0]['value'];
    $menu_name = '';
    switch($category){
      case "A":
        $menu_name = 'menu-menu-a';
        break;
      case "B":
        $menu_name = 'menu-menu-b';
        break;
      case "C":
        $menu_name = 'menu-menu-c';
        break;
    }
    if(!empty($menu_name)){
      $item = array(
        'menu_name' => $menu_name,
        'link_title' => $node->title,
        'link_path' => 'node/'. $node->nid,
      );
// update already created menu link
      if($action_type == 'update'){
        $mlid = db_select('menu_links' , 'ml')
            ->condition('ml.link_path', 'node/'.$node->nid)
            ->condition('ml.menu_name', $menu_name)
            ->fields('ml' , array('mlid'))
            ->execute()
            ->fetchField();
        $item['mlid'] = $mlid;
      }
      $mlid = menu_link_save($item);
      menu_cache_clear_all();
    }
  }
}

Hope this will help.


Multiple choices select with data module created view on my website I have a custom table, and I used the data module to create a view that uses the entries in that table.
I have created an exposed filter for one of the columns. Since I needed a select form and only search box was available, I used this code:

function mymodule_form_views_exposed_form_alter(&$form, $form_state) {

$form['myfield']['#type'] = 'select';
$form['myfield']['#multiple'] = true;
$form['myfield']['#default_value'] = array("" => "All");
$form['myfield']['#options'] = $values;
$form['myfield']['#attributes'] = array('size' => 10);

}

The problem is that when I select multiple values, it performs an "AND", but I need an "OR".
How can I procede?
Thanks!

*markus_petrux* answered, and josepvalis gave a helpful example of this in Drupal Groups in 2010.

You can use hook_views_pre_view to alter the filter to use 'OR'. Trimming josepvalis's example, try redefining the filter & applying that:

function my_module_views_pre_view(&$view) {
    $new_view_filters['field_multiselect_value'] = array(
        'id' => 'field_multiselect_value',
        'table' => 'my_table',
        'field' => 'my_column',
        'operator' => 'or',
        'value' => $array_of_values,
        'group' => '0',
        'exposed' => FALSE,
        'relationship' => 'none',
    );
    $view_overrides = array();
    $view_overrides['filters'] = $new_view_filters;
    foreach ($view_overrides as $option => $definition) {
        $view->display_handler->override_option($option, $definition);
    }
}


How to get the URL for an image thumbnail I'm using a view template to override how a field is displayed.

The field happens to be an attached image to the node.

I notice in the view it's configured to display the thumbnail - when overriding, how do I get the thumbnail?

(I'm using entity_metadata_wrapper )

EDIT

So based on the suggetions below I need to use image_style_url - how do I get the path to pass to it?

ie, how do I complete this code

$node = node_load($row->{$field->field_alias});
$wrapper = entity_metadata_wrapper('node', $survey_node);

// Field is called field_image

$path = ???

$thumbnail_url = image_style_url('thumbnail', $path)

print "<img src='" & $thumbnail_url & "'>"

You need to use function image_style_url($style_name, $path) to obtain proper path in Drupal 7.20 and later. $path is a path to an original file. Preferably output normal path, and make it a thumbnail in proper .tpl.php file.

If you need to do it in place that does not accept php functions and cannot alter it in template, you can consider disabling itok token. To do so, add following line to your settings.php

$conf['image_allow_insecure_derivatives'] = TRUE;

Then you can simply add styles/thumbnail/public/ like Kevin says, and use path like example.com/sites/default/files/styles/thumbnail/public/myimage.jpg to get thumbnail of example.com/sites/default/files/myimage.jpg.


How to close comments with just 1 click? My site editors want a quick way to close comments on a particular node, i.e. they just want to click a button on an item, rather than having to click edit, then select the comment settings tab, then click the "closed" box.  (This is for Advanced forum, but I guess it could apply anywhere).

I have a feeling this should be fairly easy to do but I can't work out how to do it. Any pointers you can give would be appreciated. (I am using the Flag module and thought flag actions would be a simple way to do this, but closing comments doesn't seem to be an available action).

You can achieve this by following steps given below:

Create a flag on nodes for administrator only
Add new rule using Rules module
Set React on in Event "A node has been flagged, under
Add action "Set a data value"
Select Data "flagged-node:comment"
Click Continue and set value as 0

Please check Rule given below(exported):

{ "rules_disable_comments" : {
    "LABEL" : "Disable comments",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_disable_comments" : [] },
    "DO" : [
      { "data_set" : { "data" : [ "flagged-node:comment" ], "value" : "0" } },
      { "drupal_message" : { "message" : "Comments closed" } }
    ]
  }
}

& Flag given below(exported):

$flags = array();
// Exported flag: "Disable comments".
$flags['disable_comments'] = array (
  'entity_type' => 'node',
  'title' => 'Disable comments',
  'global' => '0',
  'types' =>
  array (
    0 => 'article',
  ),
  'flag_short' => 'Disable comments',
  'flag_long' => '',
  'flag_message' => '',
  'unflag_short' => 'Enable comments',
  'unflag_long' => '',
  'unflag_message' => '',
  'unflag_denied_text' => 'Disabled comments',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
    'teaser' => 'teaser',
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'token' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;


Change '/user(/*)' URLs to 'profile(/*)' I want change all /user, /user/* urls by /profile, /profile/* urls.
From a custom module, I copied all user routes (found in /core/module/user/user.routing.yml) to my custom .routing.yml file. I replaced all "user*" paths by "profile*".

Now, I have the following.

mycustommodule.register:
  path: '/profile/register'
  defaults:
    _entity_form: 'user.register'
    _title: 'Create new account'
  requirements:
    _access_user_register: 'TRUE'

mycustommodule.pass:
  path: '/profile/password'
  defaults:
    _form: '\Drupal\user\Form\UserPasswordForm'
    _title: 'Reset your password'
  requirements:
    _access: 'TRUE'
  options:
    _maintenance_access: TRUE

mycustommodule.page:
  path: '/profile'
  defaults:
    _controller: '\Drupal\user\Controller\UserController::userPage'
    _title: 'My account'
  requirements:
    _user_is_logged_in: 'TRUE'

mycustommodule.login:
  path: '/profile/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

mycustommodule.login.http:
  path: '/profile/login'
  defaults:
    _controller: \Drupal\user\Controller\UserAuthenticationController::login
  methods: [POST]
  requirements:
    _user_is_logged_in: 'FALSE'
    _format: 'json'

mycustommodule.login_status.http:
  path: '/profile/login_status'
  defaults:
    _controller: \Drupal\user\Controller\UserAuthenticationController::loginStatus
  methods: [GET]
  requirements:
    _access: 'TRUE'
    _format: 'json'

mycustommodule.logout.http:
  path: '/profile/logout'
  defaults:
    _controller: \Drupal\user\Controller\UserAuthenticationController::logout
  methods: [POST]
  requirements:
    _user_is_logged_in: 'TRUE'
    _format: 'json'
    _csrf_token: 'TRUE'

mycustommodule.cancel_confirm:
  path: '/profile/{user}/cancel/confirm/{timestamp}/{hashed_pass}'
  defaults:
    _title: 'Confirm account cancellation'
    _controller: '\Drupal\user\Controller\UserController::confirmCancel'
    timestamp: 0
    hashed_pass: ''
  requirements:
    _entity_access: 'user.delete'
    user: \d+

mycustommodule.reset.login:
  path: '/profile/reset/{uid}/{timestamp}/{hash}/login'
  defaults:
    _controller: '\Drupal\user\Controller\UserController::resetPassLogin'
    _title: 'Reset password'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE
    no_cache: TRUE

mycustommodule.reset:
  path: '/profile/reset/{uid}/{timestamp}/{hash}'
  defaults:
    _controller: '\Drupal\user\Controller\UserController::resetPass'
    _title: 'Reset password'
  requirements:
    _access: 'TRUE'
  options:
    _maintenance_access: TRUE
    no_cache: TRUE

mycustommodule.reset.form:
  path: '/profile/reset/{uid}'
  defaults:
    _controller: '\Drupal\user\Controller\UserController::getResetPassForm'
    _title: 'Reset password'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE
    no_cache: TRUE

From my website, when I go to the http://mysite/profile, I'm redirected to the correct page (the user view), but the URL change automatically to http://mysite/user. I want keep the URL as http://mysite/profile. How can I do that? Is it possible?

The routes you've defined are new routes with different names and this is the reason the standard routes are still in place. If you want to override the standard routes you would have to use the same route names like user.page:.

But this is not the best approach to alter multiple routes. Better use a route subscriber:

src/EventSubscriber/RouteSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection) {
    foreach ($collection->all() as $route) {
      if (strpos($route->getPath(), '/user') === 0) {
        $route->setPath(preg_replace('/^\/user/', '/profile', $route->getPath()));
      }
    }
  }

  public static function getSubscribedEvents() {
    $events = parent::getSubscribedEvents();

    $events[RoutingEvents::ALTER] = array('onAlterRoutes', -250);

    return $events;
  }

}

mymodule.services.yml

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\EventSubscriber\RouteSubscriber
    tags:
      - { name: event_subscriber }


How to use Feed importer to import content type in which one of the field is node reference field type? I have a content type, in which one field has multiple values and they are referred from another content type. How can I upload this content type from a .csv file with the help of feeds importer?

I have used feeds tamper. Multiple values are comma separated in the file that I intended to upload. I have added explode plugin and , delimeter in the feed importer page (tamper).


Creating nodes and interacting with drupal from the command line I have a requirement where I will have to insert content (nodes) from the command line.
I know that drupal bootstraping is needed to acces the environment, and this can be done using PHP.

Is there any tool that can create/modify/read content from the command line ? Are there any other programming language binds (besides PHP) ? What are the options ?

I think the best option would be to go with the Services module. About the module from the project page:

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

You can build the other application (like android app, Java app, and many more...) in any programming languages you like and make the application interact with Drupal using Services. There is an extensive documentation available which would help you through.
Take time to read through the project page (as it contains more resources to explore) and the documentation as it might take time to get accustomed with the module (as it happened with me).

For command line access to Drupal there is a "Command line shell and scripting interface" - Drush (Drupal Shell). List of the Drush commands could be found at this site. It is very powerful utility for Drupal developers (on Windows, Ubuntu Linux, Mac, etc.); but I'm not sure if one is able to create/modify/read content (nodes) with Drush though, I think one cannot do that (please correct me if I'm wrong).


7 - Panels node form, file/image gets removed when field not present in the custom form I am using Panels to customise node forms by separating them into multiple pages.

On one page I have text fields and on another file/image fields, when saving the text field form variant all the files get removed from the node - if I add a field in that form variant, it will get saved (not removed).

Is this a normal behaviour?

I've also encountered that. The node form and the image field's value will be submitted as empty and resulting in as you say that the image get removed from the node.

It is an unfortunate side effect of how the form api works. Someone could try to work around it in Panels, and/or limit panels to prevent you from doing this, but both of these would be hacks on top of form api.

One workaround is adding the pane General form that you will find under Form when adding panes. Then click settings for the pane and under CSS properties set the class to "element-invisible". This way all other form elements that you have not placed as panes will be present but hidden by css.

I know it feels wrong but at least it get's the job done :)


Running Drupal in a Windows environment (IIS, SQL Server)? We are in the process of evaluating Drupal to replace our in-house .NET CMS. We run an IIS 7.5 web farm with a SQL Server 2008R2 on the back end. To make matters worse, we use sql server merge-replication between our primary and secondary collocation facility. Rebuilding the entire web farm structure would be cumbersome.

Can anyone provide thoughts/feedback/experiences on using Drupal with IIS/SQL server? Bonus points if you know it works sql server merge-replication.

Easiest way is to use the Microsoft Web Platform Installer to install Drupal 7 - http://www.microsoft.com/web/downloads/platform.aspx

The only option it currently provides is using SQL Server as the back-end database, so you should be golden. (The Drupal 6 WebPI installs do not target SQL Server)

I've been running Drupal 7 on a Hyper-V-based VM under Win2k8 R2 with SQL Server Express as the backend DB for a few weeks without incident.


How to render a DS fieldgroup programmatically in a node template? I am overriding a Display Suite view mode of a node using the template suggestion myLayout-node-myNode-full.tpl.php.

I am getting the $node->content using the node_build_content function. Then I have access and I am rendering all the node display fields using:

drupal_render($node->content['field_myField'])

But I cannot render fieldgroups using the drupal_render function, as it requires array parameter, but my fieldgroups are stdClass objects that can be accessed as:

$node->content['#groups']['group_myGroup']

Printing the $node variable, I do not get any other reference to fieldgroups, eg. $node->content['group_myGroup'] does not exist.

Any suggestions on how I could render fieldgroups in my template file in Drupal 7?

node_build_content is probably not suitable for your use case. However you should use node_view instead which calls node_build_content anyway but returns you the actual renderable array after it processes it and sends it through an alter as well.

For example:

function mytheme_preprocess_node(&$vars) {
  if (!empty($vars['node'])) {
    $node = $vars['node'];

    if ($node->type == 'my_content_type') {
      $vars['content'] = node_view($node); //optionally supply view_mode as a second argument
    }
  }
}

Now you can just drupal_render($content) from your node template.