How do I programmatically attach a file to a file field in a node? I have a custom content type with a file field. I am trying to attach a file uploaded through a custom form to the custom content type. I am able to load the node and update all the other values of the node except the file field.

I found Realityloop: Programmatically attach files to a node in Drupal 8,  but it doesn't seem to work.

This was what was suggested in the above link

$node = Node::create([
  'type' => 'article',
  'title' => 'Druplicon test',
  'field_image' => [
  'target_id' => $file->id(),
  ],
]);
$node->save();

This is what I have tried inside submitForm

$fid = $form_state->getValue('file_field_name')[0];
$file = File::load($fid);
$file->setPermanent();
$file->save();
$node = Node::load($nid);
$node->set('file_field_in_node', $file->id);
$node->save();

That was setting the file as permanent in the files table but the node did not have the file.

I also tried to save with

$node->set('file_field_in_node', $file);

That did not help either. I am also curious as to which is the file/function that handles the set function for the file field.

UPDATE:

[SOLVED] Not sure what was wrong earlier. Both the approaches seems to be working correctly now. So setting the file_id or the file object into the file field for the node seem to be saving the node correctly with the file attached to it.

In your custom form use code like this:

$form['imagefile'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Imagefile'),
      '#default_value' => $this->configuration['imagefile'],
      '#weight' => '0',
      '#upload_location' => 'public://images/redaktion/',
    ];

And here's a piece of code how it works low level:

// check if the folder exists
$folder = date('Y-m', time());
$data = file_get_contents($imagefilepath);
if (!is_dir("/home/rainer/src/asdent/web/sites/default/files/images/pics/{$folder}")) {
      mkdir("/home/rainer/src/asdent/web/sites/default/files/images/pics/{$folder}");
}
// create the file entity
$photo = file_save_data($data, "public://images/pics/{$folder}/".$filename, FILE_EXISTS_REPLACE);

// later in your entity::create:
'myimage' => ['target_id' => $photo->id()],

The trick is to create the file entity beforehand and then link the custom entity to it.


How to get rid of CKEditor and recover access to admin pages? I can't access anymore to many module's admin page (especially CONTENT : bueditor, wysiwyg, smileys. And MEDIA : IMCE or Imagepicker) since I uninstall CKEditor. I don't know if that's exactly linked but since then, when I go to admin/config/content/ I get "Advanced Forum", "Text Format", and "CKEditor" even if I've uninstalled it.

Of course, when I click on "CKEditor", I get a normal PHP error :

Fatal error: require_once() [function.require]: Failed opening required '*****/sites/all/modules/ckeditor/includes/ckeditor.admin.inc' (include_path='.:/usr/lib/php5') in *****/includes/menu.inc on line 501

BUT if I try to force access, like typing admin/config/content/bueditor or admin/config/media/imce, I'm redirected to admin/config/content/ or admin/config/media

P.S.: I'm on D7.

I have to ask, did you properly uninstall CKEditor?  As in disable the module first (in admin/modules) and then uninstall (admin/modules/uninstall)?

It sounds like you just deleted the folder without uninstalling it properly...


How to resolve error Unable to install the responsive_tables_filter module since it does not exist I am getting an error when importing the configuration from our development branch. When running. drush cim staging.
The error is.

  The import failed due to the following reasons: Unable to install the responsive_tables_filter module since it does not exist. We installed this module a long time ago but then unistalled it, disabled it, then deleted it.

There were settings for responsive_tables_filter in these 2 config files.
/config/core.extension.yml
/config/lightning_core.versions.yml

I removed both settings. Then ran drush export then pulled from development again and ran drush import and the error was gone.
Is it safe to manually edit these files?

If the module was never installed in the target environment, it is safe to do so.

If the module was installed before however, and it features uninstall hooks for cleaning up possibly installed database tables, key/value pairs (State API), and the like, then your approach may leave data behind.

The more appropriate way would have been to uninstall the module after you restored its module files, then export the configuration again in development, push it to production and do the import there.

Afterwards you can safely delete the module files from your environments.

The error you've seen indicates, that your code base was not in sync with your configuration. You possibly tested modules and removed its files before uninstalling them.


How can i enable automatic path creating for all nodes? In Drupal 7.12 i use pathauto, cleanurls, transliteration, i18n.

When i edit one node i saw that, "Generate automatic URL alias" in unchecked.
Then i checked other nodes and saw that for all type of nodes it became unchecked.

I'm pretty sure that it was checked until last week.

The last modifications i made:
I updated Pathauto module, installed Transliteration, installed Debug Cron module.

So, how can i re-enable this checkbox in node settings page automatically ?

(Of course i can i that manually, by editing every node, and checking the check-box)

Thank you very much for your help.

If you have Pathauto installed, it will generate path aliases for your nodes. It unchecks the box when there's already a path alias, letting you know that it won't change the alias if you change the content. You can change this behavior with the 'Update action' setting here: /admin/config/search/path/settings


Hook function for admin/structure/taxonomy/your_vocaburary form (Save and Reset to alphabetical) I'm looking for a hook function to interact with the buttons "Save" and "Reset to alphabetical" on taxonomy term hierarchy. Does anyone know how to override this functionality?

with hook_form_FORM_ID_alter you can add extra function to trigger on submit.here is a simple example for you :

/**
 * Impelement hoo_form_FORM_ID_alter
 * @param array $form
 * @param type $form_state
 * @param type $form_id
 */
function MODULENAME_form_taxonomy_overview_terms_alter(&$form, $form_state, $form_id) {
    $form['#submit'][] = 'my_news_submit';
}

function my_news_submit($form, &$form_state) {
    if ($form_state['triggering_element']['#value'] == t('Reset to alphabetical')) { // check if reset button submited or not
        drupal_set_message('RESET CALLED');
        // ADD YOUR EXTRA WORKS HERE FOR RESET
    } else { // act on "save" button submited
        drupal_set_message('SAVED CALLED');
       // ADD YOUR EXTRA WORKS HERE FOR SUBMIT
    }
}


Hiding error messages: sql query I have a site running on Drupal. There is a production site, publicly seen online and a development version on a private machine.

When migrating from a devel to a production server I'd like to disable the display of error messages. This could be done in Home » Administration » Configuration » Development (D7). However I'd like to automate that; put a proper SQL query in my migration script (that packs, transfers and 'installs' the page on a production server)

Can anyone help me with that?
Thanks!

That setting is stored in the variable table as a serialised PHP string (in the "error_level" var) - I wouldn't advise updating that table manually with SQL (although obviously you can if you need to).

Far better would be to install Drush, and use vset as part of your deployment process instead:

drush vset error_level '2'

The available options are:

0 => None
1 => Errors and warnings
2 => All messages


Adjust search system - return all nodes, but exclude a specific node type if a field is less than current date I am hoping to adjust the search system results. It works great, but i have an issue with some of the results. When a user searches "Training" I pull up all node's that have "Training" in their titles, bodies, tags, etc.

I want to continue to pull up all node types. But if one of the node types (calendar_item) pops up, I got to check one of it's fields for a value, if it has a particular value then we exclude it. I found the best way of checking if the field has a value is by going to a different table (field_data_field_date) for a value in it's field (field_date_value2). To join that table to our current query we check entity_id field (in field_data_field_date) and compare it to the node.nid. Below is an example, the only issue is it actually excludes all other node types, so the only thing I bring up is calendar_items. Anyone know How to still bring up all nodes, but if it's this particular node type do the conditional check?

Please and thank you!

function mymodule_query_search_node_alter(QueryAlterableInterface &$query) {
 $u_alias = $query->join('field_data_field_date', 'fd', 'n.nid = fd.entity_id'); // No idea what the field is called, assuming 'search.date'.
 $query->fields('fd', array('field_date_value2'));
 $query->condition("{fd}.field_date_value2", '2016-03-08T21:30:00', '>=');

}

EDIT #1:
I have now adjusted the code to the following:

function mymodule_query_search_node_alter(QueryAlterableInterface &$query) {
    $u_alias = $query->join('field_data_field_date', 'fd', 'n.nid = fd.entity_id');
    $query->fields('fd', array('field_date_value2'));
    // OR clause. The default is AND. To use or, you need to use:
    $db_or = db_or();
    // Add the conditions for the OR clause
    $db_or->condition("{$u_alias}.field_date_value2", '2016-03-08T21:30:00', '>=');
    $db_or->isNull("{$u_alias}.field_date_value2");
    // Pass the Or clause to the query object.
    $query->condition($db_or);

}

If I replace

$u_alias = $query->join('field_data_field_date', 'fd', 'n.nid = fd.entity_id');

with

$u_alias = $query->leftJoin('field_data_field_date', 'fd', 'n.nid = fd.entity_id');

I get no results! But just a simple join gives me only calendar_items.

I think you need a different kind of SQL Join there, your (inner) join will produce a result set of only nodes that have an respective entry in the field_data_field_date table.

I would try a left outer join and add an OR condition for field_date_value2 being NULL. An example:

$u_alias = $query->leftJoin('field_data_field_date', 'fd', 'n.nid = fd.entity_id');
$query->fields('fd', array('field_date_value2'));
$db_or = db_or();
$db_or->condition("{fd}.field_date_value2", '2016-03-08T21:30:00', '>=');
$db_or->isNull("{fd}.field_date_value2");
$query->condition($db_or);

Cheers!


Upload custom font files I've been given a directory full of font files (woff2, svg, ttf file types). Is there a way to get these fonts to load when a page is rendered in Drupal? Is there a specific directory I have to put them in or a module that handles custom fonts?

I took a look at the contrib fontyourface module, but it seems to require using external providers instead of being able to upload your own font files.

Do you have a custom theme? If so, you can implement it like this:

Place your fonts in your custom theme, following something similar to this folder structure:

themes
  custom
    my_custom_theme
      fonts
        my_font.woff2
        my_font.ttf
        my_font.svg

And then in your CSS file (it might be in themes/custom/my_custom_theme/css/style.css for example) add the following:

@font-face {
  font-family: "my_font;
  src: url('/fonts/my_font.woff');
  src: url('/fonts/my_font.ttf');
  src: url('/fonts/my_font.svg');
}


How to replace all Add To Cart buttons with alternative text in Ubercart for anonymous users? I need to display the standard Add to Cart button for all logged in users, but anonymous users should instead see text and a link asking them to create an account or login in order to be able to add to cart. The code below works great, but it is applicable to individually-specific products only; I need it to apply to all products site-wide. How would I modify this code to accomplish this, given the fact that all Ubercart add to cart buttons contain the node ID and are thus all unique? the example shows the code applying to the product with node ID "3".

function uc_disable_cart_button_for_anonymous_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'uc_product_add_to_cart_form_3':
        // hide add to cart button for anonymous users and show text
        if(!user_is_logged_in()) {
            unset($form['actions']['submit']);
            drupal_set_message('Please login or create a free Member account in order to proceed.');
            $form['html_markup'] = array('#markup' => t('
Please login or create a free Member account in order to proceed.
'));
        }
        if(user_is_logged_in()) {
            $form['actions']['submit']['#value'] = 'Add to Order';
            $form['actions']['submit']['#prefix'] = '
';
            $form['actions']['submit']['#suffix'] = '
';
        }
        break;
    }
}

Thanks!

I think I've got the solution. Any feedback would be greatly appreciated.

<?php
function uc_disable_cart_button_for_anonymous_form_alter(&$form, &$form_state, $form_id) {
    /* Overrides the Add to Cart form text*/
    if ( !empty($form['nid']) ) {
      $node = $form['nid']['#value'];
    }
    else {
      $node = 0;
    }
    switch ($form_id) {
        case (($form_id == 'uc_product_add_to_cart_form_'.$node)):
        // hide add to cart button for anonymous users and show text
        if(!user_is_logged_in()) {
            unset($form['actions']['submit']);
            $form['html_markup'] = array('#markup' => t('
Please login or apply for a Member account in order to proceed.

Log In &nbsp; Apply for Member account
'));
        }
        if(user_is_logged_in()) {
            $form['actions']['submit']['#value'] = 'Add to Order';
            $form['actions']['submit']['#prefix'] = '
';
            $form['actions']['submit']['#suffix'] = '
';
        }
        break;
    }

    /* Overrides the Buy It Now form text*/
    if ( !empty($form['nid']) ) {
      $node = $form['nid']['#value'];
    }
    else {
      $node = 0;
    }
    switch ($form_id) {
        case (($form_id == 'uc_catalog_buy_it_now_form_'.$node)):
        // hide buy it now button for anonymous users and show text
        if(!user_is_logged_in()) {
            unset($form['actions']['submit']);
            $form['html_markup'] = array('#markup' => t('
Please login or apply for a Member account in order to proceed.

Log In &nbsp; Apply for Member account
'));
        }
        if(user_is_logged_in()) {
            $form['actions']['submit']['#value'] = 'Add to Order';
            $form['actions']['submit']['#prefix'] = '
';
            $form['actions']['submit']['#suffix'] = '
';
        }
        break;
    }
}

The main drawback that I see is that the quantity and attribute fields are still displayed, but that could be good or bad based on use-case. I'd prefer to hide them, so I may try to figure that out.


Drush 8 installation issues Few months ago I've tried to uninstall drush 6 in order to put drush 8 instead (for D6 to D8 migration purposes). I absolutely don't know why, but it's been impossible to install drush 8 on my site, whatever the method used (either directly or via composer).

More precisely, at first glance it seemed that drush 8.1 had been properly installed, but a "drush status" command displayed curiously "version 8.0.3 installed", and no drupal site has been recognised when trying to use drush 8 in the drupal directories.

I precise that I'm hosted on a managed VPS with PHP 5.5 installed and that drush 6.7 worked perfectly well.

Here are the details while using composer at the time I tried to do it (no improvement since):

[~]# composer global require drush/drush:8.*

Changed current directory to /home/user/.composer

./composer.json has been created

Loading composer repositories with package information

Updating dependencies (including require-dev)

  - Installing pear/console_table (v1.3.0)
    Downloading: 100%

  - Installing symfony/polyfill-mbstring (v1.2.0)
    Downloading: 100%

  - Installing symfony/console (v2.8.6)
    Downloading: 100%

  - Installing symfony/var-dumper (v2.8.6)
    Downloading: 100%

  - Installing symfony/yaml (v2.8.6)
    Downloading: 100%

  - Installing jakub-onderka/php-console-color (0.1)
    Downloading: 100%

  - Installing jakub-onderka/php-console-highlighter (v0.3.2)
    Downloading: 100%

  - Installing dnoegel/php-xdg-base-dir (0.1)
    Downloading: 100%

  - Installing nikic/php-parser (v2.1.0)
    Downloading: 100%

  - Installing psy/psysh (v0.7.2)
    Downloading: 100%

  - Installing psr/log (1.0.0)
    Downloading: 100%

  - Installing drush/drush (8.1.2)
    Downloading: 100%

pear/console_table suggests installing pear/Console_Color2 (>=0.1.2)

symfony/console suggests installing symfony/event-dispatcher ()

symfony/console suggests installing symfony/process ()

symfony/var-dumper suggests installing ext-symfony_debug ()

psy/psysh suggests installing ext-pcntl (Enabling the PCNTL extension makes PsySH a lot happier :))

psy/psysh suggests installing ext-posix (If you have PCNTL, you'll want the POSIX extension as well.)

psy/psysh suggests installing ext-readline (Enables support for arrow-key history navigation, and showing and manipulating command history.)

psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)

drush/drush suggests installing ext-pcntl (*)

drush/drush suggests installing drush/config-extra (Provides configuration workflow commands, such as config-merge.)

Writing lock file

Generating autoload files

[~]# drush status

 PHP executable         :  /usr/bin/php-cli

 PHP configuration      :  /usr/local/lib/php.ini

 PHP OS                 :  Linux

 Drush script           :  /home/user/vendor/drush/drush/drush.php

 Drush version          :  8.0.3

 Drush temp directory   :  /tmp

 Drush configuration    :

 Drush alias files      :

 /home/user/.drush/en.aliases.drushrc.php

 /home/user/.drush/fr.aliases.drushrc.php

 /home/user/.drush/es.aliases.drushrc.php

[~]# drush version

 Drush Version   :  8.0.3

[~]# cd public_html/en/sites/en.mysite.com/

[~/public_html/en/sites/en.mysite.com]# drush cc all

No Drupal site found, only 'drush' cache was cleared.                [warning]

[~/public_html/en/sites/en.mysite.com]# drush ups

Command pm-updatestatus needs a higher bootstrap level to run - you  [error]
will need to invoke drush from a more functional Drupal environment
to run this command.

The drush command 'ups' could not be executed.                       [error]

This method should work in almost all environments:

Browse https://github.com/drush-ops/drush/releases for the release you want. You can't use drush 9 with php 5.5, so you have to choose drush 8.

Download the selected drush version

wget https://github.com/drush-ops/drush/releases/download/8.1.3/drush.phar

and try to run this php runtime file:

/usr/local/php5.5/bin/php drush.phar status

The php path is an example. You only need it, if php does not pickup the right php version.

You can keep running drush like this, but it is more convenient to rename it to drush, make it executable with chmod +x drush and copy it to a location where your shell finds it as executable (a path defined in $PATH). This depends on that your environment allows you to execute phar files.


Can I program a check on a save on an admin page? Take for example the CKEditor admin page, where at file browser settings you can choose IMCE at file browser type. Then  you click Save.

Can you program this? I mean in PHP; because I could also find out which SQL query is done, and use drush sql-query, but that is not what I mean. I want to program it because I have a multisite with about 70 sites.

Thanks,

Eric J.

Yes, use hook_form_FORM_ID_alter()

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'MYMODULE_some_validate_function';
  $form['#submit'][] = 'MYMODULE_some_submit_function';
}

function MYMODULE_some_validate_function($form, &$form_state) {
  if ($form_state['values']['foo'] !== 'bar']) {
    form_set_error('foo', t('Foo must be bar'));
  }
}

function MYMODULE_some_submit_function($form, &$form_state) {
  // Do something.
}

It's not possible to be any more specific than that as 'admin' pages vary in their structure. Most are created using a system_settings_form(), though, so there's a reasonable amount of consistency.

It's also worth noting that a form created with system_settings_form() saves its data in the variables table, so you can accomplish the same thing in a lot of cases with variable_set():

variable_set('site_name', 'New name');


How do I create a sticky navigation bar in Open Social? I'm using D8 and working on new theme in Open Social witch uses bootstrap/sass. In my theme I want the navigation bar (in the header region) to be sticky at the top of the screen.
I've made some javascript/sass code but I can't get it to work. This is what I have done so far:

Created a new javascript function in the theme_name.js file:

    //-- Sticky Header
    (function($) {
        Drupal.behaviors.navbar = {
            attach: function (context, settings) {

                var nbar = $('.header');

                if (nbar.length) {
                    var elmHeight = $('.header-top').outerHeight(true);
                    $(window).scroll(function() {

                        var scrolltop = $(window).scrollTop();
                        if (scrolltop > elmHeight) {
                            if (!nbar.hasClass('sticky')) {
                                nbar.addClass('sticky');
                            }

                        } else {
                            nbar.removeClass('sticky');
                        }
                    });
                }
            }
        }
    })();

This is a code snippet from the navbar.scss file:

.navbar-sticky-top {
  @include z-depth-3;
  position: fixed;
  top: 0;
  left: 0;
  z-index: $zindex-navbar-sticky;
}

Code snippet from the index.twig file:

...

This is the content of the region--header.html.twig file:

{% if content %}

      {{ content }}

{% endif %}

What am I missing here?

Seems like you're over-complicating it by re-writing things that bootstrap already does.  The stock bootstrap theme and most of it's subthemes should have a setting in the theme for setting a fixed nav bar.

See Appearances -> Theme settings -> Components -> Navbar.  There is an option for fixed top navbar.

If that does not do what you want, there is also the Bootstrap Affix plug-in which should be part of the standard drupal bootstrap theme.

See:  This W3school page for details.


Can´t create more than one content type group I am using Drupal commons for a community social network. I am trying to create a second group based on a content type named Leagues. In order to create that group I went to: /admin/structure/types/add, gave the group a name and selected the group check box (as the example given on this page: https://www.drupal.org/node/2014777).

But for some reason every time I try to create a new league and save it, I get this error:

  EntityMetadataWrapperException: Unknown data property field_og_subscribe_settings. in EntityStructureWrapper->getPropertyInfo() (line 335 of /home2/jane/public_html/devpage/profiles/commons/modules/contrib/entity/includes/entity.wrapper.inc).

It seems that the field field_og_subscribe_settings is attached to the content type group which I am not exactly sure what it means, but it seems I can´t create more than one group based on a content type.

It seems this solves your issue : EntityMetadataWrapperException

You probably need to add field_og_subscribe_settings field to your new content group type, and make it required.

You can take a look at

/admin/structure/types/manage/group/fields/field_og_subscribe_settings

to see how it's been configured for the default group content type.

Refer this link for detailed details about this issue: EntityMetadataWrapperException errors due to features not being reverted


Remove default configuration on uninstalling module During install we create content types, field storages and vocabularies. When uninstalling none of these things are uninstalled.

I know that we can set all the configuration to have the module as dependency, but that is tedious to do; is there a better way to let Drupal uninstall all the configuration on the module in the config/install folder?

I know that we can set all the configuration to have the module as dependency, but that is tedious to do; is there a better way to let Drupal uninstall all the configuration on the module in the config/install folder?

Not really. Deleting the configuration is just as tedious, as you need to know what's yours. you could solve it using a naming pattern and list all node types, fields, views, .. starting with yourmodule_ I guess.

There's been some discussion to automatically add the module providing the configuration as an enforced dependency, but that's actually also not always what you want.


Syntax error:  (line 1) in Firebug Firebug is complaining about a error in <!DOCTYPE html>,  but the HTML source is passing without problems the HTML W3C validator.

Do you have any idea? Sorry, I can't share the source code.

The reason was a failed loaded javascript file.
I use the following code to add a JavaScript file:

drupal_add_js($p . '/slider.js','module','footer');

So the following HTML was added in the footer of the page:

<script type="text/javascript" src="/sites/default/modules/custom/slider/slider.js?G"></script>

At some point I renamed the file slider.js, so it stopped being loaded, and this is the reason behind the Firebug error.

In the "Net" tab, Firebug was not showing any error; it was showing just a "301 Moved Permanently" next to the slider.js file.


Drupal webform module problem occured send email using webform.
if email does not exist get failure message in inbox
Do we need SMTP
which module we need
and settings(gmail) what we need???

Install the SMTP module

Step 1: Download the SMTP module for Drupal: https://drupal.org/project/smtp

Step 2: Extract to /sites/all/modules

Step 3: Enable the module on Admin - Modules

Step 4 (for Drupal 6 only): you have to install the PHPMailer package from Codeworx Tech., version supported is below 2.2.1. Place it in a directory named "phpmailer" in /sites/all/modules/smtp

For Drupal 7, this is no longer required. The SMTP module for Drupal 7 is shipped with the PHP Mailer. It works out-of-the-box

Configure with Gmail account

Step 1: Pls go to Admin - Configuration - SMTP Authentication Support

Step 2: On Install Options, please choose On

Step 3: On SMTP server setting, please enter

SMTP server: smtp.gmail.com
SMTP backup server:
SMTP port: 465
Use encrypted protocol: Use SSL
Step 4: On SMTP Authentication: Enter user name and password of your Gmail account.

Step 5: On Email options: Enter your email from address (could be noreply@yourwebsite.com) and email from name (could be your site name).

Step 6: On Send test email: enter a email to test whether the module is working. Click on Save and go to your inbox to check. If there is an testing email then it is fine.

If it does not work, you may need to tick on the option "Enable debugging" and send a test email. The responses will be printed so you know more about the problem.

I attach the screenshot of a SMTP configuration.


How do I make the select options have a textfield beside them instead of a box? I created a webform that uses dynamic select options generated from a specific content type, which represent objects. I would like to have a text field beside each one to in which the user can input the desired quantity of the object.

I have tried looking this up on Google but to no avail. How should I go about doing this? Is there a module or a specific way by which I can implement this?

Thanks for reading this.

You can build your own custom Form api element looking at select other example
http://drupal.org/project/select_or_other
and the documentation for it form api element is at http://drupal.org/node/1158654


How to manually uninstall a module? I'm trying to uninstall the "Browsing History Recommender" but I get the HTTP 500 Server error. I want to remove this module completely from the database and FTP.

I have been searching for a solution but no luck, I have also read this question.
How to manually uninstall/purge modules?

Please Help. Thanks

Drupal 7
Ubercart 3

If you have access to ssh, use drush to disable and uninstall the module. If you do not have access, disable your module, set the status to 0 for the module name that you want to disable.

UPDATE system SET status='0' WHERE name='module_name';

And then you can manually delete the table "history_rec_user_map".

It however has two variables ('history_rec_uid_watermark' and 'history_rec_last_aid') in the variables table. Use variable_del to delete them

To remove modules, you have to remove them from your server's modules directory (usually sites/all/modules/).

UPDATE:

To delete the modules blocks use delete from block where module = 'MODULE'


Can I easily export content? Let's say I have a Drupal 7 website, with 3 taxonomies and 3 articles.

 - Cars
   - Sport
     - Porshe
 - Family
   - Taurus
 - SUV
   - Navigator

No modules, no nothing, just this content and taxonomies.

Is is it a fairly simple process?

If you have nothing but that, yes, Drupal core migrate and migrate_drupal_ui module will easily do this.


User-selectable CSS style I have three CSS versions (default CSS, black on white and white on black for visually impaired users) of my drupal-7 website to be selected by users if they need to.

And I just have no idea how to do this with drupal... I would like to add a drop-down list in the footer to change the CSS used. Then, I imagine I would have to store it in a session variable or a cookie and change the CSS according to this value.

There may be a more elegant way to do this, but I would use the Switchtheme module, which provides a block that allows users to switch themes.

To make this work, you will have to create three separate themes, one for each option.  However, this is not as complicated as it sounds.  Just make the black-on-white and white-on-black themes subthemes of your main theme (the one with default CSS); then all you will have to do is set up the subthemes one time and add the CSS.


Should we use a separated database for our data set? We are working in website and integrating the Drupal Commerce in our website. We are also adding multiple  product per product display to allow user to select products while adding product to cart.

The website will have large data set with more than 10 million product display (node) and more than 30 million products (drupal commerce).

We have also integrated apache solr with search api and allowing user to keyword search and filtering the search result.

Can anyone suggest that if we would stored such large data into single database, will it effect our performance or we need to stored data into 'master/slave' concept of database?

As we have large dataset, so we are preparing architecture of our database, so it would not effect performance of our website.

Talk to your hosting provider. If they can't answer these questions, get a new hosting provider.

These really are concerns you should bring to your hosting provider. A quality hosting provider will be able to meet these needs and tailor a solution that ensures smooth operation of a site as a whole and within the individual components: Solr, MySQL, Apache/Nginx/Litespeed/etc.

How will they do this?

Benchmarking - Before launch, they'll launch a version of the site and then work to ensure that certain performance criteria are met. They'll tweak and scale to meet these numbers.
Infrastructure - Just having a master/slave DB isn't necessarily a solution. You have to have good infrastructure and equipment backing it up. It also has to be architected well. Good providers will have this.
Multiple Layers of Scalability - Having multiple strategies to handle load or large sites is key. This means not just having a huge DB but also effective content distribution (CDN) and internal Drupal caching (Redis) in addition to strong infrastructure.


Version 5.9: Which components does "drush site-alias --local" look for in ~/aliases.drushrc.php? In version 5.9, "drush site-alias --local" returns what I consider to be non-local sites, because they each have a remote-host and a remote-user component set in  ~/aliases.drushrc.php.

I don't understand part of this excerpt from "drush help site-alias":

--local   Only display sites that are available on the local system (remote-site not set, and Drupal root exists).

What does "remote-site" refer to -- some other component in  ~/aliases.drushrc.php?

Thanks,

Glo

The filtering is done in the _drush_sitealias_user_specified_list() function with

if ((array_key_exists('remote-site', $one_site)) || (!array_key_exists('root', $one_site)) || (!is_dir($one_site['root']))) {
  unset($site_list[$site_name]);
}

So it looks like the remote-site option is used. But the documentation for the alias settings does mention a this option. So this looks like a bug.

Note: the same condition is still used in the latest version (see https://github.com/drush-ops/drush/blob/master/commands/core/sitealias.drush.inc#L164).


How to change datatype of field in database table from varchar to int? I have created custom table. Now I want to change datatype for a particular column in table. Column name is 'session_number' and its current type is varchar. I want to change it from varchar to int. I used this to do so :

function mymodule_update_7053(&$sandbox) {
  db_change_field('abc', 'session_number', 'session_number', array(
    'type' => 'int',
    'size' => '255',
    'not null' => TRUE,
  ));
  drupal_flush_all_caches();
}

It doesn't change existing type from varchar to int. How to do it please guide.

You must have some error message if the conversion is not accepted.

You first have to validate that this field is not a key or an index. See the db_change_field documentation about this.

After, I think 255 is not a valid value for the size key. The Schema API documentation tell :

  'size': The data size: 'tiny', 'small', 'medium', 'normal', 'big'.
  This is a hint about the largest value the field will store and
  determines which of the database engine specific datatypes will be
  used (e.g. on MySQL, TINYINT vs. INT vs. BIGINT). 'normal', the
  default, selects the base type (e.g. on MySQL, INT, VARCHAR, BLOB,
  etc.). Not all sizes are available for all data types. See
  DatabaseSchema::getFieldTypeMap() for possible combinations.

And finally, I'm not sure if the DB engine can support the VARCHAR to INT conversion. Then it means your column will be empty and cannot support the 'not null' => TRUE property.

Maybe you have to do this in more than one step.


update a node field when flagging I want to achieve the following :
I have a node 'proposal' with a flag 'accept' and another node 'project'.
I want when a user flag the 'proposal' with the 'accept' flag, a field value in the 'project' node is updated.
I wrote this code but it seems not to work

function mymodule_flag_flag($flag, $entity_id, $account, $flagging)
{

$node =  node_load($entity_id);
$freelancer = $node-> uid;
$project_node = node_load($node->field_projet['und'][0]['target_id']);
$wrapper = entity_metadate_wrapper('node', $project_node);
$wrapper->field_freelancer->value = $freelancer;
}

I do not see that you are saving the project node, after changing field value.

function mymodule_flag_flag($flag, $entity_id, $account, $flagging) {
  $node =  node_load($entity_id);
  $freelancer = $node-> uid;
  $project_node = node_load($node->field_projet['und'][0]['target_id']);
  $wrapper = entity_metadate_wrapper('node', $project_node);
  $wrapper->field_freelancer->set($freelancer);
  // You missed
  $wrapper->save();
}


Different product attributes same SKU I need the user to choose a serial number from a drop down when viewing the product display. For example there is a product SKU of unxm_12 for Uncanny Xmen #12, there are 3 in stock and each one has a serial number, all are the same price.

We want the user to be able to choose a serial number from a drop down and then we can view that serial number on the order later to determine which comic book they actually want.

This needs to be custom for each product, each SKU can have multiple serial numbers. There are many products. What is the best way to do this?

Have you tried Commerce Product Attributes?


Admin user can't manage fields on custom content type When in logged in to my Drupal 7 install as the administrative user, I can't access the "Manage fields" or "Manage Display" for my custom content types.

I've tried all the following with no joy:

I've deactivated all my custom modules
I've given the admin user all permissions
I've flushed the cache, many, many times
Logged out and back in

I'm pretty sure I'm not using the hook_drupal_break hook anywhere!

I've got NO IDEA what I've done wrong. It used to work, but now I can't access it.

I feel so stupid. But I'm leaving this answer so that the next person to have this same problem will save 3 days of development time:

The module that allows fields to be created on entities (nodes, user etc.) is creatively called "Field".

But, that doesn't mean you'll have a UI to create/edit them. There is another creatively named module called "Field UI". If this modules isn't installed AND enabled you won't have a user interface to edit your fields...


trigger event before content is parsed after ajax I want to ajaxify my site. Everything, that is usally parsed as "Page Content" sould be opened in a lightbox.
So the idea is to ajaxify every link and let #lightbox be filled with the result.

but before ajax parses the request-result, I want some javascript to be done. So I want an event to be triggered after the ajax respond, and want to parse the result by myself.

any suggestions?

EDIT:

I could store the content in an hidden div#object, and use an ajax_command_invoke('body','trigger',array('myevent'))  to trigger a function attached to myevent. Does this make sense?
than I just dont know how to implement this to all links.

Are you using AJAX API? All the Ajax commands have the same return, for example

array(
    'command' => 'insert',
    'method' => 'html',
    'selector' => $selector,
    'data' => $html,
    'settings' => $settings,
);

And if you open the file misc/ajax.js, you will find insert() function in Drupal.ajax.prototype.commands. I think now you got the idea right? You just need to define a new ajax command by extending standard library, for example

Drupal.ajax.prototype.commands.lightbox = function (ajax, response, status) {
    // Do something with response.
};

And on server side, you just need to return

array(
    'command' => 'lightbox',
);

You can put more options in the command like what core does.


How to pass values or data from a page to a webform using webform link field? If we have a link to a webform in a content type and we need to pass data or values to that webform from the fields available from the content type. How do we achieve this.

I'm using webform 8.x-5

I had hardly any success with 'Field Token Value' or setting default values from the available token of the webform build settings.

Add a webform reference field to the content type and put the default values in

Default submission data (YAML)

and you see this example provided by the field:

# This is an example of a comment.
element_key: 'some value'

# The below example uses a token to get the current node's title.
# Add ':clear' to the end token to return an empty value when the token is missing.
title: '[webform_submission:node:title:clear]'
# The below example uses a token to get a field value from the current node.
full_name: '[webform_submission:node:field_full_name:clear]


Drupal 7 - Destroying the session when the browser closes is not working on Chrome Is there an issue with destroying the user session using Chrome? I've set this setting in settings.php: ini_set('session.cookie_lifetime', 0) but it seems like Chrome ignores it or is it just caching the user session itself.

On IE and FF this works as intended. I've even set Chrome to not save user credentials but to no avail.

Any ideas please?

This is not a problem with drupal session. The feature that remembers the opened tabs when the browser is closed is the root of your problem. The feature is named "On startup"  "Continue where I left off". Turn that off and you should be fine.


Contextual Filter (Author's Username) Multiple usernames I'm setting up a custom Views RSS Feed that looks something like this.

The problem is, when I add one user name as a filter, it works but anything after it, the view will not show the post of the other user. Ex: If my name is X and I put X in for the filter, it shows X's post but if I put in X/Y, only X's posts will show.

You have to have the "Allow multiple values" option of the contextual filter set (it is in the "MORE" collapsible fieldset).

Then you have to separate the names with a plus symbol (+) or a comma (,).

If you separate with a slash views will treat it as 2 separate arguments and your view only has one argument.


Rotating image background in a div using Background Field I have successfully added background graphics using the module BackgroundField module with the help of this previous question. We've had a feature creep in that we need to have a rotating image from a preset pool of images. Does anyone know of an module to facilitate this request?

It is not a Drupal Module but a very simply jQuery plugin to use.

http://jquery.malsup.com/cycle/

A snippet of me using it from my javascript:

function handle_header_carousel() {
    if ( jQuery('#header_carousel').get(0) == undefined ) {
        return;
    }
    jQuery('#header_carousel').cycle({
        fx:     'fade',
        speed:   300,
        timeout: 3000,
        next:   '#s3',
        pause:   1
    });
}

From my template page that houses the images:

            <img src="/<?php echo drupal_get_path("theme", "tcth"); ?>/img/carousel_1.jpg" />
            <img src="/<?php echo drupal_get_path("theme", "tcth"); ?>/img/carousel_2.jpg" />
            <img src="/<?php echo drupal_get_path("theme", "tcth"); ?>/img/carousel_3.jpg" />
            <img src="/<?php echo drupal_get_path("theme", "tcth"); ?>/img/carousel_4.jpg" />


How to show a title-link in a view for authorized and hide it for unauthorized users? I have a view with some fields and one of them is the title field. Now i need the feature that when an anonymous user views the view, the title is not linked to it´s content. When the user logs in, then the title should link to its content. How is it possible to realize that? I have more or less no php skills.

You can implement template_preprocess_views_view_field function in your module and rewrite output for this field for anonymous users.

/**
 * Implements hook_preprocess_views_view_field().
 */
 function mymodule_preprocess_views_view_field(&$vars) {
   switch ($vars['view']->name) {
     case 'my_view_name':
       if ($vars['field']->options['id'] == 'my_field_name') {
         if (user_is_anonymous()) {
           $vars['output'] = strip_tags($vars['output']);
         }
       }
       break;
   }
 }


Inline CSS stripped from Global: Custom text in Views I did some research on the problem in the title but haven't found any good solutions yet.

I'm using a Global: Custom text view field in a view and I need inline CSS to work in there.

I know that it gets stripped because security reasons, and I have to use inline CSS for my problem. So "use CSS classes" is not a solution, I'm well aware that in most cases that would be the best but it's not ok in this case.

Writing a node.tpl.php for the content instead of using a view in Fields mode is also not possible, becaue I have to use view result counter token on the same div where my inline css should go (with another token inside the inline css).

Thank you!

It's still not wise but use a custom PhP field : Views PhP (it's "Views custom field if you're on D6).


All added links open as target, how to prevent it? In my Drupal based website, all links that I added from CKeditor open as (target="_blank"

Link example: (Name)
After adding, example from html source: (Name)

As you see, the 'target="_blank" rel="nofollow"' added automatically.

How can I solve this problem?

In CKeditor  when adding a link it will ask

click -> hyperlink button ->in Target set it as  will resolve your issue.

or if you have installed external  module means disable it.


Preserve views exposed filter options when back button is pressed I have an ajax exposed filter in the views. When user select option from filter it loads content. But when I click on item on view and press browser back button, exposed filter resets and default option is selected. Same thing happen when I refresh the page.

Is there any way in view to preserve the last selected option? Same thing happens when I click on page number of views.

Thank you.

You'll have to turn off ajax to get this to work until this issue is resolved. See http://drupal.org/node/1248332

Then edit your exposed filter(s) and check off "Remember last selection".


Actions module - redirect to url I'm trying to learn about the functionality of this module, however I don't understand quite right what the Redirect to URL option means/does. Any hint in the right direction will be much appreciated.

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

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


Set a token as the default value of a new field In Drupal 7, you can set defaults values for most fields. Is it possible to set a token as the default value.

I remember this being possible in Drupal 6, but it doesn't seem possible in Drupal 7.

There is a thread here that discuss the possibility, but its not clear if it was solved.

What information do you try to get??

In one of my Content Type, I need to retrieve the node ID. I found that the token for the current node ID is this:

[current-page:url:args:last]

Tested and working for me!!


Render form element of type text_format, keeping WYSYWIG format In Drupal 8 I have a form element fo type text_format, and I need to render it in a twig, but keeping the same format was entered in the WYSYWIG editor. I need to know how to render this element form, keeping the format? this its done in a custom form.

$form['template'] = [
  '#type' => 'text_format',
  '#title' => 'My title',
  '#rows' => 100,
  '#cols' => 120,
  '#format' => 'full_html',
];

The solution is render it using the #type => processed_text. That's it, then you will see the element renderd keeping the format used in WYSYWIG.

$elements = [
  '#type' => 'processed_text',
  '#text' => $data,
  '#format' => 'full_html',
  '#langcode' => 'en',
];


Is there any module that let (selected) users (/roles?) see the Administration pages in read-only mode? Is there a module out there which lets us assign a permission to a role which lets a user look at the site from the perspective of an Administrator, or better, from within the permissions of any selected other role; in a view-only/read-only mode?

That would be useful to let people explore Drupal on sites with existing setup and content without having to create/clone and maintain example sites for such purposes.

(Click around in any (admin/content management) page related to the given "read-only role" without the ability to make/save changes.)

Interesting requirement.

Presumably you could assign the relevant admin permissions to the role, e.g "access administration pages", "administer site configuration" etc..

After that, you could prevent changing any settings with a hook_form_alter, adding the $form['#validate'] handler to form_set_error for non-admin users / users of that role. You could also possibly hide the submit button with a suitable #access check e.g #access => user_access('special permission'); on the button itself.

e.g

/**
 * Implements hook_form_alter
 */
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'MODULE_readonly_admin_access';
}

/**
 * Custom validate callback
 */
function MODULE_readonly_admin_access(&$form, &$form_state) {
  if (path_is_admin(current_path()) && !user_access('admin write access')) {
    form_set_error(NULL, t('Operating in read-only mode.'));
  }
}

It would definitely need a lot of careful testing to ensure no loopholes (e.g services API access, #limit_validation_errors cases) - make sure all bases are covered.


When attempting to run drush ": No such file or directory" I've been bashing my head against the wall all day trying to figure out why Drush has suddenly stopped working.

I've re-installed via composer, tried different versions, always the same error.

If I type which drush I get /home/user/.composer/vendor/bin/drush which is correct.

If I type sh -vx drush in an attempt to debug what's happening with the script, I get the following output:

#!/usr/bin/env sh
#
# This script is a simple wrapper that will run Drush with the most appropriate
# php executable it can find.
#
# Solaris users: Add /usr/xpg4/bin to the head of your PATH
#

+
: not found/.composer/vendor/bin/drush: 8: /home/user/.composer/vendor/bin/drush:
# Get the absolute path of this executable
SELF_DIRNAME="`dirname -- "$0"`"
+ dirname -- /home/user/.composer/vendor/bin/drush
+ SELF_DIRNAME=/home/user/.composer/vendor/bin
SELF_PATH="`cd -P -- "$SELF_DIRNAME" && pwd -P`/`basename -- "$0"`"
+ cd -P -- /home/user/.composer/vendor/bin
/home/user/.composer/vendor/bin/drush: 1: cd: can't cd to /home/user/.composer/vendor/bin
+ basename -- /home/user/.composer/vendor/bin/drush
+ SELF_PATH=/drush

+
: not found/.composer/vendor/bin/drush: 12: /home/user/.composer/vendor/bin/drush:
# Decide if we are running a Unix shell on Windows
if `which uname > /dev/null 2>&1`; then
  case "`uname -a`" in
/home/user/.composer/vendor/bin/drush: 15: /home/user/.composer/vendor/bin/drush: Syntax error: word unexpected (expecting "in")

wut

Ok, maybe something wonky is returned with uname -a? The response from my server is:

Linux servername 3.2.0-58-generic #88-Ubuntu SMP Tue Dec 3 17:37:58 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

There are no directory permission issues... everything is owned by the user. I'm at a complete loss. I've tried drush 5, 6, and 7 - same sort of error in each.

The server is running Ubuntu 12.04.2 LTS

I was getting this same error when running drush commands on a remote computer via a drush alias.  I could run the same drush commands  on the remote system directly with no problems but when I would try to run them via a drush alias (@remotesystem) I would get this error.

I found that the user on the remote systems default shell was sh and not bash. Because the bash configuration file ~/.bashrc contains the line that adds the location of drush to the path the sh shell was not able to find drush as ~/.bashrc will not be sourced by the sh shell only by bash.

The drush installation instructions on docs.drush.org state:

  Now add Drush to your system path by placing export PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash_profile (Mac OS users) or into your ~/.bashrc (Linux users).

You can check what your current shell is set to by running:

export |grep SHELL

This will print a line with your current shell in it like this:

declare -x SHELL="/bin/bash"

On Ubuntu the default shell is sh but the default user shell is bash. This happened on a Ubuntu Server install (no GUI).

To fix this change your default shell to bash.

For current users run the following to change the default shell:

sudo -u <USERNAME> chsh -s /bin/bash

For future users, if you use useradd, edit the /etc/default/useradd skeleton file (don't forget to make a backup though). Change the line:

SHELL=/bin/sh

to

SHELL=/bin/bash

This will set bash as the shell for new users that are created.


Custom Public form for content type How can I create a form for a specific content type so that it can be accessed publicly, I mean by user that has no administrative rights but on this content type only?
I specificly need to hide all options like publication options, menu options etc from the basic form.

Thanks

Theming the default "node/add/content-type-name" content type form will allow you to achieve what you need as these forms are publicly available to users with permission. If the user has permission to create that content type, he will be able to access the page, so either create a link to the page (node/add/content-type-name) or use the default Navigation Menu link "Create Content" to take the user to the node/add page.  Take a look at Theme a CCK Input Form for CCK2 & CCK3 to learn more about theming content type forms.

To remove the configuration fieldsets such as Menu Settings, Publishing Options, Revision Information, etc you really just need to change the permissions for the role.  For example, remove "administer nodes", "administer menu", "administer comments", etc.


Drupal commerce email order notification not sending properly On the rule of sending email order notification I just changed the "FROM:" of the send mail, instead of the email of the website I want the email of the anonymous customer from a custom field of billing information I created then this will be sent to the admin.

This is my current rule:

{ "commerce_checkout_send_an_order_notification_e_mail_admin" : {
"LABEL" : "Send an order notification e-mail ADMIN",
"PLUGIN" : "reaction rule",
"WEIGHT" : "4",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
{ "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_customer_billing" } },
{ "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_line_items" } },
{ "entity_has_field" : {
"entity" : [ "commerce-order:commerce-customer-billing" ],
"field" : "field_email"
}
}
],
"DO" : [
{ "entity_fetch" : {
"USING" : {
"type" : "commerce_customer_profile",
"id" : [ "commerce-order:commerce-customer-billing:profile-id" ]
},
"PROVIDE" : { "entity_fetched" : { "customer_profile" : "customer_profile" } }
}
},
{ "mail" : {
"to" : "[site:mail]",
"subject" : "[customer-profile:field-full-name] - Event: [customer-profile:field-event-name]",
"message" : "Customer Name: [customer-profile:field-full-name]\r\nCustomer Email: [customer-profile:field-email]\r\nCustomer Contact Number: [customer-profile:field-contact-number]\r\nEvent Date: [customer-profile:field-event-date-no-end-date:event_date]\r\n\r\nPackages Selected:\r\n[commerce-order:commerce_line_items]\r\n\r\nOverall Total: [commerce-order:commerce_order_total]",
"from" : "[customer-profile:field-email]",
"language" : [ "commerce-order:state" ]
}
}
]
}
}

When I checked the log report of the website it says "Successfully sent email" but I never received the email. but whenever I change the "FROM:" to blank or [site:mail] I will receive the email notification. Why is that? The token I used for the "FROM:" is exactly the same as on the message and it's correct.

Your issue is due to server email blocking. Please configure SMTP module for sending emails from the website. This will add appropriate headers in the mail, and your email will not get blocked.

Hope this will help you.

Thanks


How can I upgrade from Drupal 8.0.x to Drupal 8.1.x? How can I upgrade from Drupal 8.0.x to Drupal 8.1.x?

Do I have to copy the core files in the project folder and then run update.php as usual, or do I have to do something more complicated like when migrating from older versio

Yes, replace the core and vendor directories and run update.php.

Note:

  Also please follow the instructions from upgrade.txt. There are several other necessary instruction so that you can recover from any mishappening.

Drupal treats 8.0.x and 8.1.x as 8.x.x.


Drupal view to display node activity I need to provide a view which gives a simple list of user activity with regards to node 'events' - e.g. any updates to fields, new nodes created, nodes deleted etc..

For example,

Last Updated:         Activity
-----------           --------
..
5 mins ago -          username has updated Title for node:nid
6 mins ago -          username has updated Price for node:nid
7 mins ago -          node:nid has been deleted
13 mins ago -         new node:nid has been created..
..etc

Has anyone achieved something similar? If so - how did you go about this? Did you use a module?

As per your requirement it seems Activity module will suite you. But again this module is in Dev version for Drupal 7. So if you are ready to use Rules module then go ahead. Since you are only tracking the node create & edits then in Rules module you will get all the conditions and events.

But if you are also okay with developing custom module then I'd suggest to write a custom module and with all the HOOKs provided for nodes you can create the desired records and store those in a table. See the HOOKs for nodes here.

Let me know if I can assist you with creating a custom module.


Insert a value to $form_state function form_example_form($form, &$form_state) {
      $form_state ['store_value'] =1;
      $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Click Here!'),
      );

  return $form;
}

How to do this in drupal 8

Insert the the value in $form_state:

$form_state->set('store_value', 1);

And then later for example in submitForm():

$value = $form_state->get('store_value');

Don't use getValue() or setValue(), because this is for submitted values.

If you are migrating more forms from D7 to D8, use this as reference:

$form_state is now a classed object


How to create active menus for the content type in drupal 7? I want to create a simple content type with menus ,on clicking each menu the content will be shown on the same block but of the respective menu item.

In this image ,i am having 3 menus a,b ,c with a content .On clicking 'a' menuitem respective content of 'a' will be shown ,on clicking 'b' respective content of 'b' will be shown and so on.

Can anyone help me with this issue!.

If you're just about tabs in a content type you could try this.


Creating commerce iframe payment I need to create an iframe to my payment provider that will do the actual payment in the checkout process of Drupal commerce.

In this iframe the user will actually insert his credit card details.

What is the best way to accomplish this?

I need this (of course) to interact with the commerce checkout process.

I did create a Commerce payment gateway with an almost similar challenge. You can have a look at the Commerce Pesapal module code.

A brief description would be;

Register a Commerce payment method.
Create settings for your payment method if any.
Implement hook_menu()and create at least three pages. One to hold the iframe, one to hold the callback from the payment gateway and another that will hold the form used to pass values to the iframe.
The second page can also be used to pass a message to the user.
On the redirect form you will not use a 'Submit' button because we need to pass the values to an internal URL. Instead you will do something like this.

$form['#action'] = $base_path.'Path To Your Iframe';
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Pay',
);

On the iframe page you can get all the variables rom your redirect from using $_GET.

The rest of the details I believe will depend on the gateway provider from that point on.


Menu does not appear while opening my site management menu such as add content type,module ,configuration does not appear in my site.
So how can I solve it.

Please login through admin credentials. Check module permissions for Toolbar for authenticated users. Check that if it is unchecked. Try flushing drupal cache.

Once you see the toolbar. You can install admin_menu for better administration menu.

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


Using Services, why is the resource name appended to the endpoint? If I want an operation of GET api/v1.0/users and api/v1.0/pages:

Using the Services module to create a REST API, if I define a service with an endpoint of api/v1.0/users and enable the user resource (let's say I enable the Retrieve action), then I have to go to the URI /api/v1.0/users/user/ to get it to work. If I don't include the /user at the end, it returns a 404 error.

However, if I make the endpoint simply api/v1.0, and enable the same resources, then the URI is closer to expect and want: /api/v1.0/user/, but still not quite right. Also, If I define other endpoints using this style (eg. for /api/v1.0/node/), only the last one works; the rest return a 404 error.

Why is it designed this way? And how can I make it not append the resource name to the end?

Update: Based on @mradcliffe's answer, it seems that it's been designed this way so that you can define a single endpoint as a sort of 'endpoint base', such as api/v1.0, then enable multiple resources, which then append their names to the endpoint path.

The problem I see with that is that, if I later create a new version of a resource (eg. the user resource) that does things a little differently, and I thus want to name it with a new version number (eg. users_1.1) to distinguish it from the old resource, that would create a horrible endpoint path of api/v1.1/users_1.1...?

Update: To answer the question of my previous update, I think a better (more efficient) programming practice would be to simply check the api version within the code (wherever the new code deviates from the old) rather than re-naming the resource. I could define a function that pulls the version out of the path for this checking.

See mradcliffe's comment for a good explanation of the difference between an endpoint and a resource, understanding that will make it clear why the Services module does things the way it does.

Why is the endpoint for the user entity type specifically named user?

Conceptually speaking it's a safe bet that the module developer followed common REST patterns, and adopted the name of the entity as defined by the system the code is sitting in (i.e. the user entity type defined by Drupal core).

From a technical point of view, the resource is named user because the services module explicitly names it as such in _user_resource_definition():

$definition = array(
    'user' => array(
      'operations' => array(
        ...

Not a fan of this particular convention? Not a problem, Services has you covered.

Go to the "Edit Resources" tab for your endpoint, and look in the right hand column of the table; you'll see a text field that takes an "Alias". Set that to "users" for the User resource.

Set your endpoint to something sensible like 'api/v1.0', and you can now access the user resource through its alias at http://example.com/api/v1.0/users. It sounds like you might also want to add a "pages" alias for the "Node" resource, but I'm speculating a bit.


How to change the path in which are stored the media modules files and images? When using media entity reference fields, is it possible to change the path where are stored the files and how?
Is it possible to store them in the private folder?

i have found the radio button for selecting private in

/admin/structure/media/manage/file/fields/media.file.field_media_file/storage

how to change folder path , using possibly tokens?


Log a user in manually, get session? A service I have takes a username, and should find and log in a local Drupal user account with that username. After logging in, I need the session ID (from the sessions table) for that users new session.

I have some basic procedural code that I'd like to refactor for Drupal 8 practices:

$user = user_load_by_name($username);
if ($user) {
  user_login_finalize($user);
}

1) What's the OO way of loading a user entity? A service I found that may help loading a user is entity.manager, but is that the right way to do it?

2) Logging a user in? Should I just take the code from user_login_finalize and try and inject the services used and essentially "copy" what's done in that function?

3) After the user is logged in, how can I get their session information? Injecting the current_user service doesn't work, because the user data in there is stale after I log the user in.

EDIT: Looks like a user's session is not saved until AuthenticationSubscriber runs (listens for kernel response event), which is when the session data would be saved. Maybe I can manually save the session before then, and then obtain session? Not sure what that would impact.

For general entity, yes you can use entity.manager service.

For user entity, you can use \Drupal\user\Entity\User. However in your case, you are going to load user by username, this can't be done by User Entity class, you have to use entity.manager.

user_load_by_name will call something like this:

$entity_manager = Drupal::service('entity.manager');
$user = $entity_manager->storage('user')->loadByProperties(array('name' => $nusername));

I will just use this function if there is no reason to replace it.
Use the session_manager service.

$session_manager = Drupal::service('session_manager');
$session_id = $session_manager->getId();


Flag the inappropriate content and not allowing people to add a content? I have added a content type called "share", I have given the user permissions for this content type, meaning he can add the content and he can share to any one..

If any user feels that the content is inappropriate, he can flag the content accordingly.  If a piece of content is flagged 3 times, the content is automatically unpublished.. I have done this using the Rules module...

But here what I want is if a user's content is unpublished as "inappropriate", the next time he should not be able to post any content but he can still access the site.

How can I accomplish this?

I would look into using rules again.

You are going to need a way of identifying users who should not be able to post. Set a rule to apply a flag to the users account once one of their nodes has been flagged 3 times.

Then use this flag in another rule as an IF to only apply it to said user, then maybe either redirect the users who access node/add pages to a page with a custom warning message or try another form of disabling the node creation. Please see below

  Event:
  Content going to be saved / Accessing a page

  Conditions:
  User is flagged with "suspended user"

  Actions:
  Page Redirect
  Show a message on the site

EDIT: Am I correct in assuming you are wanting users to flag a node inappropriate? You should be able to use something like the rule you have already created to do so, just also flag the node author when you flag the content...


How to fix AJAX HTTP request which was terminated abnormally? I keep getting this AJAX error message every time when I add taxonomy terms or open view pages with AJAX, to name a few.

An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /system/ajax
StatusText: error
ResponseText:
ReadyState: 4

Any suggestions to how I can resolve the problem? I'm using the dev desktop.

This issue sounds like yours: Drupal alerts "An AJAX HTTP request terminated abnormally" during normal site operation, confusing site visitors/editors


how can control of number word show in article in frontpage I would like to limit the amount of text that show in frontpage. Is there an easy way to do
this?

in general i do this :-

but in front page show me article as not good like this:-

its bad in style ,,, what can i do

Select your body field within your view.

Click the "Rewrite results" fieldset and check "Trim this field to a maximum length".

Set your maximum length and then check "Trim only on a word boundary".

This will prevent your body text from being cut off.


Assigning entity (node) to group (og) programmatically How to assign an entity to a group programmatically? I have referred to this question however it doesn't seems to work:

$values = array(
    'type' => 'my_type',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
);
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->body->set(array('value' => $form_state['values']['body']));
$ewrapper->save();
$result = og_group('node', $form_state['values']['group_id'], ['entity type' => 'node', 'entity' => $ewrapper, 'state' => OG_STATE_ACTIVE]);
$ewrapper->save();

According to the API documentation, my code was missing an underscore character, and I should pass in the entity. So instead of

$result = og_group('node', $form_state['values']['group_id'], ['entity type' => 'node', 'entity' => $ewrapper, 'state' => OG_STATE_ACTIVE]);

it should be

$result = og_group('node', $form_state['values']['group_id'], ['entity_type' => 'node', 'entity' => $entity->nid, 'state' => OG_STATE_ACTIVE]);


How to migrate users from one website to another website? I created a Drupal Kickstart site and when updating I created another test site. During the updating process my older site has new members and orders how do I transfer the new database tables to reflect the new changes (members and orders) from the older site?

Users Export to export the user from your Kickstart and User Import to your new website.

For the future you should use consider using something similar to Deploy or Configuration Management so you can keep track from your changes.


Taking node map from /map/node and using it on home page I need a google map block which would show all the nodes' location with markers. I noticed that Location module has this built in if I follow /map/node url. My question is, can I somehow take this map block and use it on my home page? Add it through blocks interface or by page components?

Just create an appropriate view, give that view some path that you like, and set that path as your homepage. To actually create such view with the kind of data your question is about,  have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it. That project page also includes various screenshots.


How to add a profile field in page--user.tpl.php I need to put a profile field in page--user.tpl.php.

I try this :

function THEME_preprocess_page(&$variables) {
  global $user;
  $user_fields = user_load($user->uid);
  $variables['myfield'] = '';
  $myfield = $user->field_myfield;
  if($myfield) {
    $variables['myfield'] = $myfield['und'][0]['safe_value'];
  }
}

But i have an error :

Notice : Undefined property: stdClass::$field_myfield dans THEME_preprocess_page()

Do you know where should come the problem ?

try using field_get_items()

$field_myfield = field_get_items('user', $user, 'field_myfield');
$myfield_value = field_view_value('user', $user, 'field_myfield', $field_myfield[0]);
$variables['myfield'] = render($myfield_value);

More info here and here


Is it possible to make a custom facet that behaves like a Views grouped filter? I am moving my user search from vanilla Views to the Search API/Solr backend/Facet API with Views.

On my site, I have a Countries field on the user profile, and I would like to give users the option to choose between two options: from Japan or not from Japan.

In Views, I did this using a grouped filter:

Now I am trying to make a facet that does the same thing.  However, I don't think this is possible from the Facet UI, even with Facet API Bonus installed.  There appears to be no way to provide users with the choice of A or NOT A for a facet that has 100+ values.

How can I implement this A or NOT A search using the Facet API for a specific facet?

Based on this article, I was able to do this with the following code:

/**
 * Implements hook_entity_property_info_alter().
 */
function MYMODULE_entity_property_info_alter(&$info) {
  $info['user']['properties']['agg_nat'] = array(
    'type' => 'text',
    'label' => t('Search API Agg Nationality'),
    'sanitized' => TRUE,
    'getter callback' => 'MYMODULE_search_agg_nat_getter_callback',
  );
}

/*
 * Getter callback for agg nationality property.
 */
function MYMODULE_search_agg_nat_getter_callback($item) {
  // Need to load the user object to get fields
  $account = user_load($item->uid);
  $nationality = $account->field_gen_nationality['und'][0]['iso2'];
  switch ($nationality) {
    case 'JP':
      return 'ja';
    break;
    default:
      return 'en';
    break;
  }
}


Drush crashes Call to undefined function ctype_alnum() in ubuntu I've installed drush on ubuntu 14.04 apparently successfully but attempting to use drush within my drupal 7 app yields this:

PHP Fatal error:  Call to undefined function ctype_alnum() in /home/sam/.phpbrew/php/php-5.4.34/lib/php/drush/includes/command.inc on line 896

OK, I'm still new at PHP but apparently my php 5.4.34 installed via phpbrew is calling it? From reading about this function on PHP I see that it's part of PHP 5.4. That said, it does not show up in my phpinfo() page. Looking around the web the few times I see this as an issue seems an issue with certain modules. My code using the drush installed on OS X shows no problems so perhaps it's not my code?

Ubuntu didn't seem to report errors on install and I'm not sure if I need to install some extension to my php or if there's something wrong with my code. Help me see where I need to fix this? thx, sam

PHPBrew must be disabling ctype by default.

Try explicitly installing the extension with
phpbrew ext install ctype


Passing current node ID to the block template I have a module with a custom block MyCustomBlock.php that get the nid of the current page and pass the value to the block template:

$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->nid->value;
return array(
  'currentnid' => $nid,
);

Inside the template I print the passed value {{ currentnid }}, but it only works cleaning the cache! For example, if I load the page with nid 5 it prints 5, but if I move to page with nid 3 it prints 5. Cleaning the cache and reloading page with nid 3 I get the value 3 printed. I think it is a problem with the template caching system in D8, do you have any idea about this?

The proper way to do this would be use contexts. Plugin contexts, not cache contexts.

Similar to NodeType condition plugin, put something like this in your plugin annotation:

* context_definitions = {
*  "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
* }

And then get the node using $this->getContextValue('node').

This has two advantages:

Your block doesn't rely on global state directly. It could for example be used also in page manager, with a different node.
Drupal automatically understands that your block varies by whatever node is passed in. If using the current node, it will vary by route, if it would e.g. be a node from a static page manager context, it wouldn't. It will also include cache tags, in case the node is changed in a way that would affect your output.


Ajax Form on load Event Is it possible for a Drupal Ajax form to automatically fire a callback when a page is loaded?

I know this is possible using an external JS file and doing it through Drupal behaviors, however I would prefer to be able to do is straight from the Drupal form callback as this allows for less code and more security.

I am trying to do something like this:

$form['mark'] = ['#markup' => '
REPLACE ME
'];
$form['test'] = [
  '#type' => 'textfield',
  '#title' => 'My Title',
  '#ajax' => [
    'callback' => '::callback',
    'event' => 'load',
  ],
];

The load event doesn't work, which makes me think Drupal doesn't want to allow this type of functionality. When I use something like click or mouseout it does work. Is there some type of event here that I can use that will fire this ajax callback when the form loads? Or is it not possible this way?

The load event in jQuery doesn't work with elements without URL. This is not a Drupal issue. You can't use it this way.


html.tpl.php is deleted and the site is down! I'm mid-versed in WordPress, but newbie in Drupal, developing a Theme from scratch. I started with page.tpl.php, then extended the design with a custom front-page (page--front.tpl.php). Then for a custom structure I made html.tpl.php, after heard about it from a Drupal geek. But I found no connection with it to the site and Shift+Delete it. And my site is down now.

To retrieve the site, I copied the page.tpl.php and renamed it to html.tpl.php. But till there is nothing but an alt text of my logo. I even can't get access to the /user, Clearing cache section. But cleared the browser cache with no hope.

Developing environment: WAMP 2.1, localhost

Found a solution. An unconventional solution though!

Step I: I moved my custom theme from sites/all/themes/ to one step up (sites/all/). So the system cannot identify the theme in place. I got access into the Drupal.
Step II: I set "Bartik 7.22" as the Default theme.
Step III: Then moved my theme back to its place again.
Step IV: Renamed the file html.tpl.php to html.tpl.php.BACKUP.
Step V: Then reactivated and set default my theme in the Appearance.

It's live!

  Reason: I think it's the Drupal cache. The process I followed was simply tweaking the caching in an alternative, but unconventional way.


I want to make ajax call to module functuion I want on onclick event send some data to module and do some processing and get result back.

I have module name 'custom' and js code i have mentioned below. Url of page from where ajax call is made is 127.0.0.1/field-work

    Drupal.behaviors.custom = function (context, settings)
 {
    $(document).on('click', '#clear-filter', function() {
    console.log("Hello");
    jQuery.ajax({
            type: 'POST',
            url: 'custom/field-work',
            dataType: 'json',
            success: function(data){
            console.log(data);
           },
        });
    });
};

Module code to receive ajax call have mentioned below.

function custom_menu() {
    $items['custom/field-work'] = array(
    'title' => t('foo AJAX'),
    'type' => MENU_CALLBACK,
    'page callback' => 'details_data',
    'access arguments' => array('access content'),
    );
    return $items;
}

From details_data i am returning some random data. But ajax call is not working. If i am removing drupal behaviour the js part is working fine.

Please help me out.

Please reread the documentation to drupal ajax documentation, particularly how Drupal behaviours do work.

You are missing one crucial part. Drupal calls the attach-function of your behaviour on documentReady or before DOM-elements get injected into the current document. As your JS-code does not have an attach-method, nothing happens. The code below should give you an idea how to fix your problem:

Drupal.behaviors.custom = function (context, settings)
{
  attach: function(context, settings) {
    $(document).on('click', '#clear-filter', function() {
      console.log("Hello");
      jQuery.ajax({
        type: 'POST',
        url: 'custom/field-work',
        dataType: 'json',
        success: function(data){
          console.log(data);
        },
      });
    });
  }
};


How to get custom line item's custom attribute's value after order complete Using this guide I added a custom line item type to my Drupal Commerce installation and have allowed the customer to add extra data when purchasing an item. When the order is complete I need to get hold of that extra data and use it to build some database rows that will grant them access to the service they have just purchased. I have implemented hook_commerce_checkout_complete($order) but I haven't been able to find the data within $order. I know it is there somewhere because I can view the order on the customer's account and have modified the View to show the data next to Unit price, Quantity and Total columns.

You can use the entity_metadata_wrapper on commerce_order

/**
 * Implements hook_commerce_checkout_complete
 */
function package_designer_commerce_checkout_complete($order) {

  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
    if(isset($line_item_wrapper->field_package_configuration)){
      $package_configuration = $line_item_wrapper->field_package_configuration->value();
      // You can also get the raw value like this:
      // $package_configuration = $line_item_wrapper->field_package_configuration->raw();
    }
  }

}


Remove dates from rss can someone help me on how to remove or manually edit the post dates displayed on my drupal feeds? No I am not using views to create it.

Go to your content type you feed and click on "Manage Display". There you have different possibilities to change the way how your content looks in different view modes. You probably need to activate the view mode for RSS Feeds to change anything.


Set different pricing attributes for each product here is the thing:
 On my drupal commerce site I added a term reference field 'sizes' to line item, and make it to be an attribute on 'add to cart' form.
 Also I added a field collection in to my product, wich has two fields: Margin(price) and size(term reference). So when I add some product I can choose a size and some extra margin to price.
 What I want to do is when user add product to cart he chose some size, this size would compare with a size in field collection and the price for this item will update relatively to margin field collection field.
 Anyone have any idea how can I do this?
 Thanks

Thanks, Neograph734, but it's not exectly what I tryed to do.
Maybe it isn't a proper way to do it but I solve this problem using custom _add_to_cart_form_submit() function and hook_commerce_cart_line_item_refresh().
So it looks something like this (maybe it will help someone):

function custom_add_to_cart_form_submit($form, &$form_state){
  // line item field_size_pick
  $line_item = $form_state['line_item'];

  $field_size_pick = field_get_items('commerce_line_item', $line_item, 'field_size_pick');
  $size_pick = $field_size_pick[0]['tid'];

  //get product
  $product_id = $form_state['values']['product_id'];
  $product = commerce_product_load($product_id);

  //fc sizes
  $field_fc_product_sizes = field_get_items('commerce_product', $product, 'field_fc_product_sizes');
  foreach ($field_fc_product_sizes as $key => $value) {
    $item_id = $value['value'];
    $fc_item = field_collection_item_load($item_id);

    $field_fc_size = field_get_items('field_collection_item', $fc_item, 'field_fc_size');
    $size = $field_fc_size[0]['tid'];

    if ($size == $size_pick) {
      $field_fc_margin = field_get_items('field_collection_item', $fc_item, 'field_fc_margin');
      $margin = $field_fc_margin[0]['amount'];
      break;
    }
  }

  if (isset($margin)) {
    $commerce_unit_price = field_get_items('commerce_line_item', $line_item, 'commerce_unit_price');
    $price = $commerce_unit_price[0]['amount'];
    $price += $margin;

    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    $line_item_wrapper->commerce_unit_price->amount->set($price);
    $line_item_wrapper->save();
    commerce_line_item_rebase_unit_price($line_item_wrapper->value());
    commerce_line_item_save($line_item_wrapper->value());
  }

  $form_state['rebuild'] = TRUE;
}

function custom_commerce_cart_line_item_refresh($line_item, $order_wrapper) {

  $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

  $field_size_pick = $line_item_wrapper->field_size_pick->value();
  $size_pick = $field_size_pick[0]->tid;

  $field_fc_product_sizes = $line_item_wrapper->commerce_product->field_fc_product_sizes->value();
  foreach ($field_fc_product_sizes as $key => $fc_item) {
    $field_fc_size = field_get_items('field_collection_item', $fc_item, 'field_fc_size');
    $fc_size = $field_fc_size[0]['tid'];

    if ($size_pick == $fc_size) {
      $field_fc_margin = field_get_items('field_collection_item', $fc_item, 'field_fc_margin');
      $fc_margin = $field_fc_margin[0]['amount'];
      break;
    }
  }

  if (isset($fc_margin)) {
    $price = $line_item_wrapper->commerce_unit_price->amount->value();
    $price += $fc_margin;
    $line_item_wrapper->commerce_unit_price->amount->set($price);
    $line_item_wrapper->save();

    commerce_line_item_rebase_unit_price($line_item_wrapper->value());
    commerce_line_item_save($line_item_wrapper->value());
  }
  $order_wrapper->save();
}


problem with [$node->language][0] I have a problem with this code in node.tpl.php

<?php if (isset($node->field_image[$node->language][0])): ?>

    <a href="<?php print $node_url ?>" title="<?php print $node->field_image[$node->language][0]['title'] ?>">
      <?php print theme(
        'image_style',
        array(
          'style_name' => 'teaser',
          'path' => $node->field_image[$node->language][0]['uri'],
          'alt' => $node->field_image[$node->language][0]['alt'],
          'title' => $node->field_image[$node->language][0]['title'],
          'attributes' => array(),
          'getsize' => false
        )
      );?>

<?php endif; ?>

I know above code work if language natural, but my website is bilingual.
How can i solve this problem.

You shouldn't be accessing the data directly. You should use field_get_items() instead. I also use a foreach below, as that makes your code more generally applicable. Limiting to a single image should happen at the field layer, not theme. If you really want to, you could $image = reset($images).

$images = field_get_items('node', $node, 'field_image');
foreach ($images as $image) {
  $image_render = theme('image_style', array(
    'style_name' => 'teaser',
    'path' => $image['uri'],
    'alt' => $image['alt'],
    'title' => $image['title'],
    'attributes' => array(),
    'getsize' => false)
  );

  $link = l($image_render, $node_url, array('title' => $image['title'], 'html' => TRUE));
  print '
' . $link . '
';
}


Display user register form in template? I'm working on a design heavy site and one of the sections created via the Paragraphs module requires to display the user_register form.

I'm currently doing this in the paragraphs-item--myparagraph.tpl.php file with the following code:

<?php
  $form = drupal_get_form('user_register_form');
  print drupal_render($form);
?>

This works for showing the form but the problem is that if there are form validation errors, they don't show. I have read that the issue is rendering the form too late but I can't see how I adapt this to Paragraph entities. I have tried using mytheme_preprocess_entity to pass the form in but I can't render it?

I ran into something similar recently, and I opted for the Block Reference module.

I created a new paragraph called Block Reference
Added a block reference field
Selected "system blocks" as being referable under the field settings
Selected the user login block

and wham bam thank you mam ive got a user login block in a paragraph.


So I've installed FirebugForDrupal (updated) I installed the browser plug in and module in drupal. On this (development environment) I gave authenticated users access to the 'Access Firebug Debug' permission. Site Admin has access to that and 'Execute Firebug PHP'.

Browser/Client

Firefox 17.0.1
Ubuntu 11.10
Firebug 1.11.0
DrupalForFirebug 0.0.8 2.0
Logged in as User 1

Server (development box)

Drupal 6.25
Redhat 5.8
PHP 5.3.3

UPDATE:

Just this morning DfFB released it's 2.0 version. I spun up the DfFB module again, ran cron, and cleared cache. In the source code of my page, I can now see <div>'s  with class names such as drupalforfirebug_general and drupalforfirebug_sql. So it appears that information is binging handed to the browser from Drupal.

UPDATE 2:

I switched to DfFB 2.0a and this what I see.

Is this what I'm supposed to see?

It seems the extension is not compatible with Firefox 14. The issue report has been opened on July 19, 2012, and it still is open.

The last comments from one of the co-maintainers of the module say:

  unfourtunatly no, currently the new (from the ground up) plugin registers itself with firebug and firefox; it displays the drupal tabs and subtabs. But it doesn't gather the data from the drupalforfirebug drupal module yet.

  Once it is ready I will package it as an xpi and allow it to be downloaded from bitbucket while mozilla reviews the update. I should be done sometime this week.

  So now the code on bitbucket is functional. I wouldn't call it testable -- still hanging around pre-alpha.

  Before I we call it testable I need to do two things.

  Further abstract the connection between the Drupal Module and the Firefox Module. Right now the presentation layer calls the connector that returns the content directly. However, once I abstract that connection to an API call layer then changes to the API will be less problematic for Firefox plugin to deal with.
  Remove the dependency on jQuery for the plugin. Currently the plugin loads jQuery to deal with a couple of UI niceties.<-- this is what is blocking the release.

  By all means though, If you know how to install from code a firefox plugin then please do so. It works just like the old one for the time being.


Form in controller does not render as usual In Drupal 8.4.3, I tried to render a form inside a controller's method, but it does not render as usual.

The value of #default_value is not taken into account
Fields have no name attribute (which causes them not to be sent)

This is the smallest code I've been able to write to reproduce the issue.

public function list()
{
  $render = array(
    '#type' => 'form',
    'search' => array(
      '#type' => 'textfield',
      '#title' => 'Search',
      '#default_value' => 'Lorem ipsum'
    ),
    'actions' => array(
      '#type' => 'actions',
      'submit' => array(
        '#type' => 'submit',
        '#value' => 'Apply'
      )
    )
  );

  return $render;
}

The rendered markup is the following.

<form method="post" accept-charset="UTF-8">

    Search

    <input type="text" size="60" maxlength="128" class="form-text">

  <input type="submit" name="op" value="Apply" class="button js-form-submit form-submit">
</form>

The sent data is the following. Obviously, the search field is not sent as it does not have a name.

op=Apply

I can overcome the missing name attribute with a #name key, but I cannot understand why it is needed here, but no where else.

This is the most basic route/controller pattern.

What could interfere in my context?

It's not possible to use form elements in a controller directly, only render elements. You find a complete list of both types here: https://api.drupal.org/api/drupal/elements/8.4.x

To use form elements in a page controller you need a form route:

example.routing.yml:

example.form:
  path: '/example-form'
  defaults:
    _title: 'Example form'
    _form: '\Drupal\example\Form\ExampleForm'
  requirements:
    _permission: 'access content'

And then build the class ExampleForm by extending FormBase. See https://www.drupal.org/docs/8/api/form-api/introduction-to-form-api

This is the most basic route-controller pattern for forms.


Basic Multiple Image Upload to replace standard image uploader First question on Drupal Answers, hi everyone.
Starting off with a very basic question actually:

While the standard single image at a time uploader is swell and all, I've got the Galleria module installed, and we have hundreds of photos to upload across multiple albums, and a ton more to come along in The near future. Quite simply is there an existing package/mod that can transform that single image uploader into a multiple image uploader, One where you can select multiple images in the browse window?

The best multiple image uploader that I have found is http://drupal.org/project/plupload (example widget is on their website)

Also if you are working with images and are using drupal 7, you may also wish to check out http://drupal.org/project/media - this modules is looking more and more promising, and now has views integration as well. It also works with the above recommended plupload module)


commerce unique identification number for each item on each transaction What options are they to achieve a unique identification number for each item sold in a commerce store.

I want to have a unique number for each item on each transaction, the number needs to be unique across all transactions.

even if I have 5 of the same line item in an order I should still get 5 unique numbers.

I have a unique id number per item per order but i don't know how to achieve a truly unique id.
Would appreciate any guidance.

prepend your unique id with the order number. Since it's already unique within the order, and presuming an order number is unique, [order-number]-[unique-id] should return a truly unique value with the added benefit of being traceable since the order number would have a searchable or reference-able value.

EDIT:

Further research yielded the module Field default token

This module enables to use tokens as field default values.

Using this you should be able to create the order-ID combination (or any other combination). To prevent user tinkering, I would also suggest Field Permissions:

The Field Permissions module allows site administrators to set field-level permissions
to edit, view and create fields on any entity.


How can I edit Custom Form API? I have created the Custom registration form module using the form API as per the requirements. I have also inserted the records in the database using form alter functions. Now I need to create an edit registration form  for the logged users.

My suggestion on this is:

Create edit_reg form module with form controls
Retrieve the records of logged users
Pass the values to defalut value of form controls

Is the above method good? May you suggest me any other method to edit the form API?

I am using Drupal 7.

Why not use the existing user edit form, and use hook_form_alter() to add your fields. That way, you get all the built in functionality, such as password changing etc.

It would also make sense to make the user registration alterations the same way, instead of creating your own flow, unless it for some other reason makes sense to do it that way.


User points category = taxonomy term Im using user points (module) to reward users whenever they create content on my site. Now, I`d like to start rewarding thise points within categories (Points categories).

The categories I want in my points system are to be the terms that is available in a specific vocabulary on my site.

Exampple:
User X creates a "node Y" and classifies it with "term A". In this case Id like to award user x 5 points in the "term A" category.

Anyone know how to do this?

Thanks,

Ditch user points and download and install Rules instead.

Make sure you enable Rules UI.

Go to user fields and add a field of type Integer. Example: Lets name it Term A Points.

React on: (under node) After saving new content

Restrict by type: None

Add condition >> (under node) Content is of type >> select your content type (If you want multiple, hold the Ctrl button on your keyboard to highlight the content types you want)

Lets assume your term reference field is called hello world

Add Condition >> Data Comparison >> node:field-hello-world >> (type the term name here)

Add Action >> Set a Data Value >> node:author:field-term-a-points >> (click on switch to data selection) >> Data Selector: node:author:field-term-a-points >> Click on OFFSET and put the points you want to award, ex: 5

You can then use the Field Permissions module if you want to hide the Term A Points field from users so they cant see it and/or edit it.

Then you can create another rule when Content is deleted, do the same except OFFSET -5

If you want to diplay a message:

Add Action >> (under system) Display a message on the site >> Type your message here. Ex: [user:name] you have been awarded 5 points.


Get a sortable link in Views table display I have an content type (bundle) "Journal" that has a field "journal number" (integer field) and an entity reference to "Document" bundle. I have a view that lists"document" objects as a table. I want to add there a number of journal referencing to the "Journal" item. It can be done via Relations in Views. But then I want to see this number as a link to corresponding journal. I see two ways there:

.1. that number is shown as a link via "override" option of the field with hardcoded url. (I use pathauto with custom patterns which means that I'm to monitor that hardcoded with "override patterns" urls to be correspondent to their actual urls provided by pathauto)

Pros: the field is sortable as an integer (I want it to be that).

Cons: if Pathauto patterns change, the views overide patterns should be changes correspondingly by hand.

.2. Add a field "Link" referencing to that journal and override this field with a journal number field.

Pros: linking system works without any crutches: Pathauto pattern changes -> link to journal will still work.

Cons: The overriden property is NOT SORTABLE

How can i get both beiing a link and sortable ability as a number for a field?

You should use the first option, but with a slight alteration. If you use the base url when you create a link using override - views will render the link using the Drupal APIs and the the link will use any path alias created.

So all you have to do is to create the link like: node/[nid], instead of doing content/[title]. These urls are examples.