How to display a table view and an add/edit form on the same page?

Hey Erin, certainly a good way to build customized pages is use Context module instead of Panels... (Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context. Link: Context).

In addition of that, you can create a block (be sure to have PHP Filter enabled), and include the following code.

For a existing node edit form:

//you should have your nid (May be loaded by a custom arg or even a given GET variable)
$nid = 99;
$node = node_load($nid);
//load needed file from node module
module_load_include('inc','node','node.pages');
//load node edit form
$form = drupal_get_form($new_node->type . '_node_form', $node);
//print the form you have loaded
echo($form);

In case you want to load a fresh node add form, instead of loading a node with node_load, you should create a stdClass object, and give the type name just as bellow:

//load the current user info
global $user;
//empty object for node
$new_node = new stdClass();
// your machine name content type
$node->type = 'page';
// set the author for the node to be created
$node->name=  $user->name;
//load needed file from node module
module_load_include('inc','node','node.pages');
//load node edit form
$form = drupal_get_form($node->type . '_node_form', $node);
//print the form you have loaded
echo($form);

Actually it may not be the best way to do that, but certainly is a functional method.


Possible explanation for error and site crashing randomly without any provocation?

Make sure the i18n_menu module is enabled,

e.g:

drush en -y i18n_menu

i18n_menu has i18n_menu_install to add that language field to the menu_links table on install, and an i18n_menu_uninstall to drop it on uninstall.


how to save a field created by using hooks in database

first create submit button

$form['submit_button'] = array(
                '#type' => 'submit',
                '#value' => t('Click Here!'),
                );

when you create submit it calls this function and feilds submitted or updated to your database

function form_try_form_submit($form, &$form_state)
            {
                echo '<pre>';
                var_dump($form_state['values']);
                echo '</pre>';
                $insert=db_insert('DB')
                ->fields
                (
                    array
                    (
                        'phone' => $form_state['values']['phone']
                                 )
                 )
            }


Does requiring core/drupal load jQuery in custom script files?

No, core/drupal depends only from core/drupalSettings; using it will not load core/jquery. The definition of those libraries is contained in core.libraries.yml, where  you can see their dependencies.

drupal:
  version: VERSION
  js:
    misc/drupal.js: { weight: -18 }
    misc/drupal.init.js: { weight: -17 }
  dependencies:
    - core/drupalSettings
  drupalSettings:
    suppressDeprecationErrors: true

drupalSettings:
  version: VERSION
  js:
    # Need to specify a negative weight like drupal.js until
    # https://www.drupal.org/node/1945262 is resolved.
    misc/drupalSettingsLoader.js: { weight: -18 }
  drupalSettings:
    # These placeholder values will be set by system_js_settings_alter().
    path:
      baseUrl: null
      scriptPath: null
      pathPrefix: null
      currentPath: null
      currentPathIsAdmin: null
      isFront: null
      currentLanguage: null
    pluralDelimiter: null


Title's will not show translated version (multilingual site) in View list

I've found it myself.

when using fields, instead of adding content:title as a field, use entity translation:title. This will show the same field as your title but the translated version.


only allow to upload profile pictures of a certain size

You need to form alter user_account_form().  Remove user_validate_picture() as the validator.  Duplicate that function into your own module, and add as a validator.  Inside that, update the size line to be:

'file_validate_image_resolution' => array('160x160', '160x160'),

This should enforce the same value for both minimum and maximum size before the file gets saved off.  I don't think you can add a second validator; I think the size check needs to be done in one step.


Configuration form and submission handler

There are the following errors in that code:

You call parent::submitForm($form, $form_state) inside the foreach() loop, when it should be called once, outside the loop
You keep setting element, which means you are only saving a single value
Your code is still accessing the FormStateInterface object as an array, as it was done in Drupal 7

I cannot comment about the \Drupal::state()->get('cleanupeditform_formkeys') part, except that I would probably inject the service as dependency, but I would rather use the following code.

public function submitForm(array &$form, FormStateInterface $form_state) {
  foreach ((\Drupal::state()->get('cleanupeditform_formkeys') ?: []) as $key => $value ) {
    $this->config('cleanupeditform.admin_settings')
      ->set(CLEANUPEDITFORM_HIDEPREFIX . $key, $form_state->getValue(CLEANUPEDITFORM_HIDEPREFIX . $key))
      ->set(CLEANUPEDITFORM_ALLOWPREFIX . $key, $form_state->getValue(CLEANUPEDITFORM_ALLOWPREFIX . $key))
      ->save();
  }
  parent::submitForm($form, $form_state);
}


Views Escaping Special Characters in URL

With the Pathauto module you can strip the special Chars. Here is a quote about it (from the module's project page):

  ... automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.


query to fetch all path aliases's content type and title

Can you try:

$connection = \Drupal::database();
$query = $connection->select('node_field_data', 'n');
$query->leftJoin('url_alias', 'u', 'n.nid = u.source');
$result = $query->fields('n', ['changed', 'nid', 'type']);
$result->addField('u', ['alias']);

$result->execute();

foreach ($result as $rows) {
  $totalRows[] = $rows;
}

I saw two main problems.

1) Basically you had a mistake that was causing runtime error:

$query->join('url_alias', 'u', '/node/n.nid = u.source');

2) Using join, where for this you need left join.

Different types of joins:
https://stackoverflow.com/questions/5706437/whats-the-difference-between-inner-join-left-join-right-join-and-full-join

Tip: Before running $result->execute(), you can run $string = $result->__toString().
This will give you the produced raw SQL. You can use it in a tool like adminer/phpmyadmin to debug in more detail.

Best regards,
Oleg


Override drupal form output. Place two input fields side by side

You can groupe the two fields into a field group. This gives HTML code wrapped around the fields. Just change the CSS settings of this HTML to your needs.


How to check "Show as expanded" by default on the Add menu item page

To set a default value for the menu link entity use hook_ENTITY_TYPE_create:

use Drupal\menu_link_content\MenuLinkContentInterface;

/**
 * Implements hook_ENTITY_TYPE_create() for menu_link_content.
 */
function mymodule_menu_link_content_create(MenuLinkContentInterface $menu_link_content) {
  $menu_link_content->expanded->value = 1;
}


Troubles with adding video provider to Video Embed Field module

I've found solution, it's simple.

You need to go in the field settings of this field and find a checkboxes   with all video providers. Mark Wistia or any new provider here and it will work.


Use Views module and make a content view in relation with Content authored.


Not as such, but you can just implement your own version of that alter hook to make the changes you need to, and make sure your implementation runs later on.

To do that you'll need to implement hook_module_implements_alter():

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Push your module's implementations of hook_form_alter(), and derivatives,
    // to last in the list. This will make it run after menu_form_node_type_form_alter()
    // so you can alter whatever you need to.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

function MYMODULE_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  // Make changes as usual
}


It looks like this could be a known issue. Please see the below two issues for the taxonomy_menu project - the second contains a patch you could try?

http://drupal.org/node/1208484

http://drupal.org/node/1485198


You will need some css to do this task. Pick a class from view content html and fix its height and set overflow-y property to scroll. Example snippet below -

.view-content{
    height: 50px;
    overflow-y: auto;
}


I found out that sourceMigration() doesn't allow multiple data source data rows (but please correct me if I'm wrong). So, I made a custom query in my prepareRow() that somehow works like sourceMigration. Here's what I did:

// group concat code
$query->addExpression('GROUP_CONCAT(file.field_file_fid)', 'file_id');

// in field mapping
$this->addFieldMapping('commerce_file', 'file_id');
$this->addFieldMapping('commerce_file:file_class')
      ->defaultValue('MigrateFileFid');

// in prepareRow()
public function prepareRow($row) {
  if (parent::prepareRow($row) === FALSE) {
    return FALSE;
  }

  // get the values of the file_id where you used group concat function
  $product_id1 = explode(",", $row->file_id); //convert csv to array
  $product_id1 = array_values($product_id1); //redeclare it to clear its index / optional
  $newsIds = array(); //array where the ids will be stored

  foreach ($product_id1 as $i) { //loop through array
      $getEquivalentId = db_select('migrate_map_privatefile', 'p') //'migrate_map_privatefile' is the migrate map table where the ids of the files are stored
              ->fields('p', array('destid1'))
              ->condition('p.sourceid1', $i);
      $resultOfId = $getEquivalentId->execute();
      foreach ($resultOfId as $id) {
        $newsIds[] = $id->destid1; //store result to $newsIds
      }

    }

    $row->file_id = $newsIds; //the values of file_id will now be $newsIds

  }

Hope this would help someone, someday.
Cheers!


Why aren't the main menu and the secondary menu simply regions?

So after much research I found that the main menu and secondary menu settings are there for historical reasons. They had proper functionality in Drupal 5 but its usefulness has declined over the release of newer version ( 6 and 7 ) to the point where modern themes ignore them completely in favor of the powerful regions concept.

The included themes ( as others have mentioned ) have these special "regions" still just because no one cares to remove them.

The original idea was to have an easy way to present sub menu links ( secondary menu ) dependent on the what you select in the main menu.

The modern approach is to have a pop-out sub menu ( like Superfish ) this has made the secondary menu feature obsolete.

So much so in fact, that the functionality is broken and no one fixes it.

In summary, the feature is broken and obsolete. I hope someone removes it from Drupal 8.


Programmatically changing theme after hook_custom_theme

Both hook_custom_theme() and hook_init() are invoked from _drupal_bootstrap_full(), which contains the following code.

menu_set_custom_theme();   // It invokes hook_custom_theme().
drupal_theme_initialize();
module_invoke_all('init');

The reason of the order is explained in the comment before that code, which says:

  Prior to invoking hook_init(), initialize the theme (potentially a custom one for this page), so that:

  Modules with hook_init() implementations that call theme() or theme_get_registry() don't initialize the incorrect theme.
  The theme can have hook_*_alter() implementations affect page building (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()), ahead of when rendering starts.

It seems that your situation is a circular-reference situation, where an implementation of hook_custom_theme() depends from hook_init(), and an implementation of hook_init() could depend from the value returned from hook_custom_theme().

If you are sure that the result of hook_custom_theme() doesn't influence the code of spaces_init(), which doesn't need the theme to be initialized, then you could invoke spaces_init() in your hook_custom_theme() using module_invoke('spaces', 'init'), but that sounds like a hack, and subject of problems if spaces_init() is changed, and it actually needs a theme to be initialized before being executed.


This solved it for me.

The documentation at this link was missing a mention that you need to use the class prefix - I just submitted an update to the Drupal Docs to make it more clear:

$this->addFieldMapping('preserve_files')
  ->defaultValue(1);

$this->addFieldMapping('file_replace')
  ->defaultValue(MigrateFile::FILE_EXISTS_REUSE);


Apache Solr form alter add custom fields in search form

You need to add facetsapi module and in form alter add the custom fields. On form submit you need to use

$keys = $form_state->getValue('keys');
$custom = $form_state->getValue('user_custom_field');
$form_state->setRedirectUrl(Url::fromRoute('search_api_page.en' . '.' . $form_state->getValue('search_api_page'), array('keys' => $keys), array('query' => array('facet_key' => $custom))));


Ordering results for form autocomplete fields

I would think its the query that handles the ordering. You can alter the query that fetches the results for the autocomplete field. Find the query in the module code and it should have a tag associated with it. You can then alter the query by implementing hook_query_TAG_alter

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_query_TAG_alter/7

This will allow you to change the orderby for the query

EDIT: Looking at the masquerade module I don't think it adds tags to the queries which means you cant mess with the ordering.


How do you populate existing entities with the default value for a newly added field?

I just found this module: https://www.drupal.org/project/field_defaults

It seems like it might work. But I'll withhold accepting this as the answer unless there are better ideas out there.


What you are doing, sorry, is plain wrong. There is a field API and you should use it instead of messing around with the SQL tables. If you are going around the field API and it breaks, you truly get to keep both parts. I find it astonishing you expect support for going around such a complex API.


On a development site I would suggest uncommenting the following lines in the settings.php file.     emacs sites/default/settings.php

if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

and then copying the file example.settings.local.php from /sites folder to /sites/default folder and rename it to settings.local.php

cp sites/example.settings.local.php sites/default/settings.local.php

In addition to adding the following setting

$config['system.logging']['error_level'] = 'verbose';

it also adds a few other settings which will help you in debugging and making development easier. If you don't want any of them in particular, you can always comment them out.

Note : If you think adding a file_exists call to each page will slow down the site, you can always remove it in the production code.


I found my answer and post it here so maybe it helps others later.

First, in MYTHEME.theme:

In Drupal 8.2 language got added to page the variables in template_preprocess_page. But in my current version 8.1 it didn't exist so I added it with:

function MYTHEME_preprocess_page(&$vars) {

  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $vars['language'] = $language;
}

Then in my Twig file I use {{ language }}. Also I can get the language name with {{ language.getName() }}.

Update

After Drupal 8.2  a global variable language exists and now there's no more need to add it first.

{% if language.getId() == 'en' %}
  Do something
{% else %}
  Do something else
{% endif %}

Update
Thanks @Lucas for his comment

on Drupal > 8.7.5

{% if language.getId() == 'en' %} should be {% if language == 'en' %}


There is D7 patch if you're savvy enough with that. I wouldn't bother with it unless you anticipate reseting frequently. An easier fix is to just truncate all the tables that store the data:

db_query('TRUNCATE {userpoints}');
db_query('TRUNCATE {userpoints_txn}');
db_query('TRUNCATE {userpoints_total}');


How to add a views block in a basic page via editor?

Have you tried to use the simplest php-code inside your body field ?
For example,

<?php print 'The simplest text'; ?>

It can be situation, where filter for content of your field is configured wrongly.

Moreover, it would be nice to try names of the view and view mode.


Include email attachment in new content Rule

If anyone else is struggling with this problem (and, I did find quite a few that were), I've found a work around.  First, it appears like this may be a known bug.  Given that, I found the work around at #25 worked for me.  In my case, I had to tweak the attachments value in the rule to look like this...

[node:field-file-attachments:file:path]

Note: no preceding path was required.  With the above, I now get attachments in emails that are generated via a rule.


Image style in views field template on image

Try something like this :

<img src="<?php print image_style_url('product_overzicht', $img_url);?>">

Where $img_url should be uri, which in your case can be : public://products/img_filename.jpg


I've Featured some Paragraph Bundles, but they are not showing up on the remote site

You might try manually creating the paragraph bundle and see if the fields pop in once the bundle is made, or once the bundle is made and the feature is reverted.

Might be that the features integration for paragraphs in D7 is still iffy.


Block level configuration not available in reaction part of context

In your original context that adds the block you can negate a path by using a Tilde along with your path (in the context condition).

e.g. ~your-path


How can I have a nested slideshow with paragraphs and views?

You could achieve this with more control by overriding node/field/paragraph templates in your theme to get the required markup, then creates the Slick sliders via custom JS code.

If you never worked with templates, you should start here https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates


I think preprocess_node should do the trick

use that in your template.php

function template_preprocess_node(&$vars){
  //Supposing that your content type name is "group"
  if($vars['type'] == 'your type'){
    $vars['content']['your_field']['#title'] = '';
  }
}


User error: "1" is an invalid render array key in Drupal\Core\Render\Element::children()

Remove the brackets after the ['your_variable'] part as your variable holds only 1 array:

function MYTHEME_preprocess_views_view_fields(&$vars) {
   $tempstore = \Drupal::service('user.private_tempstore')->get('evenementrimouski');
   $some_data = $tempstore->get('nid');
   $vars['your_variable'] = [3,4,5,6];
}

Also use the short array syntax. It's part of the new coding standards: https://www.drupal.org/node/2135291


I think you could create a view for that, and select which fields to show.


This is more like a Javascript question, no i don't think you will find that kind of module.

You can always write your own Javascript/jQuery slideToggle() behavior (my suggestion) in a .js file in your theme, control any DOM element (like a block title) and assign this behavior to it.


Secure Way of sending argument from one page to another

You can symmetrically encrypt the data into a cipher before sending it, and decrypt it at the receiving page.  This will not stop anyone from seeing the encrypted data, but they will not have access to the encryption key and will therefore not be able to understand the data.

If the data to passed is short, the encrypted data can be passed in the URL.  To use an URL, just base-64 encode the resulting cipher so it can be represented by a string (and base-64 decode it at the receiving end to get back the cipher).  Remember to decrypt to convert from the cipher to the original cleartext.

If the data is too bulky to fit in an URL, you may use a session variable to transfer the cipher.  Then you can skip the base-64 encode/decode step.  A session variable is not secure. However, just as with the URL, encryption will keep the data confidential.

Or, you can simply use pass the data using the database.  This requires you to create a very small custom module that associates the data with a token that does not give away any information (e.g. an integer).  You then pass the token by means of the URL, e.g.:

http://XXXX/someURL?tokenid=15

The receiving page then use this token to look up the data in the database.


SMTP module - "Unable to send e-mail..." and "A test e-mail has been sent..."

It looks like the sendmail service is not installed.

Try the command sudo apt-get install sendmail via ssh to install it.


drupal 7 xml sitemap showing nodes that are unpublished

solution - turn off the individual node. with the xmlsitemap node module enabled.  at the bottom of the content page when you are editing you can choose Inclusion: Excluded.


How do I create a user relationship to show author name in Views?

In Drupal 6 you don't need a relationship for the author name of a node, it is directly available in the fields' list.


If your view is set up with a Contextual Filter for language, this should work:

print views_embed_view($viewname, $display_id, $languagecode);


In a group content add form, the og_group_ref is empty, except for the "_none" value

It turns out that organic groups permissions were inadvertently changed, causing the issue, and attempts to fixed this made it only worse. Permissions have been restored, and the system now works as expected.


How do I use contextual filters and relationships to show related articles?

I have implemented the same in one project in Drupal 7 to display products of same catalog.

You can create a views of article content and can create a contextual filters for tags. It will display all the article of that tags.

You can follow below step:

Add a contextual filter of tags. Checked radio button "Provide default
value".
Select "Taxonomy term Id from url" in the type drop down.
Checked "Load default filter from node page" check box.
Checked "Limit terms by vocabulary" check box.
In the Vocabularies section, checked the check box of Vocabularies
(tags) which you want to add filter in the views.
Under the more section, checked "Allow multiple values" check box, so
multiple tags can use filter the term.

You can find below image for reference.

You also need to add contextual filter of node id and follow below step, so current node page will not display in related views section.

Add content: Nid contextual filter in the views.
Checked "Provide default value" radio button and select "Content id
from url" in the type drop down.
Under the more section in contextual filter, checked "Exclude" check
box.


What is the equivalent of hook_menu_alter() to change a menu item type?

Drupal 8 has a new menu system, there is no hook_menu and no hook_menu_alter anymore.

If you want to alter an existing route, it is a little bit more complicated in comparison to Drupal 7.

In your module you have to create a class file at YOURMODULE/src/Routing/CLASSNAME.php that extends RouteSubscriberBase:

/**
 * @file
 * Contains \Drupal\YOURMODULE\Routing\RouteSubscriber.
 */

namespace Drupal\YOURMODULE\Routing;

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

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Get the route you want to alter
    $route = $collection->get('system.admin_content');

    // alter the route...
  }
}

You can take the RouteSubsciber class of the node module as an example.

To let your RouteSubscriber be recognized you also have to create a YOURMODULE.services.yml file in the root of your modules directory:

services:
  node.route_subscriber:
    class: Drupal\YOURMODULE\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

To get a better insight to the new menu system I would recommend the following articles:

D7 to D8 upgrade tutorial: Convert hook_menu() and hook_menu_alter() to Drupal 8 APIs
What Happened to Hook_Menu in Drupal 8?

Edit:
As mentioned by Berdir, the menu system has a different structure now, which has nothing to do with D7's menu system, so there is no such thing as a menu type anymore.


Display the taxonomy term name in the page.tpl from a node

I would use an entity metadata wrapper for this:

// Load the current active language.
global $language;
// Put the node object in a wrapper.
$wrapper = entity_metadata_wrapper('node', $node);
// Get the term object.
$term = $wrapper->language($language)->field_term_ref_1->value();
// Translate the term.
$translated_term = i18n_taxonomy_term_get_translation($term, $language);
// Pass the term name to page.tpl.
$variables['term1'] = $translated_term->name;

// The same for term 2.

// Now you can print them in your page.tpl.
print $term1;

Not sure if the language part works, though.


Hook function for admin/structure/taxonomy/your_vocaburary form (Save and Reset to alphabetical)

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
    }
}


Exposed Filter of Child Terms on Parent Page

You can create a separate Views of type Taxonomy term (not content!) display Block that is showing taxonomy term names, add the Relationship to the parent term and require it, and a Contextual filter to taxonomy term ID using that relationship.

Test it by entering parent term ID into Preview, you should see the parent's children.

Edit the Format to set the fields to display inline, or use CSS (later) to make them appear horizontally.

Then in your Content (original) Taxonomy Term views add View area into Header and choose the above Block with Inherit contextual filters option ticked.


multisite: only changing name of the website

Do you have a settings.php file per site ?

If yes, you can add inside $conf['site_title'] = 'My Site name' this variable his stocked in the table variablebut you can override it directly with settings.php.


Facebook Autopost. Why I still receive download library message?

Please make sure that the facebook.php file is found at sites/all/libraries/facebook-php-sdk/src/facebook.php.


user_authenticate() function not working

user_authenticate($name, $pass) (Drupal 7) will return the user ID on successful authentication, or FALSE on failure. In Drupal 6, it will return the user info array.


The default is 30 days, per the NODE_NEW_LIMIT constant.

Nodes changed before this time are always marked as read.
Nodes changed after this time may be marked new, updated, or read, depending on their state for the current user. Defaults to 30 days ago.

Since use of that constant is hard-coded in node_mark(), I imagine you'll need to provide your own 'marking' system if you want to do things differently to the core version.


How to bypass node_access when using EntityFieldQuery?

Drupal 7.15 allows you to bypass the access on the node.

See DANGEROUS_ACCESS_CHECK_OPT_OUT query tag added to EntityFieldQuery for more information.

  A "DANGEROUS_ACCESS_CHECK_OPT_OUT" query tag has been added to EntityFieldQuery to allow bypassing access checks. Previously, queries executed through EntityFieldQuery would always be altered by the node access system, potentially causing unexpected behaviour and data loss.

  If you need to bypass access checks in an internal query within your module's API, you may add this tag, but you should only do so if it is necessary. If this query tag is added to a query whose results will be displayed to the user, it will bypass all access checks, potentially exposing sensitive information.

function MYMODULE_field_query($field) {
  $query = new EntityFieldQuery();
  return $query
    ->fieldCondition($field)
    ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
    ->execute();
}


How to popup a dialog when a checkbox is unchecked on webform?

$('#checkbox-id').click(function(){
  if(!$(this).is(':checked')){
    alert('You unchecked the checkbox');
  }
});


Recommended techniques for changing the appearance/design of my Bootstrap sub-theme?

Since you're using Bootstrap as a style framework already, I'd recommend you simply restyle the navbar to look like Bartik. You'll have to modify your page.tpl.php template to move the various elements of the header around to put the site title and user menu on top of the main menu.


As per my understanding of your question you should follow below steps:

Create a form using Webform and then in Webform >> Advance settings mark that webform as "Available as block".
Now you can see that webform as a block in Blocks page.
In block configuration you can set the option to display that block on specific page.

Let me know when you implement it.


Modify instead of add a class in classes_array for theming purposes

Search for the key of the value you want to replace and then modify it. It's that simple.

function paddle_admin_preprocess_menu_block_wrapper(&$variables) {
  if ($variables['delta'] === 'management_level_2') {
    // Search for the key
    $key = array_search('class_to_be_replaced', $variables['classes_array']);

    // If class was found, replace it
    if ($key !== FALSE) {
        $variables['classes_array'][$key] = 'class_that_replaces';
    }
  }
}


Using Views to Display Taxonomy Terms Along with a single image field of the latest content type that has that taxonomy term

Apparently there's a module called Views distinct that would eliminate duplicate entries due to having one field having the same values.


function MyModuleName_form_alter(&$form, &$form_state, $form_id)
{
   if ($form_id == 'search_form_id') {
     $form['#submit'][] = 'MyModuleName_custom_serch_form_submit';
   }
}

function MyModuleName_custom_serch_form_submit($form, &$form_state)
{
  if(isset($_GET['q']) && !empty($_GET['q']))
  {
     $string_serch= $_GET['q'];
    drupal_goto("http://yourdomain.com/search?q=".$string_serch);
  }
}


Can't disable module when it defines an field type used by a custom entity

So as Clive suggested I solved this by creating a helper module called emtr_fields.

The emtr_fields module creates the entity and has the field schema.

Then the main emtr module creates the field and it's instance.

To remove all of this again first the emtr module has to be disable AND uninstalled (it has to be uninstalled as the field and it's instance is deleted in hook_uninstall), and then the emtr_field module can be disabled and uninstalled.

I also found some documentation on this on drupal.org here:

Module cannot be disabled because Drupal claim "Field type(s) in use"

Moving field(s) definitions into a separate module of a installed module.

Field types should be defined by one module and implemented by a separate module.


I found the problem.

The problem was an option on the advagg module that move all JS to the footer (which is usually a good thing).

The "All" option was problematic.
when I chose "Disabled" - the views UI worked correctly.

here is a screen-shot:


How to hide breadcumbs on the front page?

Assuming you are using D7.  There are a number ways to achieve it. I am providing three methods here.

Contributed module.
The easiest one is to use "Disable Breadcrumbs" module.

Theme Overide.
If you think it is overkill, don't want to use that module, you can also implement the preprocess html hook to remove breadcrumb like this:

/**
 * Implements template_preprocess_html()
 */
function THEMENAME_preprocess_html(&$variables) {
  if ($variables['is_front']) {
    // kill breadcrumb, set to empty array
    drupal_set_breadcrumb(array());
  }
}

Custom Module. You can also done this in your custom module by implementing hook_page_alter

/**
 * Implements hook_page_alter().
 */
function MODULENAME_page_alter(&$page) {
  if (in_array('front', $page['#theme_wrappers'])) {
    // kill breadcrumb, set to empty array
    drupal_set_breadcrumb(array());
  }
}


Display output from custom module in a panel

I would recommend using hook_block_info() and hook_block_view() to expose your custom content in a block. This gives you Panels support + contextual links should the need for a form arise, and you can set caching settings for the block.


Great to know you're exploring Drupal! :D

Create a new content-type "job", add a title, description and pay -
all text fields.

Since you want to ask data from users or something like a survey, Geek Alvaro J Hurtado V is right. The Entityform module is the way do go since it uses entities and fields which are future proof and used in Drupal 8.
Brings me to another module called Views, Entityform works well together with the Views module. This module helps to create data lists without any coding needed. This is one of the most used module in the Drupal world. Check it out if you have time. :)

How do I associate the new form with the content-type?
When the form is submitted, how does the data get saved? How do I associate the submitted form with the database?

The Entityform module already handles this for you out of the box.
So what you need to do is to create your survey form using the Entityform module and you're basically good to go. You would have:

A public form where your anonymous/not logged in users can fill-up.
A content type where it relates the data submitted by the user.
A page which lists all the user submitted data.


Do you want to get the username, as the variable name suggests?

$uname = User::load($userCurrent->id())->name->value;

Your question does not make sense, why load the user with the id to get the id, you already have?


Changing page orientation of a pdf of a views generated by the Print module

If you used MPDF as your library then add this function to your themes' template.php:

function MYTHEME_print_pdf_mpdf_alter(&$mpdf, $html, $meta) {
  //return;
  if(is_view_path()) {
    $paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT);
    $format = $paper_size . "-L";
    // set document information
    $mpdf = new mPDF('UTF-8', $format);
    $mpdf->SetAuthor(strip_tags($meta['name']));
    $mpdf->SetCreator(variable_get('site_name', 'Drupal'));
  }
}

I could not find a way to alter the paper orientation after the object was instantiated, so I opted to just create it again (orientation is set in class creator).

You should then implement a function called is_view_path that returns true if it detect the printpdf path of the view, so that the code only runs for your specific view.

function is_view_path() {
  $path = current_path();
  return $path == 'VIEWPATH'; // just add your view path here
}

If you used TCPDF you should look at the function print_pdf_tcpdf_print_pdf_generate in print-pdf-tcpdf.page.inc at how to instantiate the $pdf object, and then implement an alter hook similarly to what I did above. I could not do it as for some reason I cannot get the tcpdf library to detect.

For DOMPDF I could not find an alter hook.


Theme import not changing the color scheme

You have to export the color configuration from the old site and import it to the new site.

You can do this in UI. Go to /admin/config/development/configuration/single/export, select configuration type Simple configuration and the configuration name color.theme.mytheme. Copy and paste the color configuration to the new site. Use here the single item import section.

If you want to do this automatically when installing the theme you can place the file color.theme.mytheme.yml in the /config/install folder of the theme.


1.content type specific template would be: node--type-article
2.{% if logged_in %} will return boolean.
3.{% if (node.field_video_embed_filed.value != NUll)  %} or null can e replaced by your condition or you can use kint devel modue for better filtering like: {{ kint(node) }}


drupal_set_breadcrumb() function doesn't work on "Add content" pages!

Ok, I just solved it! It's too easy! Using the below function in template.php file:

function mytheme_breadcrumb($variables) {
  $sep = ' &gt; ';
  if (count($variables['breadcrumb']) > 0) {
    return implode($sep, $variables['breadcrumb']) . $sep;
  }
  else {
    return t("Home");
  }
}

and using the arg() values and $variables['breadcrumb'] values in above function can enable you to check every pages path. Such as adding the below piece of code the above function:

  $breadcrumb = $variables['breadcrumb'];

  $is_add_content=false;
  foreach($breadcrumb as $key=>$value){
    if(strpos($value,"node/add"))
      $is_add_content=true;
  }

References:

https://www.drupal.org/node/64067
https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_breadcrumb/7


Create a layout 3 column with 2-1-2 teasers

This solution is not perfect, but will most likely be the fastest to achieve:

In hook_node_preprocess() render the image field twice, once with small and once with large image style.
Edit your node--YOUR-CTYPE.tpl.php file and display both images.
Use CSS to display the correct one. You can basically do this:

.views-row-1 .your-large-image-selector,
.views-row-2 .your-large-image-selector,
.views-row-4 .your-large-image-selector,
.views-row-5 .your-large-image-selector {
  /* Hide large image. */
}
.views-row-3 .your-small-image-selector {
  /* Hide small image. */
}

Other than that, you could try doing this in a custom module, unless you really need Views for something. I think doing this through a custom module makes more sense if you have to display a larger number of images on the page (e.g. 20-30), because with the approach above you will end up with twice as much images.

Here's what you would need to do in a custom module:

Add hook_theme() implementation and declare your own custom template. Here you would display the first two items on the left, third in the middle and the last two in the right column. The arguments for the template would be just an array called items for example.
Get all nodes you want to display, prepare the output and split them into groups of 5. Every third item would use the larger image style.
Loop through the groups and theme the output based on your custom theme.
Put everything together and display on the page.

This way you won't have 2 images for each node, but you will have to write custom code.

There are other ways to achieve this, but I believe developer sanity should not be overlooked. The ways I suggested above are more or less easy to do.

Hope this helps.


Drupal has jQuery UI tabs built right in so you'd be better off leveraging that if possible. This is a standard theme function I chuck into most projects to help with this sort of thing:

function theme_tabs($vars) {
  if (empty($vars['items'])) {
    return '';
  }

  $js_added = &drupal_static(__FUNCTION__, FALSE);
  static $delta = 0;

  if (!$js_added) {
    drupal_add_library('system', 'ui.tabs');
    drupal_add_js("jQuery(document).ready(function(){ jQuery('.tabs-container').tabs(); });", 'inline');
    $js_added = TRUE;
  }

  $tabs = $content = '';
  foreach ($vars['items'] as $key => $item) {
    if (isset($item['#access']) && !$item['#access']) {
      continue;
    }

    $tabs .= '
' . $item['title'] . '
';
    $content .= '
' . render($item['content']) . '
';
  }

  $delta++;

  return '
' ."
$tabs
$content
";
}

You would call it like this:

$tabs = array(
  'tab1' => array(
    'title' => 'Title for tab 1',
    'content' => 'Content for tab 1' // Note this can be a string or standard Drupal render array
  ),
  'tab2' => array(
    'title' => 'Title for tab 2',
    'content' => 'Content for tab 2'
  ),
  // etc.
);

$args = array('items' => $tabs);
print theme_tabs($args);

Of course if you're doing this 'properly' you would register the theme function in a module like so:

function MYMODULE_theme() {
  return array(
    'tabs' => array(
      'variables' => array('items' => array())
    )
  );
}

and call it like this instead:

print theme('tabs', array('items' => $tabs));

Hope that points you in the right direction.


Showing different nodes for same taxonomy terms on different URLs

You can use the Views module to create two different pages:

"Jobs in City %1" at /jobs/%
"Companies in City %1" /companies/%

Your Views will need a filter for content type, and a contextual filter for taxonomy term.  Next, use the Rabbit hole module to make the /taxonomy/term/NNN pages disappear.


How can I automatically add taxonomy terms to a page's  keywords in the HTML?

I think you are looking for the Drupal 6 Nodewords module.

The Meta tags module is/was supposed to be the new Drupal 7 version, but it appears to be on hiatus. The Meta tags quick module, however, is an option (currently in dev).

This helpful post has more details.


In which template file is a node title supposed to be?

Page title is now a block

  The page title is now provided by a block so it can be easily moved
  without editing the page template.

  The markup for the page title can be edited in page-title.html.twig,
  and template_preprocess_page_title() can be used in conjunction with
  the template

Source: https://www.drupal.org/node/2568563


Go to admin/appearance/settings/your_subtheme_name. Check attached image. You can set rights on who is or isn't allowed to see debugging stuff.

Uncheck debugging options will hide empty blocks...


Use a view to show multiple content types, but only show a field if it belongs to specific content type

Yes, i'm pretty sure you could use a module like Display Suite to make a custom view_mode for content type B. You could only use this view_mode in your View to show everything but field A from Content Type B.

Note, there are other modules that let you define custom display modes as well -- DS is not the only solution.


Allow anonymous users to load site contact form without granting admin privileges

The Access Denied error is returned because the following code executed by code_site_form(). (Notice the call to drupal_access_denied().)

  $limit = variable_get('contact_threshold_limit', 5);
  $window = variable_get('contact_threshold_window', 3600);
  if (!flood_is_allowed('contact', $limit, $window) && !user_access('administer contact forms')) {
    drupal_set_message(t("You cannot send more than %limit messages in @interval. Try again later.", array('%limit' => $limit, '@interval' => format_interval($window))), 'error');
    drupal_access_denied();
    drupal_exit();
  }

Users with the "administer contact forms" permission don't get that error, since the limit for the sent messages doesn't apply to them.

Check those Drupal variables have not been set to different values that lower the number of allowed messages. The default is 5 messages in 1 hour.

As side note, render(drupal_get_form('contact_site_form')) would cause a "call-time pass-by-reference" warning in PHP 5.3, since render() is expecting a variable passed by reference, but drupal_get_form() doesn't return a reference. PHP 5.4 will raise a fatal error for that same code. The code calling render() should always use a variable.

module_load_include('inc', 'contact', 'contact.pages');
$form = drupal_get_form('contact_site_form');
print render($form);


How would you assign a taxonomy term on user registration programmatically?

Have you considered using Rules?
You could have it react on updating an After saving a new user account,

check for the role being set,

Click on Add Action, select Set Data Value

For DATA Data Selector put account:field-[name] In mine I named/called the term reference field test
For VALUE Data Selector put site:current-user:field-[name]
We use site current user, because the current logged in user is the Meeting Manager, so we use their term ref field value.

Result:
This is how it should look like for you. Except for you the authenticated user in condition should be customer and in Action the test should be your term ref field name.


How to manually make sure the database schema is right?

The Schema module gives you a lot of different tools to handle your schema; for example, it checks whether your schema is in sync with your database.


How to sort field_info_instances return value by field weight?

You probably want something like this

$info = field_info_instances('node','bundle_name');

uasort($info, function($a, $b) {
  $a_weight = (is_array($a) && isset($a['widget']['weight'])) ? $a['widget']['weight'] : 0;
  $b_weight = (is_array($b) && isset($b['widget']['weight'])) ? $b['widget']['weight'] : 0;

  if ($a_weight == $b_weight) {
    return 0;
  }

  return ($a_weight < $b_weight) ? -1 : 1;
});

// $info is now sorted by weight.


How to perform some Rules Actions WHILE some condition is TRUE?

I'm not aware how to implement such WHILE-construction by only using Rules. However, if you also enable the Conditional Rules module, you can implement such WHILE-construction.

Example

Consider this rule (in Rules export format):

{ "rules_execute_a_while_loop" : {
    "LABEL" : "Execute a while loop",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_nr" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Value specified for \u0022Free format nr\u0022 is: [node:field-free-format-nr]" } },
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : "1" },
          "PROVIDE" : { "variable_added" : { "loop_counter" : "Loop counter" } }
        }
      },
      {
        "WHILE" : { "NOT data_is" : {
            "data" : [ "loop-counter" ],
            "op" : "\u003E",
            "value" : [ "node:field-free-format-nr" ]
          }
        },
        "DO" : [
          { "drupal_message" : { "message" : "Do your thing for \u0022loop_counter\u0022 value = [loop-counter:value]" } },
          { "data_calc" : {
              "USING" : { "input_1" : [ "loop-counter" ], "op" : "+", "input_2" : "1" },
              "PROVIDE" : { "result" : { "incremented_counter" : "Incremented counter" } }
            }
          },
          { "data_set" : { "data" : [ "loop-counter" ], "value" : [ "incremented-counter" ] } }
        ]
      }
    ]
  }
}

Some more details about this rule:

Rules Events: After creating a new node, or after updating an existing node.
Rules Conditions:

Content is of type "Article".
Entity has field, for field with machine name field_free_format_nr (which is of type integer).

The above Rules Events and/or Rules Conditions can be more or less anything (I just used some of the popular ones). The actual magic is in the Rules Actions:

Show a message on the site, just for demo / testing purposes, to show the value enter for the field_free_format_nr field.
Add a variable, with machine name loop_counter, and initial value 1.
While: NOT Data comparison, whereas the test is to check if NOT (loop-counter is greater than [node:field-free-format-nr]), in which case all of the below Rules Actions are performed:

Show a message on the site,  just for demo / testing purposes, to show a message like

  Do your thing for "loop_counter" value = [loop-counter:value]

Calculate a value, to increment loop_counter with 1, and (temporary) store the result in incremented_counter
Set a data value, to copy the value of incremented_counter in loop_counter

BTW, it could well be that the last 2 Rules Actions can be consolidates in a single one, though using 2 Rules Actions should be easier to understand what's happening.

Demo

With the above rule enabled, these are the messages shown if I create or update an article, and specify a value of 3 for the field_free_format_nr field:

Value specified for "Free format nr" is: 3
Do your thing for "loop_counter" value = 1
Do your thing for "loop_counter" value = 2
Do your thing for "loop_counter" value = 3


How to prevent applications from uncovering the technologies used on the website

Making all the Drupalisms disappear is hard work and most definitely not worth your while, as stated above by Clive. In addition, you'd also have to edit/obfuscate many of your http headers.

At that point, if it were me visiting your site all the SSL and Trustee certs could not make up for trust lost and I'd leave. Plus, I might tell my nerd friends what a suspicious weird site you run and turn them off too.

My advice: Don't break what makes the web work, and secure your site. You can and should stop nginx and PHP from advertising their version numbers, and you should delete Drupal's .txt files.


I believe you can use Views to display your node and aggregate your Taxonomy terms to prevent duplicates.


How do I know when Hooks are called and in what order?

You're looking for an event, not a hook to do this in 8.x

Specifically, you're looking for the RESPONSE event, see \Drupal\Core\EventSubscriber\AnonymousUserResponseSubscriber for an example. Create a class like that, register it in yourmodule.services.yml and then do whatever you want with the $response object.


Is it possible to write node migrations for D8 alpha/nightly yet?

We haven't written Drupal 8 sources yet and they won't be written until Drupal 6 and Drupal 7 is done. It's not a priority. You could, of course, help with writing them :)


How do I control the visiblity of an exposed filter in a taxonomy term view?

There is an option in views to display your exposed filters in a block. In this usecase, if you only have one exposed filter, it might work for you to put the exposed filter in a block and then identify the pages you want to display it on in the block administration page.

You could use url aliases and a wildcard * to isolate all terms of a certain vocabulary to save you listing each page in the block admin form.

To put the exposed view in the block: Click on the advanced tab over on the right of the views pane and change 'Exposed form in block:' from No to Yes.


To add field_images to your product type, you need to use the "Add existing field" and not "Add a new field" Then the existing machine name is reused. Following that you can configure bundle specific settings under field "instance" settings, as opposed to the shared "global" field settings.


POST request trying to make a Session authentication in the REST SERVER return a HTML error 406 Not acceptable

First of all make sure you choose the appropriate Data types for request formatters and parsers for your resource. You will find it under admin/structure/services/list/your_resource_name/server. Having said that, this works for me :

// .xml asks for xml data in response, choose what you need here
$service_url = 'http://localhost/your-endpoint/user/login.xml';
$post_data = array(
    'username' => 'admin',
    'password' => 'pass',
);
// We format post data as application/x-www-form-urlencoded so make
// sure that you tick it under the rest server parser options.
$post_data = http_build_query($post_data, '', '&');
// Initialize the request
$curl = curl_init($service_url);
// We want curl to return a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Choose method POST
curl_setopt($curl, CURLOPT_POST, true);
// Feed the data to POST to curl
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
// Make it verbose for debugging.
curl_setopt($curl, CURLOPT_VERBOSE, true);
// Go!
$response = curl_exec($curl);
curl_close($curl);
print "LOGIN RESPONSE:\n";
var_dump($response);
// parse the response we get (in XML see above)...


A quick search turned up this video from DrupalDude: Statistics module in Drupal 5

There's also the documentation for the module for the D5 version on Drupal.org that suggests you should be able to use statistics_get() to get the views for a certain node.

Something like the following would do it:

$stats = statistics_get($nid);

// Total view count
print $stats['totalcount'];
// Current day view count
print $stats['daycount'];
// Timestamp of last view
print $stats['timestamp'];


The solution in my case was to run...

composer global update
composer global require drush/drush:dev-master

Previously, I had been running composer update but needed to run composer global update.


Where to put Commerce Kickstart translation po file?

The internationalization process is not unique to Commerce Kickstart; it is the same for all Drupal sites and handled by the Locale module.  The Drupal.org documentation can be found here.  (Start with Install a language.)


How do I override the title with the username?

Make Fields your format

Alternatively: if you are using the rendered entity row plugin check the Force using fields in the Format | Settings.
In RELATIONSHIP, Add Content author

Checkmark ☑ Require relationship

In FIELDS, add Name

Checkmark ☑ Exclude from display
Uncheck ☐ Link to the user

For TITLE put {{ name }}'s blog

OR you could put it in your CONTEXTUAL FILTER; even though {{ name }} is not listed as a replacement pattern, it works (as long as you do step 1, 2, and 3).

Result

BONUS

If you want to capitalize the first letter of the user name use {{ name|capitalize }}'s blog.

You can also add a Rendered Entity as a field.


How to add points using User Points in Drupal 6

Check nodevote module. It does something similar. You may use it directly or base your code on it.

If you want to use a more sofisticated solution with VotingAPI you can use  userpoints_votingapi and use rate module for the widgets

Cheers.


How to remove square brackets from name attribute in webform elements?

you can use hook_form_alter

Example D8

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if ($form_id=='comment_comment_form') {

    $form['subject']['widget']['0']['value']['#name'] = 'field_machine_name';

  }

}

Example D7

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

 if ($form_id=='comment_node_article_form')        {
    $form['subject']['#name'] = 'field_machine_name';
 }

}


You use CSS to style the links. Looking at your code, the secondary menu has an id secondary-menu-links. So target that within your CSS:

#secondary-menu-links a:hover {
  /* your pop-out effect here */
}


To get the YouTube video thumbnail URL in twig!
Try with:
{{ file_url(content.field_url_vid2.0['#media'].thumbnail.0.entity.uri.value) }}


Order nodes based on entity reference filter

Create a view that shows Content of type "A", add a relationship for Entity Reference: "B".  Then add a sort criteria and sort by Content "A".  Choose the relationship on the sort criteria as the relationship you made earlier.  You can expose the sort order so it can be chosen to sort ascending or descending.  This is not a draggable solution but it does allow you to sort by the referenced entity.


How to enforce users to input user account's fields after user registeration?

Try using Rules. You could add a new field into the users' accounts that is Completed Profile Fields and it could be a single boolean or possabily a multi-value field.

Then your rule could check:

If login, or page load -- has user completed profile fields? If yes, continue to any page -- else show a profile form page (not necessarily their account page).
I'm not sure it would be easy to do this globally, or test the profiles have been filled prior to going to a /node/add page for instance.
After filling in the profile values the Rule could update the user account field completed profile fields to True.

If you don't want users to see this completed profile fields field -- you can install and use Field Permissions.

EDIT

If you dont want the user to see this special completed profile fields but still want the rule to update the value you may need to set the uid of the user updating this field. I do this usually by creating a fake user for the system called like mysite-system-user and give him a special role called system role for instance.


How to set up Drupal 7 on Apache/2 without .htaccess files ?

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

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

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

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


menu_tree_all_data returning empty arrays for custom menus

If you are looking to print a menu tree, then it's answered here. I have tried this and solution worked !

<?php

$tree = menu_tree_page_data('menu-name'); // Replace menu-name with menu name you want to print
$first_level = db_query("SELECT mlid FROM {menu_links} where menu_name = 'menu-name' and plid = 0 ORDER BY weight ASC");
while ($item = db_fetch_object($first_level)) {
  $mlid = $item->mlid;
  // Extract subtree
  $subtree = admin_console_menu_get_subtree($tree, $mlid);
  // Render as HTML menu list
  $content .= menu_tree_output($subtree);
}
return $content;
?>

/**
* Extract a specific subtree from a menu tree based on a menu link id (mlid)
*
* @param array $tree
* A menu tree data structure as returned by menu_tree_all_data() or menu_tree_page_data()
* @param int $mlid
* The menu link id of the menu entry for which to return the subtree
* @return array
* The found subtree, or NULL if no entry matched the mlid
*/

function admin_console_menu_get_subtree($tree, $mlid) {
  // Check all top level entries
  foreach ($tree as $key => $element) {
    // Is this the entry we are looking for?
    if ($mlid == $element['link']['mlid']) {
      // Yes, return while keeping the key
      return array($key => $element);
    }
    else {
    // No, recurse to children, if any
      if ($element['below']) {
        $submatch = admin_console_menu_get_subtree($element['below'], $mlid);
        // Found wanted entry within the children?
        if ($submatch) {
          // Yes, return it and stop looking any further
          return $submatch;
        }
      }
   }
}
// No match at all
return NULL;
}


How I create table View of webform submissions

You can create your own tables of Webform submissions with Views...

Make a new view of type 'Webform submissions'
Add a page, set the path and set the Style to 'Table'.
Add the fields you want, sort and filter as needed.

If you want submissions filtered by the node (Webform) they were submitted against,  you should add a relationship for 'Webform submissions: Node' so you can pass the Node ID to the view -- remember to include the argument placeholder in your path for the nid (e.g. submissions/%)

(Of course, this provides a tabular view of Webform submissions with the fields you choose as outlined in your question -- the existing view of submissions will still be on the tab for that Webform node... Changing that is a different question.)


What is the correct way of logging in through services from android?

You can use Android AccountManager over https to be more secure.
Like this Drupal 8 Android app at https://github.com/onedrupal/One-Drupal-Android.


Exception handling in Drupal

Exceptions are handled by FinalExceptionSubscriber, unless there is a more specific exception subscriber handling it before.

Core defines several of them, which are listed here: 27 uses of GetResponseForExceptionEvent

How default exceptions are handled

When you throw an exception in code

throw new \exception('ID ' . $id . ' not found in table xyz!');

the default exception handler returns a 500 http status code with this standard message:

  The website encountered an unexpected error. Please try again later.

If you enable error reporting (admin/config/development/logging) you get a more verbose exception message displayed on screen:

  The website encountered an unexpected error. Please try again later.

  Exception: ID abc not found in table xyz! in Drupal\mymodule... (line
  123 of modules/custom/mymodule/src/....php).

Conclusion

Now, what you want to do depends on how much information you want to disclose to the public. Often if you don't find the data you are looking for a 404 exception is more meaningful than a 500 exception. If none of the core exception handling fits your purpose you can implement a custom exception subscriber:

Handle database connection exception via custom handler


As an adminstrator, you can set additional user fields at:

/admin/config/people/accounts

Note the tabs Manage fields and Manage displays. You can control if and how these fields appear on the registration form, and also how they appear to the user via these tabs. You can even create non-visible fields for storing other kinds of hidden data against a user should you need to.

By default, the link to register is:

user/register

You would normally create a menu item if one doesn't exist already to appear somewhere on your site, or you can just output the link in a suitable location depending on your needs.


Is there a module for "mail routing" in Drupal 6?

You could try: https://drupal.org/project/reroute_email
While it's mainly designed to reroute all email to predefined addresses, e.g during development, you could use it as a starting point for similar functionality.


Updating settings.php breaks website hosted from subfolder

Try setting your base URL in settings.php like

$base_url = 'http://site1.com';  // NO trailing slash!

And in your .htaccess file set RewriteBase to:

RewriteBase /site1

or

RewriteBase /site1-test


How do I create a view to re-arrange blocks or menu items?

You can use draggableviews to reorder the items.


I am not clear what is your requirement. If you want to create a single menu page and want to show list of group name , you can do this using views. Create a view page and list your content and select menu type as normal nemu item.

OR

If you want to create list of menu items according to group name, in that case you should try to create custom menu using hook_menu.
check here https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7


Views exposed filter and non latin characters

Transliteration module has some useful functions to convert unicode strings into latin strings. You may give it a try and use some of those functions in your alter hooks. I cannot give you a specific function name but I'm sure that I've used this module for a similar purpose.

Anyway, if you work with non-latin languages, you'll probably need to install this module for other purposes, like fixing the filenames and url parts generated by user input etc.

A quick look-up into the source code of Transliteration module, I can say that you can use transliteration_get() function to transliterate a give string. A sample implementation for your case would be:

function YOUR_MODULE_views_query_alter(&$view, &$query) {
  // To debug comment out the following line (Devel module is required).
  //dpm($query);

  if ($view->name = 'YOUR_VIEW' && !empty($view->exposed_raw_input['YOUR_FIELD']) {
    $transliterated = transliteration_get($view->exposed_raw_input['YOUR_FIELD']);
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on your field, change the
        // condition value to the transliterated string.
        if ($condition['field'] == 'YOUR FIELD') {
          $condition['value'] = $transliterated;
        }
      }
    }
  }
}


How to extend block.block.* schema configuration file

The answer is to use the ThirdPartySettingsInterface Interface, using that interface you can add/save custom configuration for config entities, works perfect. Thank you !.

More info here
https://www.heididev.com/how-alter-configuration-entity-data-drupal-8-or-add-additional-data-configuration-entities


Look at theme_facetapi_deactivate_widget function in facetapi.theme.inc. Of course, you can override it in your theme.


How do I fetch user profile data in search api entity (node) view?

Your search api view is only able to list what has been indexed, so you should add the node author to the search api index.

After this, in search api, you should be able to add 'related fields'.

After adding items to be indexed in search api, make sure you reminded your site!


To design the search block form you can override the existing search-block-form.tpl.php in the theme's template folder.

<?php

$variables['form']['search_block_form']['#attributes']['placeholder'] = "Search for...";
$variables['form']['search_block_form']['#attributes']['class'] = "form-control";

?>

        <?php if (empty($variables['form']['#block']->subject)): ?>
          <button class="btn btn-default" type="button"><?php print t('Go!');?></button>
        <?php endif; ?>
        <?php print $search_form; ?>


I think I know what is going on. I've had this problem several times before.

The issue is that on some pages, multiple pagers may be in use. Which would explain why theme('pager'); wouldn't work.

I just had the same problem, and I got it working by doing this:

theme('pager', array('element' => 1));

On my end, I wasn't displaying multiple pagers, but I think something else on the page must have been doing this, because the above code made it work! I hope this helps anyone else who encounters the same problem.


There is a bock for this.

You can create/configure the block from Configuration->Search and Metadata->Current Search block (admin/config/search/current_search)

Create a new Search Block and choose a type: Active Items. In pattern enter from tokens below: [facetapi_active:active-value]
Then go to your blocks page and activate your new block.

See the screenshot how my settings look like.


override 'Edit own content' using taxonomy access

Ok, I've found a way around it. I'm using the Workbench Access module.

This module, which can be used as a stand alone module, allows you to use taxonomy terms as sections you can set on any node and then you need to assign the roles (or particular users) who can update nodes with these terms/sections. In conjunction with the taxonomy access control module I found that you must at least set the global default for that role to 'view'. If you don't, the users of that particular role won't have update AND view access which is not what I wanted. They can see what they've created but they can't change it anymore after they saved it or after a certain taxonomy term has been set, by themselves or automatically through rules.

Hope that helps others as well!
Cheers!


To check user role before login you need to create a validate function for login. You can put this code in template.php of your theme or in custom module file. e.g my custom module name is MYMODULE.

<?php

/**
* Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'user_login') {
$form['#validate'][] = 'MYMODULE_user_login_validate';
}
}

/**
* Additional handler for user_login form validate.
*/
function MYMODULE_user_login_validate($form, &$form_state) {
  // check user role here by the function mentioned abve
   $name = $form_state['values']['name'];
   $user = user_load_by_name($name);
   $role = array_key_exists(2, $user->roles);
   // do something
}

Hope it will help you.


You seem to be trying to use method for adding settings. I believe this is the correct way as stated on the docs:

$form['#attached']['js'] = array(
  'jQuery(function() { console.log("test"); });' => array(
    'type' => 'inline',
  ),
);

Docs: #attached


Let local drush call remote drush with `bash` or `sh`

You will need to do something like this:

$aliases['myremotesite'] = array (
  'remote-host' => 'isp.example.com',
  'remote-user' => 'www-admin',
  'root' => '/srv/www/example.com/drupal',
  'uri' => 'http://example.com',
  'path-aliases' => array(
    '%drush-script' => '/home/www-admin/bin/my-drush',
  ),
);

Customize URIs, paths and sitenames to suit.  Then, create a 'bin' directory in your $HOME (if you don't already have one), and make yourself a 'my-drush' script like this:

#!/bin/bash

bash drush $@

Once we commit https://github.com/drush-ops/drush/pull/1595, you will be able to simplify the above by copying the drush.wrapper script to your remote site's Drupal root, and prefixing its call to the Drush launcher with bash.  That PR is close, but it's also Drush 8 only, so you might prefer making your own my-drush script, as shown above.


How to give edit permission only to specific fields in node edit in?

You can use the Field Permissions module. It allows you to set permission for each field for every user type. It works simply fine.

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

  Features

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on who the entity owner is.
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.


How show time period in one concrete time unit?

Perhaps it would be simplest to just use an integer field?

Set the field type to Integer
Click save, and then on the following page you should be able to set a "Suffix" of 'mins' or 'minutes' as you prefer.
If you want a space between the number and minutes, be sure to type that at the start of the suffix field.


Keeping $attributes but adding a rel (D7)

If I understand you right you just want to add the rel attribute to the $attributes array before you call l(). Something like this:

$attributes['rel'] = 'the_rel';
print l('

' . $image, $link_path, array('html' => TRUE, 'attributes' => $attributes));

That will add the an item to the $attributes array with a key of rel and a value of the_rel, and won't affect any of the other attributes already in the array.


Use email to validate post, not unlike craigslist

You can use the Rules module, but you'll have to write a custom rule to grab the email from the submitted node and send a verification link to the email address. You could also do this with a custom function through hook_entity_insert().

For the verification link you could do use drupal_hmac_base64() to create a url-safe hash of the content of the post or of the node + timestamp + email or something like that.

Then you can create a custom menu to fire a callback function that takes arguments from the verification link to publish the node if the verification link is correct.


Update: It seems this data is never rebuilt in full, but is only updated by a field definition listener.

One possible solution is to remove all fields and bundles from the site (by deleting the configuration from the sync folder and importing), then re-creating them (by reverting the deletions and importing again). This will obviously delete any content that may have been created.


Deleted all the content... but it's all still there?

That Undefined index: name in system_sort_modules_by_info_name() error sounds like a broken module not defining its name in its .info file

One possibility is from coder/coder_sniffer/Test/bad.info

see: http://drupal.org/node/1015368


Users add payments to order without editing order

Have found the answer in "commerce/modules/payment/commerce_payment.module"

Lines 964-972

    // Creating new payment transactions.
case 'create':
  if (user_access('create payments', $account)) {
    // We currently allow any user to create any payment transaction,
    // regardless of the order, because entity_access() doesn't give us a
    // way to discriminate on the order.
    // @todo: find a way to prevent creating a payment transaction if the
    // user doesn't have access to the order.
    if (!isset($order) || commerce_order_access('update', $order, $account)) {
      return TRUE;
    }
  }
  break;

need to be updated to the following

    // Creating new payment transactions.
case 'create':
  if (user_access('create payments', $account)) {
    // We currently allow any user to create any payment transaction,
    // regardless of the order, because entity_access() doesn't give us a
    // way to discriminate on the order.
    // @todo: find a way to prevent creating a payment transaction if the
    // user doesn't have access to the order.
    if (commerce_order_access('view', $order, $account)) {
      return TRUE;
    }
  }
  break;

This does not appear to have any security implications.


Using module_invoke for Menu causes Undefined index notice

It is caused from the following line, executed from menu_block_view().

$data['subject'] = check_plain($menus[$delta]);

$delta is the value you pass as last argument to module_invoke().

It means there isn't any menu with that ID, or you misspelled the menu ID. Try with main_menu, for example.


How to show a view with 2 columns on the front page?

There are many ways to do this:

Create a block for each of your views, then add the blocks to the
content area and select to show on front only (all done via block
UI), and set it side by side via CSS.
Create a content type for the front page. Then create a new instance
of that content type. Run it through panels and choose two column
layout, then add views of your liking to the left and right panel.
Create a content type for the front page. Manage the display of this
content type via Display Suite and use two column layout. Add a
dynamic field for each of the left and right columns, and set the
dynamic field to display a view of your liking.
Implement hook_menu_alter for the front page in a custom module.
Return the output of 2 views_embed_view() calls wrapped in HTML for
the columns, or in a render array that will suit your layout.
Create a content type for the front page or use an existing type.
Then create a new instance of that content type. Note the path of
this content (node/ID). In configuration - site information, set it
as the front page. Edit this content type's body element, and using
the PHP filter embed the views with calls to views_embed_view().

Methods 2 and 3 are in my opinion preferable, with method 5 the least preferable method. Method 1 is perhaps the easiest.


how to make an automatic download button?

The generic file output of the file field is pretty close to what you are asking. It creates a link with a icon showing the file type and links to the file (download, unless the browser understands the file, like an image would be displayed in the browser instead of being downloaded)

You could with theming/css alter the appearance if you so please.

If you want force download, you have to modify the headers sent to the browser. You can use the File Force Download if this is your goal (Thanks for the tip @nicoz). It seems to be using field formatters, which functions much like the generic file display possible with file fields.


Aren't the Article content type and the Blog module the same?

The blog module allows several users to have different blogs. It adds more features that are typically found in a blog to the article. If you are making a single author blog it might be better to build with Views using the Article content type than use the blog module.


Inline entity form shows a content type select list

Try editing the inline entity field and only setting one entity (ie Company content type in your example) that can be referenced.


How to create an unsubscribe link via mail in simplenews?

You need to use token_replace.

Try this:

<?php
$newsletter = simplenews_newsletter_load($node->nid);
$context = array(
  'category' => simplenews_category_load($newsletter->tid),
  'simplenews_subscriber' => simplenews_subscriber_load_by_mail($mail)
);
print token_replace('[simplenews-subscriber:unsubscribe-url]', $context, array('sanitize' => FALSE))';
?>

You should get a url like so: http://example.org/newsletter/confirm/remove/c453d5e25d2t10

That thing in the end is an hash, built in simplenews_token() (simplenews.tokens.inc).

Update: I updated my answer to show how you can get the correct variables from simplenews. Taken from simplenews_node_view() (in simplenews.module).


How do you make nodes automatically publish one by one after specific time?

You can use Rules module with rules scheduler, check this tutorial for better understanding on how to configure.

and also take a look at Scheduler module


How to add a view for a node with an ID?

I think you'd find Panels with a node_view panel page override suits there.

Install and enable page manager then enable the default "Node view" panel page.

It will override node/%node with a page in which you can embed views content pane displays etc...


View contextual filters to work as needed

This is extremely easy using Panels as Panels is context aware. You can pass this context to the view, which displays the results based upon the contextual filter.

Look at http://nodeone.se/sv/node/702 and the next episode to get the hang of it.


How do you show/hide delete(remove) product button in the Cart?

Shopping cart in Drupal commerce is a view. To remove the "remove" link, all you need to do is edit it and remove the "remove" field.

The view can be found at /admin/structure/views/view/commerce_cart_form/edit
and remove the field (Line items referenced by commerce_line_items) Commerce Line Item: Delete button (Remove)


Look on how Advertisement module is doing it.

Simplified outline is:

Each image is linked to a page named like /count/someuniqueid
Module implements that page to increase counter and then sends 302 Found HTTP header to user's browser.
Browser is redirected to a desired page and user don't really see what happened at all.

Actual workflow is, due to performance issues, way more complicated and involves php files that does not bootstrap Drupal, caching and all that.


Adding Count Up module to custom front page

Working sample:
     <!DOCTYPE HTML>

       <meta charset="UTF-8">
       <title>CountUp.js</title>

0


Unusual behavior of Shopping Cart (Drupal Commerce)

What you describe is the default behavior in Drupal Commerce, as it is supporting the idea of "multiple carts", so when you log in you get the items that you've got in your current cart and the other cart will be kept in the "background".

In fact, if you end the purchase you have once logged in, you'll most probably see that the items you had in the cart in the first place are back in there.

I'm afraid this is something you can't solve without some coding or rules, the theory here is that on the user login event, you get all the past orders from that user and combine them in the current cart of the user. This is not something you normally want as the cart pulled might be old.


Why can I not find the og table after installing Organic Groups?

The Drupal 7 version of Organic Groups doesn't have an og table. The Drupal 6 version does, but it's removed as part of the upgrade process, and never exists in the newer version.

You can always find out what tables a module is responsible for by checking its implementation of hook_schema() (in this case og_schema()).


Filter view list items by user property and item property

I think I understand what you're describing, and it is theoretically possible to handle in the hook as you've started, with something like this:

/**
 * Implements hook_preprocess_views_view_unformatted().
 */
function mymodule_preprocess_views_view_unformatted(&$variables) {
  if (isset($variables['view'])) {
    $view = $variables['view'];
    // You'll want to check the ID && possibly the current_display so as not to fire on every View!
    // In this example, my View is called "test", and I have a page display called "page_1".
    if ($view->id() == "test" && $view->current_display == "page_1") {
      $result = $view->result;
      // You mentioned doing something regarding the user, so you could grab that here.
      $current_user = $variables['user']->account;
      // The $result will be an array of ResultRow entities.
      foreach ($result as $key => $resultRowEntity) {
        // Do some customized logic on each row.
        // You can access the entire entity here if needed like this:
        $row_entity = $resultRowEntity->_entity;
        // In my case this is a Node, so can do something to get a term field from it.
        // In this example, getting the "some_field" and the first delta of it as a string value.
        $some_field_on_the_node = $row_entity->get('field_some_field')->getValue();
        // You could do some sort of logic here to determine whether or not to unset this row.
        // In this example, I'll say if the field doesn't equal 2, OR the user ID is not equal to 1, unset the row.
        // This would remove it from the result.
        if ($some_field_on_the_node != "2" || $current_user->uid != 1) {
          // You'll want to unset it from 'rows' to not display it.
          unset($variables['rows'][$key]);
        }
      }
    }
  }
}

I think the takeaway is to use "isset" to avoid those nasty PHP errors, and I highly recommend using XDebug, or at the least the devel && kint modules, so that in your code, you can put things like ksm($variables['view']) to get some insight into what variables you have available to use. PHP can be very finicky when you try and reference things that don't exist!

Even though this might technically work, it's worth noting that a better approach would be to implement a relationship in Views to bring in the taxonomy term entity being referenced on your node, and that would allow you to add View filters in the UI to massage out the data that way. You could also add a role that could be associated with viewing your particular content type, and this would automatically exclude it from Views results regarding the user if they didn't have this role.

Of course, I may me misunderstanding the complexity of your use case. Another "better practice" approach would be to implement a custom Views filter, which could then be added via the Views UI and maintained separately in a custom module, and would possibly allow for a cleaner implementation - It's somewhat of a broad topic, but I think this is a great intro to the topic: https://www.webomelette.com/creating-custom-views-filter-drupal-8.

I hope this helps point you in the right direction!


Creating node with multiple custom blocks, best method

You could try the context module https://drupal.org/project/context. With context you can specify that certain blocks only appear on a path specified so if you only wanted them to appear on the page with the url applepoluza you could do so.

As for being able to edit the blocks from the node edit page, perhaps you could set a context with a path to the edit page of the specific node to display a new custom block and in that custom block put in a list of links to each of the desire custom block edit pages. That would a be a pretty simple way to be able to accessibly access all of the custom blocks edit pages from the node edit page.

To directly edit the blocks on a node edit page would get pretty messy but could probably be done with something like Entity Fields and a bit of hard coding if you REALLY wanted to.


Preprocess variables only for certain blocks

Unfortunately, there is no way to do it like that (similar to hook_form_alter()).

The best way to do this would be to use $variables['block']->bid to apply modifications only to the blocks you want:

function mytheme_preprocess_block(&$variables) {
  if ($variables['block']->bid === 'target_block_id') {
    // do something for this block
  } else if ($variables['block']->bid === 'other_target_block_id') {
    // do something else for this other block
  }
}


Set a page to show only to registered users

There's a usable dev version of Node Privacy by Role for D7.

Alternatively, you could edit the templates for those pages to check a user's role before displaying the content. I can't really think of why you'd want to, but you could.


I have never used that particular module, but I used to use the standalone version of the WordPress Audio Player a lot.  The player isn't really skinnable in the same way you can skin other Flash components.  There are some JS properties that you can set to change colors and dimenstions.

The documentation for the module claims

  Player can be styled and changed through Drupal admin interface.

so you should visit the settings page to see what you can do.

That said, there are other options you can explore

jPlayer
Flowplayer
MediaElement (Drupal 7 only, though)


How to remove the zip code field from the checkout page?

Address modifications should be done on the Address module level, not on the Commerce level.

You can disable the zip code for a specific country by subscribing to the AddressFormatEvent and removing the %postalCode token from the $definition['format'] string. A str_replace('%postalCode', '', $definition['format']) should do it.

You can find an example event in this blog post.


How to add radio button in drupal profile page

By using the Profile Checkboxes module, you can be able to add radio buttons in the Drupal profile page.

Download the Profile Checkboxes module, and install it.
If you need to create a radio buttons field, click "List selection" in "Add new field."
In that page, you will find the "Selection options" option with a text area field. Enter the radio button details here. For example, if you are adding the gender, enter "Male" and in next line enter "Female."
Now, at the bottom of the page you will find the "Profile checkboxes" tab.
There you select the "Radio buttons (single choice)" and save.


How can I add a new value for a multi-value field programmatically?

Architectually speaking, it would be much better if you use custom table for this functionality.You can take a look for inspiration (or even use) the following module:

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

From the description of the project:
User IP Log is a simple module that logs the IP address of users on login event to table {uiplog}.

Updated answer:
Since you want to do it yourself. You can implement a hook_user_login in your custom module.
https://api.drupal.org/api/drupal/core%21modules%21user%21user.api.php/function/hook_user_login/8.2.x

Inside you can just paste the following code.

Assumptions/ notes :

This is simple text field is from the type: "Text (plain)". If
you choose any other option I am not sure if this snippet would work
for you.
The machine name of the field is field_field_1. Not the best name but
you could quite easily change that on line 5.

I have added quite a few sanity checks that I think would be helpful on the long run.

// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// The machine name of the field.
$field_name = 'field_field_1';
// Sanity check against the machine name of the field.
if ($user->hasField($field_name)) {
  $field_config = \Drupal\field\Entity\FieldStorageConfig::loadByName('user', $field_name);
  // Checks if has unlimited cardinality, otherwise the appendItem will throw
  // weird error.
  if ($field_config->getCardinality() == '-1') {
    // This is a fancy way to return $_SERVER['REMOTE_ADDR'].
    // Keep in mind that on localhost, this will return ::1.
    $a = \Drupal::request()->getClientIp();
    $user->$field_name->appendItem(\Drupal::request()->getClientIp());
  }
  $user->save();
}

Regards,

Oleg


How to create translations programmatically?

After several days, I finally found the solution. Obviously, there is a bug with Drupal (here 8.4.0).

The hasTranslation() method don't work properly. Instead, you should use  EntityManager::getTranslationFromContext() (will be deprecated in Drupal 9 though).

You can also write a new method like this one to replace it:

/**
 * Check if a node as a translation for the given language.
 *
 * @param object $node
 *   The node object.
 * @param string $langcode
 *   The langcode.
 *
 * @return bool
 *   True (exists) or false (does not exist).
 */
function has_translation($node, $langcode) {
  $existing_translation = \Drupal::service('entity.repository')->getTranslationFromContext($node, $langcode);
  return ($existing_translation->langcode->value === $langcode) ? TRUE : FALSE;
}

So, my corrected code is the following:

if (has_translation($node, $langcode)) {
  $node_translation = $node->getTranslation($langcode);
  $node_translation->title = 'title en';
  $node_translation->field_sub_title = 'subtitle en';
  $node_translation->status = NodeInterface::PUBLISHED;
}
else {
  $node->addTranslation($langcode, $values);
}

$node->save();


An illegal choice has been detected. Please contact the site administrator in drop down list

check for details in watchdog under form to get an indication of which form element is causing the grief - in your case it will be the 'roll' or subject name field (possibly both!)

if you are updating the option array and removing the currently set option, then you have 2 choices:

in your form builder, either

unset($form_state['input']['roll']);

or

$options[$form_state['values']['roll']]
 = "the option i'm trying to get rid of";

the first option just discards the earlier selection, the latter option keeps it available (probably the first option is generally preferable)

additional: I've discovered I can also cause this error by messing my ajax call back so that the options are updated ok, but the form element in the browser isn't updated. In this case you will notice your options are not updating. You then need to double check your callbacks and div id's etc.

hth


An option would be using module_load_include(). Manually making sure it's loaded


Is there a theme equivalent of hook_install()?

You may provide configuration via YAML files as part of a module, profile or theme install by adding them to the config/install directory inside the respective project. So, for example, a file block.block.my_theme_branding.yml would install the branding block into the specified region. This would then contain the setting to disable the site slogan by default. Take a look at block.block.bartik_branding.yml in the standard profile as a starting point.

If the specific block is provided by another module, then it should probably be placed in the config/optional directory.


How do you upload files using the RestWS module?

i use services not restWS, but the steps are quite similar on every REST service.

with your REST client. ie, restsharp, in my case im using Http (plugin for unity).
your first need to be connected, to do that call your server.dominio.co/site/apiName/user/login.json (you need to tick the option on your rest api, that enables user login service). also need to tick file creation permission.
if your are using token rememter to save it, also the session name, and session id myForm.AddHeader(session_name,session_id) (is the cookie). in my case i dont send it because http already do it for me. after that this is how i upload a file with c# and services,

Hashtable hashdata = new Hashtable();

    WWWForm myForm = new WWWForm();
    myForm.AddField("file", base64Img);
    myForm.AddField("filename", name);
    myForm.AddField("filepath", "public://" + folderName);
    string path = server.dominio.co/site/apiName + "file";
    HTTP.Request theRequest = new HTTP.Request("post", path, myForm);

    theRequest.synchronous = true;
    theRequest.AddHeader("X-CSRF-Token", myTOKEN);
    theRequest.Send((request) =>
    {
        if (request.response != null)
        {
            request.response.GetHeaders();

            string result = request.response.Text;
            hashdata = new Hashtable();
            hashdata = (Hashtable)JSON.JsonDecode(result);

        }

    });
    return hashdata;

will return the fid of the file just uploaded... after that you will need to update the field of the node where you want the file to be attached to... you will need a new REST request to update that node, method update, etc, etc

Hopes this helps a bit.... know it's not THE solution... but hope it points you the right way.


Deleted the Content Type now cannot delete or edit node of that type, but it is visible on site

Ideally you should re-enable module which supports that custom node type, so the node can be properly removed.

Otherwise, you can load, edit or delete the node grammatically.

For example, to load the node using drush command-line, you can run:

drush ev "var_dump(node_load(1234));"

To delete it, try:

drush ev "node_delete(1234);"

Alternatively, you can delete these nodes from the node table.

To find all other references, check your database, e.g.

drush sql-dump --ordered-dump | grep my_node_name


Content Type "Article" is not showing when trying to add, but it is showing in Structure-> Content Type. Please help me

Try re-enabling the content types in the navigation menu.

Go to administration->structure->menus->navigation and you should see your article content type disabled in the menu. Just re-enable them and it should all work fine


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

<?php if ($exposed): ?>

  <?php print $exposed; ?>

<?php if ($header): ?>

  <?php print $header; ?>


Export selected view rows and selected columns to excel

To export just a particular column or number of particular columns you would change the view itself. To preserve the original one, just copy the view export only the column(s) you need and delete the temporary view.


How to prevent Drush pm-update from backing up symbolic links?

This should probably be in the Drush issue queue. Maintainers can help you work through issues if you want to make a patch.  Be sure you are using the latest version of Drush.  By intention, it looks like Drush should only behave as you describe if the --dereference option is specified; without that, it should not follow and archive symlinks.  Run Drush with --simulate to see what actual tar commands, etc. Drush is running.  Post results and followup questions to the issue queue.


What are the security trade-offs between Organic Groups and other methods?

It sounds like you are going to need to use Domain Access and set your organic group permissions to fit your use case.

Here are key points to Multisite vs. Domain Access.

Multisite
 - One database/prefix per site, possible to share users, tables but requires tweaking.
 - Separate install for each but can share modules and themes

Domain access
 - Single Database
 - shared content, users


Views 3 - Create an archive for a given type grouped by year, then split in to months

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


Second ajax button not working on user profile form

If Drupal can't find one of its core files it's nearly always because you're trying to use it in a context in which it wouldn't be automatically included.

For example when you use the user profile form normally, the menu item makes sure the file containing the form functions is included.

For your example the missing function is in user.pages.inc, so:

form_load_include($form_state, 'inc', 'user', 'user.pages');


Drupal 7 Themeing - template.tpl.php vs template.php - variables

The disadvantage is you leak a lot of PHP code processing Drupal inner structures to the template file.

I would preprocess $content in template.php to expose a simple array of strings as a custom variable:

$colors = $content['product:title']['#product']->field_taxonomy_color['und'];
$colorNames = Array();
for ($x = 0; $x < count($max_length); $x++) {
  $colorNames[$x] = $colors[$x]['taxonomy_term']->name;
}
$variables['color_names'] = $colorNames;

Then the template code could be:

<?php if ($color_names): ?>

  <?php foreach ($color_names as $cn)
    print '
' . $cn  . '
'; ?>

<?php endif; ?>


Drupal will add the cols attribute to the textarea, however its CSS which controls it. i.e Width of the textarea or its container is controlling it.

Here is the fiddle example explaining this scenario

In the above example first textarea didn't affected by any CSS so it has 100 cols, however the second one is bounded with another container and its width is restricted, so textarea is rendered within the available width that's why cols value didnt affected the textarea.

The same is applicable for rows attribute when you set height attribute.


Get a single date value from a date field on a node with entity_metadata_wrapper()

In these situations with meta_data_wrapper you could put the array-value before the value function, like this:

$date = $node_wrapper->field_tournament_date->value->value();


select nodes whose created date in hours is equal or larger than 48 hours

Even quicker (and more efficient):

$sql = 'SELECT n.nid, n.title, n.created FROM {node} n WHERE (UNIX_TIMESTAMP(CURRENT_TIMESTAMP()) -n.created)/3600 >= 72');
node_delete_multiple(db_query($sql)->fetchCol());