Save entity without validation While adding a new submit button to the form
$form['actions']['save_as_draft'] = [
  '#type' => 'submit',
  '#value' => t('Save as Draft'),
  '#submit' => ['::submitForm', '::save', 'save_as_draft'],
  '#validate' => [],
  '#limit_validation_errors' => []
];
$form['#validate'] = [['validate_errors']];

This does not save the entity. I am not sure how to edit the following validate function.
function validate_errors(&$form,FormStateInterface $form_state) {
  if ($form_state->getTriggeringElement()['#value'] == t('Save as Draft')) {
    // Skip validation.
  }else {
    // Validate here.
  }
}

Meanwhile, I got the error when saving (Entity validation was skipped):

Any inputs on how I can fix this and allow the entity to be saved without validation?

I had the same problem.
Instead of "#limit_validation_error", adding validation handler which simply omits all the error works fine.
function my_module_form_alter(&$form, $form_state, $form_id) {
  $form['actions']['save_as_draft'] = [
    '#type' => 'submit',
    '#value' => t('Save as Draft'),
    '#submit' => ['::submitForm', '::save',],
    '#validate' => ['_my_module_clear_errors'],
  ];

  // Add this to avoid 'Entity validation was skipped' error.
  $form_state->setTemporaryValue('entity_validated', TRUE);
}

// Remove all errors.
function _my_module_clear_errors(&$form,FormStateInterface $form_state) {
  $form_state->clearErrors();
}

This comment was really helpful
https://www.drupal.org/project/workflow/issues/2859053#comment-12140370


Entityform - "The form has become outdated." error I have an entityform that appears on a page, for some reason the form will not submit ...

// implement hook_menu

function foiagen_menu() {
  $items['node/%node/foiagen'] = array(
    'title' => 'Foia Generator',
      'description' => 'A foia generator form.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('foiagen_form', 1),
      'access callback' => TRUE,
  );
return $items;
}

// embed the form (it's an entityform).

function foiagen_form($form, &$form_state) {
  module_load_include('inc', 'entityform', 'entityform.admin');
  $entity_form_name = 'foia_generator';
  $render_estimate_form =
    entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
  $form['foiagen'] = $render_estimate_form;
  return $form;
}

function foiagen_form_validate($form, &$form_state) {
}

function foiagen_form_submit($form, &$form_state) {
}

I have tried to wrap my head around this solution but cannot figure out where, once my form is rendered, filled and the submit button pressed the 'update' occurs that makes the input void...

I have seen the comment here and tried adding

 $form['#token'] = NULL;

to my 'function foiagen_form' that does circumvent the 'The form has become outdated.' error but leads to a blank page. Indicating that perhaps something else altogether is malfunctioning.

  following direction from answer came up with this:

function foia_generator_form($form, &$form_state) {
  form_load_include($form_state, 'inc', 'entityform', 'entityform.admin');
  $entityform = entity_create('entityform', array(
    'type' => "foia_generator",
  ));
  $form = entityform_form_wrapper($entityform);
  return $form;
}

It looks like you may have a hook namespace collision with hook_form().

Although that might only be called if you're defining a node type, it's probably worth using a more specific function name for your form builder (e.g function foiagen_generator_form). Also make sure you're returning the form build array (array of elements), and not the rendered form in your form build function.


How to alter node url or toUrl function output? How do we alter what's returned from $node->url()?  or $node->toUrl()?

There are many entity reference fields that don't allow referencing more than one entity type or a custom route, such as entity queue or entity reference fields.  For this purpose, so that we can create entity queues that reference other entities other than nodes, I am attempting to create a node with the bundle "redirect", and when the node referenced on the site, it would display the link to the referenced item on a field on that entity field_path (which is a link field).

The problem is that $node->url() or $node->toUrl() is tightly integrated into the node object.  In Drupal 7 we had hook_url_outbound_alter which made this kind of thing easy.  I would like a Drupal 8 equivalent.  So that whenever a url or link to my redirect node is displayed, it is replaced with the value of field_path.  Not just that node/ redirects, but that it displays the redirect.

So how do we alter $node->toUrl() if $node->bundle() == 'redirect'?

I have found I can fix this most places on the site using two hooks:

/**
 * Implements hook_entity_view().
 *
 * Gets the output for extra fields.
 */
function mymodule_preprocess_node(&$variables) {
  if ($variables['node']->bundle() == 'redirect') {
    if (!$variables['node']->field_path->isEmpty()) {
      $redirect = $variables['node']->field_path->getValue()[0]['value'];
      $variables['url'] = $redirect;
    }
  }
}

/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {
  if (empty($variables['options']['external']) && !empty($variables['options']['entity'])) {
    $entity = $variables['options']['entity'];
    if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'redirect') {
      if ($variables['url']->getRouteName() == "entity.node.canonical" && !$entity->field_path->isEmpty()) {
        $redirect = $entity->field_path->getValue()[0]['value'];

        if ($new_url = URL::fromUri('internal:'.$redirect)) {
          $variables['url'] = $new_url;
        }
      }
    }
  }
}

But this doesn't help if someone calls the ->url() function without the link wrapping it.

Path outbound processing still exists: OutboundPathProcessorInterface, check the implementations, like path alias handling. It's a tagged service.

That said, not sure if that's the approach that I'd take, I usually implemented something like that simply by overriding the necessary node templates/preprocess.


how to dynamically add new fields to a form using ajax? I need to add the options array for a select field based on the first one
like

<?php

function lists_form_alter(&$form,&$form_state,$form_id){
    $governments=array();
  if($form_id == 'place_node_form'){
      /*$vocabularies=  taxonomy_get_vocabularies();

      foreach($vocabularies as $vocab){
          if($vocab->machine_name =='listings'){
              //
              //$_SESSION['vid']=$vocab->vid;
              break;
          }
      }*/
            $options=array();
      $g=taxonomy_get_tree(23,0,1,FALSE);
      $x=count($g);
      for($i=0;$i<$x;$i++){
                $city[$i] = taxonomy_get_children($g[$i]->tid,23);
                      $options[$g[$i+1]->tid]=$g[$i]->name;
      }
      }
                  $options[0]='choose the government';

       $form['gov']=array('#title'=>'Gov','#name'=>'governorate','#type'=>'select','#options'=>$options,
           '#suffix'=>'

'
           ,'#ajax'=>array('callback'=>'ajax_callback','event'=>'change','wrapper'=>'replace','method'=>'replace'));

isset($form_state['values']['governorate']) ? $op=taxonomy_get_children($form_state['values']['governorate'],23)
        : $op='';
$form['city']=array("#title"=>'City','#name'=>'city','#type'=>'select','#prefix' => '
',
        '#suffix' => '
',
           '#options'=> $op);

}

function ajax_callback($form_state,$form){
    $form_state['rebuild']=true;
    return $form['city'];
}

?>

what's wrong here?

You've got the parameters the wrong way round in your callback function; and you should probably take $form_state by reference if you need to change it:

function ajax_callback($form, &$form_state){
  $form_state['rebuild']=true;
  return $form['city'];
}


Modal API not displaying ajax response I am trying to use the Drupal 8 Modal API to output a link in a modal window - using the "Simple Link" approach here.

When clicking my link, I get a little animated spinner and I can see the response being returned via ajax using my browser inspector. However, no modal appears? There are no errors output to the console.

I am using a custom theme - is there some mark up I must place in the theme, to act as a container for the modal?

After some more research, I found the solution in a comment on this article - basically, every article I could find on the subject seems to have been written prior to some API changes being made, in how a dialog or modal is invoked.

An example link would be:

Show me a 500px wide modal

So, the key thing is that data-accepts attribute is replaced with data-dialog-type.


I cannot sign into my drupal site. The login page just refreshes and there are no error messages I cannot login into any account from the login page. I can get to the admin page by doing drush user-login but if I log out of admin and try logging in again, the login page just refreshes and I do not get signed into the account; no errors messages, even if I put in an incorrect username and/or password. After nuking my local repo a couple times, I found out that if I put in the wrong username and/or password or if I log in and out a bunch of times, I will not be able to sign in to any other account. The login page will just refresh.
I tried doing stack traces using debug_print_backtrace() in the UserLoginForm.php located in core/modules/user/src/form but my computer just freezes. Normally, when I actually log into an account, the console on the browser under network shows a 303 which redirects, but when I cannot login, that request is not present. I've cleared cache, cleared cookies, tried different browsers, but nothing seems to work. The watchdog log messages just say a session has been started by a user and
Notice: Undefined index: function in Drupal\Core\Database\Log->findCaller() (line 154 of /app/core/lib/Drupal/Core/Database/Log.php).
I'm making a custom theme and module if that helps. Any ideas would be greatly appreciated. Thanks.

So after failing to log in a couple times, drupal will block your ip and makes it so you can't login until some arbitrary amount of time, which explains a lot. To unblock ip addresses use drush sql-query "delete from flood" I also did not have the error messages popping up when you put in a wrong password.


Pseudo field show/hide setting per node I have created a pseudo field using hook_entity_extra_field_info() and displaying markup using hook_entity_view().

How can I create a checkbox setting in node create form so that I can show / hide this pseudo field per node?

In hook_ENTITY_TYPE_view which you use to render your pseudo field there already is the $entity available. Which in your case must be a node object. You simply can get any field value from there.

So all you need to do is to add a Drupal default checkbox/boolean field to your content type, from the UI probably, hide it from display, and then output your pseudo field depending on its value, per node.

/**
 * Implements hook_entity_extra_field_info().
 */
function MYMODULE_entity_extra_field_info() {

  $extra['node']['article']['display']['foo_bar'] = [
    'label'       => t('My pseudo field'),
    'description' => t('My pseudo field description.'),
    'weight'      => 0,
    'visible'     => TRUE,
  ];

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->bundle() == 'article') {

    // Get the choice.
    $editors_choice = $entity->field_editors_choice->first()->getValue();
    $editors_choice = isset($editors_choice['value']) ? $editors_choice['value'] : FALSE;

    // And fire accordingly.
    if ($display->getComponent('foo_bar') && $editors_choice) {
      $build['foo_bar'] = [
        '#markup' => 'This is my custom content',
      ];
    }
  }
}


Total number of nodes based on content type I have 3 content types and I want to add a section to my site that displays the total number of nodes that each content type has.

However I don't want them to display per content type, i want the total number of all 3 to appear.

So basically nodes in A + B + C = total number of nodes

Is this possible?

In your views, section "OTHER", use aggregation.

It will provide you with options like COUNT in your views fields. You then can simply use the nid field, with a content type filter, and then display the count of the nodes.


Remove Welcome message and "No front page content has been created yet." The home page of my website contains blocks and views only. Hence, I want to remove both of the following message-

Welcome to my web
No front page content has been created yet.

I tried to add following code as described here but I can still see the message Welcome to my web

unset($page['content']['system_main']['default_message']);

Both are displayed by the different code, hence you need to unset/remove both.

1. Create a separate front page template: In your theme's tempaltes folder make a duplicated of page.tpl.php and rename the dulpicate one as page--front.tpl.php. Now your all other pages will be handeled by page.tpl.php and the only front-page will be handeled by page--front.tpl.php.

2. Edit the page--front.tpl.php template: Now, as you said you are able to remove the message using the code which is in your Question, so go ahead with that.

Secondly, remove the following code from your page--front.tpl.php, which will remove the Welcome...... part.

<?php if ($title): ?>
   <h1 id="page-title">
     <?php print $title; ?>
   </h1>
<?php endif; ?>


Drupal 7 skip loading the template for ajax requests I am trying to upload an image in my template page, using jquery ajax-form submit.

And i am returning just the image name after it is uploaded in the module function.
However, i am getting the entire html as response.

In my theme's template.php, i have used the following code:

function my_theme_preprocess_page(&$vars) {
  if ( isset($_GET['ajax']) && $_GET['ajax'] == 1 ) {
        $vars['template_file'] = 'page-ajax';
  }
}

I have this code in my theme's page-ajax.tpl.php: <?php print $content; ?>

And i am passing the 'ajax=1' parameter to the module hook menu function that handles the image upload.
How can i just output the image name in ajax response, instead of the entire html.tpl.php?

How are you generating the ajax response?

If you simply want to return a string eg a file name you can just return it as plain text or as JSON using hook_menu and a callback function eg:

function mymodule_menu() {
    $items['my/custom/path'] = array(
      'page callback' => 'mymodule_callback',
    );
    return $items;
}
function mymodule_callback() {
  //Do stuff like get filename from DB.
  print 'filename.jpg';

  //to return JSON use drupal_json
  //drupal_json(array('filename' => 'filename.jpg'))
}


iframe in - rewrite results - Override the output of this field with custom text I'm trying to make a view for showing latest youtube videos in a block

I have a field called Youtube Video ID (Plain text) where I Drupal 8 stores the ID of the video...

I'm using the option of the field "Override the output of this field with custom text" in REWRITE RESULTS...

I'm doing something like this:

Like you can see.. I'm using that mark up to show a youtube video.. taking the value of the field....

the problem is that Drupal is cleaning the iframe mark up.. I think for security...

this is how Drupal render it in the website

When you configure the content type you can see a note:

Allowed HTML tags:   <big>
 <q>      <tt>

This field supports tokens.

how can I add more allowed tags?

How can I allow that HTML tag for this view?
¡Thanks!

I have been wrestling with this as well but my users want to embed google docs.  Same concept though.

I figured out the solution and it's not super complicated.  You you just need to create a 'Field Template' in the theme.

This video covers the concept with 'Node Template' but you can easily apply it to the field template.

Drupal 8 Theming - Part 11 - Displaying Fields
https://www.youtube.com/watch?v=fQ6Ypik_jsE


Repository module code completely different from downloaded file Using the Drupal Soundmanager2 module that hasn't been updated in about three years. Added a little functionality and want to submit a patch.

I think this can be done via git:

git clone --branch master http://git.drupal.org/project/soundmanager2.git

but the files shown in the tree that are in the download zip file are completely different from what's in the git repository.

Am I missing something here?

I think the master branch is still pointing to an old (probably obsolete) branch. To get the latest version, which is inline with the zip file you downloaded, you should use:

git clone --branch 7.x-2.x http://git.drupal.org/project/soundmanager2.git

Maybe you should open an issue and point them to the Moving from a master to a major version branch documentation.


Views and Workflow module I am attempting to create a view that displays Content by it's current Workflow state.

I cannot see how this is possible using the Views module combined with the Workflow module.

Can you advise?

Have you enabled the "Workflow Views" module (in the workflow 'module')?
With it you get a example "workflow summary" view with a list of all content with its current state, title and type of the content.
In views you get access to a few new fields like "current state", "previous state", ...


views exposed filter on field collection item I use views-7.x-3.3 and field_collection-7.x-1.x-dev of 2012 Jun 28.

I have a very simple content type (person) with the following fields:

name: text
surname: text
mother language: term reference [en, fr, de]
portfolio: field collection of:

website language: term reference [en, fr, de]
url: link

I can create an exposed views filter on the mother language field just fine. The drop down appears and correctly filters the nodes as expected.

When I try to create a filter on the website language field of the portfolio field collection though, it fails to filter. No results are returned unless the dropdown value is set to "all".

Is it the case that field collection fields cannot participate in views filters? Is there a solution to that?

Field collection items can perfectly participate as Views filters. The key is to use Views relationships. You can create a relationship for the portfolio field, and then in the filter specify to use that relationship. That will cause the filter to analyze the field collection's contents, as opposed to the host entity's.

For example, here I established a relationship to an image gallery collection, created a file id filter, and associated the filter with the collection. The fid filter is also exposed:


Theme hooks vs module hooks Sometimes when I try to apply a hook, just to realise it's supposed to be in a module file.

Is there a way of knowing what hooks can be implemented in a theme's template.php file, or one in a module?

Generally speaking, only alter hooks can be implemented by themes, which means hooks like hook_form_alter() and hook_menu_alter(), or in short all those hooks that are invoked through drupal_alter() in Drupal 7 and lower (ModuleHandler()::alter() or ThemeManager::alter() in Drupal 8).

Other hooks, which are invoked by module_invoke_all() (ModuleHandler::invokeAll() in Drupal 8), don't get invoked for themes simply for fact the code doesn't check if the currently enabled theme defines any hook.

  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

In Drupal 8, where the ModuleHandler class invokes hooks implemented from modules and the ThemeManager class invokes hooks implemented by themes, only the first class implements invoke() and invokeAll(). This means that in Drupal 8 theme hooks aren't invoked, by Drupal core.

This is valid for Drupal core hooks, and mostly all the hooks used by third-party modules. It is then up to a module to verify a hook is implemented by a theme too, and invoke it. This is what the Views module does.

  // Let modules modify the view just prior to rendering it.
  foreach (module_implements('views_pre_render') as $module) {
    $function = $module . '_views_pre_render';
    $function($this);
  }

  // Let the themes play too, because pre render is a very themey thing.
  foreach ($GLOBALS['base_theme_info'] as $base) {
    $function = $base->name . '_views_pre_render';
    if (function_exists($function)) {
      $function($this);
    }
  }
  $function = $GLOBALS['theme'] . '_views_pre_render';
  if (function_exists($function)) {
    $function($this);
  }

For hooks used by third-party modules, you need to check the code used to invoke them. Chances are that only alter hooks are invoked for themes, but in some cases also other hooks could be implemented by themes.
Keep in mind that in the case of themes, not all the enabled themes are checked for hook implementations, contrary to what happens with modules. Only the currently used theme and the base themes are checked, as done from the Views module.


Custom PHP code as a Panels selection rule Panels allows selection rules to be created with custom PHP code (disclaimer: I know this approach is insecure and should be avoided).

When adding PHP code as a selection rule, the helpful description states:

  Access will be granted if the following PHP code returns TRUE. Do not
  include . Note that executing incorrect PHP-code can break
  your Drupal site. All contexts will be available in the $contexts
  variable.

I made a function in a custom module to use for the selection rule:

function mymodule_selection_rule_is_location_set() {
  global $user;
  $user_fields = user_load($user->uid);
  if (isset($user_fields->field_acc_location['und']['0']['lat'])) {
    $location = $user_fields->field_acc_location['und']['0']['lat'];
  }
  if (empty($location)) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

However, when I set the selection rule as shown below, the selection rule is not triggered even when there is a value for $location and the function returns TRUE (confirmed with devel module).

Evaluates false as a selection rule even when the function returns TRUE

mymodule_selection_rule_is_location_set()

To get it to work, I had to write the selection rule like this:

Evaluates correctly

if (mymodule_selection_rule_is_location_set()) {
  return TRUE;
}

My question is why do I have to write it like the latter rather than the former?

I think the calling function which executes your PHP code would expect the RETURN true/false statement. Thus, you would need return to the calling function as returned by the called function.

return mymodule_selection_rule_is_location_set();

If you don't have return, the calling function would expect NULL and it would execute as FALSE always regardless of what is returned by the called function.


Submit handler is not called from theme function I am actualy trying to build up a dragable table, but for some reason after implementing the theme_function, my submit handler is not longer getting called.

This is what my Code actualy looks like:

function he_ministerienschalter_theme($existing, $type, $theme, $path) {
  $themes = array(
    'he_ministerienschalter_admin_form' => array(
      'render element' => 'element',
    ),
  );
  return $themes;
}

/**
  * Implements the ministerschalter admin form
  */

function he_ministerienschalter_admin_form($form, &$form_state, $form_id, $item) {

  $domainnames = he_ministerienschalter_domainselect();

  $count = 0;
  $form['ressortswitch'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#tree' => TRUE,
    '#theme' => 'he_ministerienschalter_admin_form',
  );
  foreach ($domainnames as $key => $domainname) {
      $form['ressortswitch'][$key]['domainID-'.$key] = array(
        '#type' => 'value',
        '#value' => $domainname['domain_id'],
      );
      $form['ressortswitch'][$key]['domainname-'.$key] = array(
        '#type' => 'item',
        '#title' => $domainname['sitename'],
        '#size' => 60,
        '#maxlength' => 128,
      );
      $form['ressortswitch'][$key]['domainshort-'.$key] = array(
        '#type' => 'textfield',
        '#default_value' => $domainname['sitename'],
      );
      $form['ressortswitch'][$key]['weight-'.$key] = array(
        '#type' => 'textfield',
        '#default_value' => !empty($domainname['domain_weight']) ? $domainname['domain_weight'] : '0',
        '#size' => 3,
        '#attributes' => array('class' => array('item-row-weight')),
      );
      $count++;
    }

    $form['ressortswitch']['count'] = array(
      '#type' => 'hidden',
      '#value' => $count,
    );
    $form['ressortswitch']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save Settings'),
    );

  return $form;
}

/**
  * Theme callback for the he_ministerienschalter_admin_form
  */

function theme_he_ministerienschalter_admin_form($variables) {
  $element = $variables['form'];
  drupal_add_tabledrag('ressortswitch_table', 'order', 'sibling', 'item-row-weight');
  $header = array(
    t('Domainname'),
    t('Domainshort'),
    t('Weight')
  );

  $element_items = array();

  foreach($element['ressortswitch'] as $id => $record) {
    if(is_int($id)) {
      $element_items[] = $record;
    }
  }

  $rows = array();
  foreach ($element_items as $id => $item) {
      $domainNAME[$id] = $item['domainname-'.$id];
      $domainSHORT[$id] = $item['domainshort-'.$id];
      $domainWEIGHT[$id] = $item['weight-'.$id];

    $rows[] = array(
      'data' => array(
        drupal_render($domainNAME[$id]),
        drupal_render($domainSHORT[$id]),
        drupal_render($domainWEIGHT[$id]),
      ),
      'class' => array('draggable'),
    );
  }

  $output = theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array('id' => 'ressortswitch_table'),
  ));

  $output .= drupal_render($element['ressortswitch']['submit']);

  return $output;
}

/**
  * Implements hook_form_submit
  */

function he_ministerienschalter_admin_form_submit($form, &$form_state, $item) {
  db_delete('he_ministerienschalter')
  ->execute();
  $count_domains = $form_state['values']['ressortswitch']['count'];
  $count = 0;
  // dpm($form_state);
  dpm($form_state);
  while($count < $count_domains) {
    db_insert('he_ministerienschalter')
      ->fields(array(
        'domain_id' => $form_state['values']['ressortswitch'][$count]['domainID-'.$count],
        'domain_short' => $form_state['values']['ressortswitch'][$count]['domainshort-'.$count],
        'domain_weight' => $form_state['values']['ressortswitch'][$count]['weight-'.$count]
    ))
    ->execute();
    $count++;
  }
  drupal_set_message('Eingabe gespeichert');
}

Any idea how to solve that?

I Updated my theme function like this and now it works like a charm :-)

$output .= drupal_render($element['form_id']);
$output .= drupal_render($element['form_build_id']);
$output .= drupal_render($element['form_token']);


Create a view to display the list of content created by user I want to create a view for each individual user of my site which would display the content create by that logged in user only, i.e, When a user logs in, then when he clicks a tab (i am using quicktab here) a view appears which shows all the content that this user only has created. I do not want to show this user content created by others. Is there any efficient way to do so. I am using Views3.

Thanks for your time

Yes, the easiest way to list content created by user is with Views.

Basically, create your view, with the relevant filters for content type, fields etc..

Then add a contextual filter for current user.

Click "Advanced" > "Contextual Filters"
"Add" > "Content: Author uid"
"Provide default value" > "User ID from logged in user"
Save


How to apply patches on Term Reference Tree while using Term Reference Tree module it shows me following error. I have found the PATCH for this error.

I am new to drupal. I don't know how can I apply this patch. Please help me to solve this problem. Thank you very much.

Notice: Undefined property: stdClass::$vid in i18n_taxonomy_term_name() (line 461 of /home/lawand9/public_html/law/sites/spanish.lawandmoney.info/modules/i18n-7.x-1.11/i18n/i18n_taxonomy/i18n_taxonomy.module).
    Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of /home/lawand9/public_html/law/includes/entity.inc).
    Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 350 of /home/lawand9/public_html/law/includes/entity.inc).
    Notice: Undefined property: stdClass::$vid in i18n_taxonomy_term_name() (line 461 of /home/lawand9/public_html/law/sites/spanish.lawandmoney.info/modules/i18n-7.x-1.11/i18n/i18n_taxonomy/i18n_taxonomy.module).
    PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.i18n_tsid' in 'field list': SELECT base.tid AS tid, base.vid AS vid, base.name AS name, base.description AS description, base.format AS format, base.weight AS weight, base.language AS language, base.i18n_tsid AS i18n_tsid, v.machine_name AS vocabulary_machine_name FROM {taxonomy_term_data} base INNER JOIN {taxonomy_vocabulary} v ON base.vid = v.vid WHERE (base.tid IN (:db_condition_placeholder_0)) ; Array ( [:db_condition_placeholder_0] => 1 ) in DrupalDefaultEntityController->load() (line 191 of /home/lawand9/public_html/law/includes/entity.inc).

If you would take one second and google how to apply patches, you would come across this page: https://www.drupal.org/patch/apply. It explains how to apply patches.


How can I tell Drush in which folder should a module be copied? Is there a way to make Drush download modules into a specified folder besides sites/all/modules (e.g. sites/all/contrib, sites/all/core)?

If this makes a difference, I am using Drush 4.4.

You can default this to, for example, sites/all/modules/contrib, in your .drush/drushrc.php file.

$command_specific['dl'] = array('destination' => 'sites/all/modules/contrib');

Also note that you won't be able to exclude the 'modules' part of the path, as Drupal uses this to scan for modules.

There are 6 places this file can live:

  Drupal site folder (e.g. sites/{default|example.com}/drushrc.php).
  Drupal /drush and sites/all/drush folders, or the /drush folder in the directory above the Drupal root.
  In any location, as specified by the --config (-c) option.
  User's .drush folder (i.e. ~/.drush/drushrc.php).
  System wide configuration folder (e.g. /etc/drush/drushrc.php).
  Drush installation folder.


How to have one stylesheet for logged in users and another one for anonymous users? Anyone know how to have one CSS stylesheet for logged in users and another for anonymous users?

The template_preprocess_html() preprocess function adds a 'logged-in' or 'not-logged-in' class to the classes array.
These classes get printed in the html.tpl.php template on the body tag.

So you should be able to target anything in your css for logged in or logged out users by using those classes. For example:

.sharing-block {
  top: 0px;
}
.logged-in .sharing-block {
  top: 25px;
}

Something like that should work without needing to worry about conditionally applied stylesheets or anything like that.


Preprocess taxonomy for a custom template file In Drupal 6, I am customizing a view where I am trying to make the taxonomy terms work in all the page template files.

This is the code in the template.php file.

function getTermsName($taxonomy_id) {
  $terms = taxonomy_get_term($taxonomy_id);
  return $terms->name;
}

This is the code in the custom page template file.

$taxonomy_id = 'term id you got';
echo getTermsName($taxonomy_id);

Nothing happens.

I am quite bad at this; I hope in a very simple solution.

EDIT

With Boriana we found out that the mythemename_preprocess function is not working not taking effect in my drupal. If anyone has idea why, that will be the key to this problem.

If you're trying to use this in your page template files, then you should put your template.php code inside the yourtheme_preprocess_page(&$vars) function.  That's the one that will get called before your page template file, and it can "communicate" its results to the template file by putting them in the $vars variable which was passed to it by reference.

So here's an idea of how you can improve your code:

In template.php:

function mytheme_preprocess_page(&$vars) {
  $term = taxonomy_get_term($taxonomy_id);
  $vars['term_name'] = $terms->name;     // Store anything you want to use later in $vars
}

In page.tpl:

<?php print $term_name; ?>

Let me know if that helps you get closer!

============================ EDIT =============

The variables set in the hook_preprocess_page() function are only available in your page.tpl files.  If you're trying to get to these variables in your view templates, you'll have to instead use a views pre-processing function, such as mytheme_preprocess_views_view(&$vars)


Synchronize with only published nodes We are going to have a "staging" server where all edits will be made. We are going to push to the cloud production server with Drush sync. I know there is a way to exclude tables, but is there a way to only push nodes and field data from published nodes/revisions?

Viewing all the options listed on https://drushcommands.com/drush-8x/sql/sql-sync for drush sql-sync command, it seems you can apply limitations on a table level only. So you might want to build a custom code for syncing data as there is no way to push nodes and field data using Drush sync per their published statuses.


How do I check if an image field is empty in a template file? I am trying to check if the user_picture field is empty using the twig template, but I am not able to do this.

I tried lots of ways:-

{% if node.user_picture.value %}
{% if node.user_picture.entity %}
{% if content.user_picture.value %}
{% if content.user_picture|render.entity %}
{% if content.user_picture|render %}

Sample of code:

  {% if node.user_picture.value %}

User-picture 02

    {{ user_picture }}
  {% else %}

Anymonus-picture 02

  {% endif %}

Use the method isEmpty() on the image field:

  {% if node.field_image.isempty %}

Field "field_image" is empty.

  {% endif %}

Although in this case you might need to check the user entity of the node author:

  {% if node.uid.entity.user_picture.isempty %}

Picture of the node author is empty.

  {% endif %}


How to insert javascript in a block? I would like to insert a JavaScript code in block body but I cannot save it, after 2 or 3 minutes it stop (shows a message The connection has timed out). I want to add statcounter code to a block.

EDIT 1:

I can add JavaScript in local-host but I can't do in server (Linux server, VPS cPanel)

Create your own text filter which just does nothing which means it allows really "all" input without any filtering.

Please make sure that you allow only trusted people to use this filter since it would be easy to add XSS code.


Hide the shortcut toolbar How can I hide the shortcut toolbar in Drupal 8.6? I need the very top menu gone (the green part highlighted in screenshot).

It looks like you are using adminimal as admin theme, so go to themes/contrib/adminimal_theme/css/adminimal.css and paste this code in the bottom.

.toolbar-icon.toolbar-item {
  display: none !important;
}

It should do the trick.


PDOException when setting field value in node presave I have a hook_node_presave implementation to set the value of a node field based on one of the user-entered values.

The code for it looks like this:

function er_pr_node_presave($node) {
  .....
  foreach($nameResult as $row) {
    $node->field_co_pi[LANGUAGE_NONE][$i]['value'] = intval($row->entity_id);
  }

  dpm($node);
}

With the dpm function I can see the values in the node, and the correct value is set to the field_co_pi field. However, the placeholder field doesn't get set when the insert query for that custom field is ran, resulting in a PDOException:

Sounds like you should be setting target_id instead:

foreach ($nameResult as $row) {
  $node->field_co_pi[LANGUAGE_NONE][$i]['target_id'] = intval($row->entity_id);
}

Note that not all fields have the same data column (such as 'value'). Reference fields have target_id which holds the referenced entity id.

Aside from that, just make sure that it has a value before setting, or you will get the same error again.

You redacted other parts of the code, so, I can't see if you set $i or not. Are you incrementing that per loop with $i++? I just assumed it is a multivalued field since you are doing a foreach instead of setting [0] directly.


How to assign credit hours to user account once the content is marked completed by admin I have a custom content type "course" and it has an entity reference to username. ( the username is basically an instructor who is suppose to teach the course )

I have created a field "Course Completed" in course content type and admin changes it to "completed" manually. The content type also has a filed "Number of hours"

What i need is, when the node is marked as completed, the "Number of hours" is taken from node and added  to user account.  ( i can create a field using profile2 and name it as "user credit hours")

How would i do this? is there any module which will work similar to what is needed  ?

thanks

i managed to do it with rules and adding some action code in a custom module.

After adding a condition, i had a make a custom action and then i was able to add that action in to the created rule.

You can send value to your custom action and then load user and update its field.

$user = user_load($user_trainer_id);
$obj = entity_metadata_wrapper('user', $user);
$obj->field_earned_credit_hours = $new_custom_value;
$obj->save();


Multilingual site, always use language path prefix (no bare URLs) I have a Drupal 8 site with two languages, Japanese (default language) and English.

By default, the default language pages are available at both / and /ja.

For example, /about and /ja/about both go to the Japanese "about" page.

I want to get Drupal to force the path prefix so that the URL is always shown as /ja/about and never just /about.

Interface text language detection settings

URL (path prefix, english: en, Japanese: ja)
Selected language (Japanese)

How can I do this?

For Drupal 7: see this question

Here the steps:

Install Redirect module.
Enable the module /admin/modules
Go to admin page /admin/config/search/redirect/settings.
Ensure Enforce clean and canonical URLs is checked.


Export menu to html? The project I'm working on has a specific requirement where I need to export the main menu as an HTML file. I figured the simplest way to do it would be using views but I found that views doesn't interact with the menu system.

I looked up the menu_import module to see how it exports menus to JSON files to see if I could rewrite the output to be HTML but haven't really gotten too far with that.

Any ideas how I can approach this?

Use the next code:

$tree = menu_tree_all_data('main-menu');
$menu_html = render(menu_tree_output($tree));
file_put_contents('myfile.txt', $menu_html);

Source: Programmatically load a menu.

EDIT
If you want to make it downloadable you can add next code to your page or submit callback:

// Get menu tree.
$tree = menu_tree_all_data('main-menu');
$menu_html = render(menu_tree_output($tree));

// Download menu txt file.
$filename = "menu.txt";
drupal_add_http_header('Content-Type', 'text/plain; charset=utf-8');
drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
drupal_send_headers();
echo $menu_html;
drupal_exit();


How to authenticate a user which exists in an external site? I would like to authenticate a user which exists in an external site.

Here is a use case:

In Drupal, user enters his username and password and hits submit.
Drupal tries to find that user in it's system and does not find him. At this point an error message is still premature.
Drupal then runs a custom function which does a REST call to an external site.  The REST call validates the username and password.
If the username and password pair is valid, the REST call returns a success code.
I then log him in.

Is this possible? If so, how? What hooks do I need to implement?  What method should I call to log a person in?

I can programmatically log a user in via

$form_state['uid'] = <user_id>;
user_login_submit(array(), $form_state);

but user_id needs to exists in Drupal for this piece of code to work.

I am using Drupal 7.

Thanks.

Based off of your comments, it sounds like you have the basic procedure down: hook_form_alter the user_login form, and use your own validation.

If you take a look at user_login_default_validators, I think your problem is that you need to swap out user_login_authenticate_validate with your own, but still get the form back into the same state.

I think your best bet is to do your RESTful authentication in a validator, and then set $form_state['uid'] to a valid user in the system.

My suggestion is to create a single user that you map all of your REST logins to, and use this as $form_state['uid'].  This way, you still can use the permission system across your site.  To get them logged in, you can just do a user_load with the $uid of your special user.

I am not positive, though, if having all of these users will cause any problems with sessions.  I have only done something similar with Drupal 6 and each remote user got their own account in Drupal.


Localized Taxonomy terms in a View Localized taxonomy terms are not displayed in a View. Only the default language term is shown. I solved this issue writing a small module according to this article.

Perfect. But in one View i have two fields: term ID and Global PHP code. My question is: what needs to be changed in the Global PHP code below to have the localized terms displayed?

$term = taxonomy_term_load($data->tid);
//print l($term->name,"voices", array('query' => array('type' => $term->tid)));
print l($term->name,"voices", array('query' => array('f[0]' => 'field_production_type_:'.$term->tid), 'attributes' => array('class' => array($term->name))));

/*
  $url = drupal_get_path_alias('taxonomy/term/'. $term->tid);
  $url_part = explode('/', $url);
  print l($term->name ,"voices/voiceovers/".$url_part[1], array('attributes' => array('class' => array($term->name))));
*/

From the question details provided, I'm not sure if the i18nviews module is enabled (make sure it is).

Probably the best option might be to use i18n_taxonomy_term_get_translation as explained also in the questions:

How to get the translated term name by tid?.
how to get the translated taxonomy term programmatically?

Something else you may want to try to get the terms translated, is to use the setting (for Translation mode) Translate. Different terms will be allowed for each language and they can be translated (instead of 'Localize'). This setting can be found within admin/structure/taxonomy/<YourTaxonomy>/edit.


Displaying Media as a field in Views? I am trying to get Views to display files I have uploaded to my server using the Media module.

My end-goal is to display the 5 most recently uploaded pictures (from any album) in a slideshow on the front page (using Views Slideshow).

My website as a whole will be my personal photography-website when it's complete. The way I have everything set up so far is: I created a new content type for my pictures called Photos. Next, I create a new piece of that custom content and upload pictures to it. The organization structure is that, each new piece of Photos content behaves like an album--containing a set of images pertaining to it's title.

For example, if I wanted an album specifically dedicated to landscapes, I would create a new Photos piece of content, and upload all my images of landscapes to it.

The problem I have right now is, I can get Views to display my custom content type and scroll through it, but because each individual picture is wrapped inside a Photos content, the View will display every single image in that album 'per-slide'. How do I get Views to only display the five most recently uploaded Media files? (As opposed to what it's doing right now, displaying the five most recently added Photos albums.)

(Using Drupal 7)

In your field in your view, if you uncheck the option "Display all values in the same row" in the "Multiple field settings", each new image in any photo piece of content will be considered as a row. You then will be able to show only the last 5 images instead of the last 5 photo albums.


Date input format problem I need to import a large dataset (over 300,000 records) into a Drupal 8 site. I have figured out how to do this with feeds on a small test dataset.

The dates in the records are in the format June 8, 2018. I do not see a way to use a Drupal 8 Date field to input dates in this format.

I need to be able to create a view that displays records based on a date range.

What is the best way to get the data into Drupal in a format that a view can use? Would it be to maybe use computed field to transform the data while it is being imported? Or would it be better to maybe execute a SQL query after the data is imported?

Rather than using Feeds, I suggest using the core Migrate module.  There is also a core plugin for converting dates during migration, FormatDate.  This will allow you do specific the input format and the output format.  I believe, this process configuration would work in your case:

process:
  field_date:
    plugin: format_date
    from_format: 'F j, Y'
    to_format: 'Y-m-d'
    source: event_date

If Feeds is your preferred method, then you can try the Feeds Tamper module.  Based on the plugin list for Drupal 8, I think you would need to do a "String to Unix timestamp" tamper on the field, followed by a "Unix timestamp to Date" tamper, using 'Y-m-d' as the format string. However, I haven't used Feeds and Feeds Tamper in a long time, and would typically write custom tampers for something like this.


How do I unpublish a user's content with rules? How can I unpublish a certain user's content when a certain rule triggers?

The configuration would look like this:

Build a view that, when given a user ID as input, lists all the
nodes that that user has posted.
Use view style bulk operations, and select the action unpublished
node.
Set up a rule that triggers on user updates. (Is there one? I'm not
sure...) As condition, compare the roles before and after user save
to see if anything should be unpublished. As an action, let it call
the view from.

Use this idea you can do that


How can I update/revert a feature which includes page manager and mini panel components that is stuck as overriden? I have a feature which includes page manager and mini panel components that is stuck as overriden?

I have tried reverting and updating the feature both from the web ui and also from drush to no effect.  I don't get any error messages but after clearing the cache twice the feature is still marked as overriden.

Generating a diff reveals about twelve differences that look like this:
+'new-6' => array(
-'new-1' => array(
+'pid' => 'new-6',
-'pid' => 'new-1',

I assume this is the result of the site on which I created the feature having a lot more content already in place than the site on which I have installed the feature, which has no other content.

I also tried removing the offending parts (those related to page manager and panels) from the feature, updating the feature, and then adding them back onto the feature using the web ui, but it still displays as overriden.

I found this thread but there wasn't any particularly helpful information:
http://drupal.org/node/744450

Any ideas about how I can update or revert this feature?

Attempting to answer the question:

You should be able to simply re-export the feature to update the pane identifiers in code.

Background info:

There are two parts to this problem.
First of all, features uses a different way of determining whether or not something is overridden, than ctools does. So Ctools consider the state to be "in code", but features, "overridden".

Secondly, the way panes are identified have recently changed. The change initially came about to solve a particular bug, but now causes other problems instead, namely the 'new-X' "overrides".

There are several different patches in the Panels queue that all have different ideas on how this problem should be solved. Currently, I'm afraid to say that I believe you can't do a great deal about this. The current behavior simply isn't optimal.

You can read more in this issue, and the ones that are linked to.


Set permanent status for managed_file in theme settings I'm creating some Drupal 8 theme and I need some additional settings for it. So, I have to add some managed_file field in theme settings.

I have theme-settings.php file where I define this field and I want to make this file permanent.

There is what I have in theme-settings.php so far:

<?php

/**
 * @file
 * Provides an additional config form for theme settings.
 */

use Drupal\Core\Form\FormStateInterface;

// Set theme name to use in the key values.
$theme_name = \Drupal::theme()->getActiveTheme()->getName();

/**
 * Implements hook_form_system_theme_settings_alter().
 *
 * Form override for theme settings.
 */
function onion_form_system_theme_settings_alter(array &$form, FormStateInterface $form_state) {
  $form['options_settings'] = [
    '#type' => 'fieldset',
    '#title' => t('Theme Specific Settings'),
  ];

  // Main navigation logo
  $form['options_settings']['menu_logo'] = [
    '#title' => t('Menu Logo'),
    '#type' => 'managed_file',
    '#default_value' => theme_get_setting('menu_logo'),
    '#upload_location' => 'public://',
    '#description' => t('Logo below main navigation. Available extensions (.gif .png .jpg .jpeg)'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg')
    ),
  ];

  $form['#submit'][] = '_onion_form_system_theme_settings_submit';
}

function _onion_form_system_theme_settings_submit(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {
  $menu_logo_id = $form_state['values']['options_settings']['menu_logo'];
  $menu_logo_file = \Drupal\file\Entity\File::load($menu_logo_id);

  // set status to permanent so that its not deleted
  $menu_logo_file->setPermanent();
  $menu_logo_file->save();
}

But I'm getting this warning:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function '_onion_form_system_theme_settings_submit' not found or invalid function name in Drupal\Core\Form\FormSubmitter->executeSubmitHandlers() (line 111 of core/lib/Drupal/Core/Form/FormSubmitter.php).

What I'm doing wrong there and what is the best and right way to set file permanent?

I think you just need to adjust your submission handler; don't include the fieldset "options_settings". I use the getValue() method and pass it an array of values, the form key and the index of its value.

  if ($file_id = $form_state->getValue(['header_background', '0'])) {
    $file = \Drupal::entityTypeManager()->getStorage('file')->load($file_id);
    $file->setPermanent();
    $file->save();
  }


How to handle hook_node_validate? I am using some contirb module and in which hook_node_validate is used. I am overriding the function passed in hook by running CUSTOM_MODULE_node_validate. But the contrib module validate also keeps running, is there any way that I can stop it running and let only mine one to run?

function CUSTOM_MODULE_node_validate($node) {

  $nodep = 'object' == gettype($node);
  $isrelevantp = _anonymous_publishing_relevantp($node, $nodep);
  if ($isrelevantp) {
    custom_anonymous_publishing_cl_content_validate($node); // function replaced with my custom for validation
  }

}

function custom_anonymous_publishing_cl_content_validate($node){
  ..........
}

ALREADY RUNNING IN MODULE:

/**
 * Implements hook_node_validate().
 *
 * The validate function will handle the honeyfield.
 */
function anonymous_publishing_cl_node_validate($node) {
  $nodep = 'object' == gettype($node);
  $isrelevantp = _anonymous_publishing_relevantp($node, $nodep);
  if ($isrelevantp) {
    _anonymous_publishing_cl_content_validate($node);
  }
}

function _anonymous_publishing_cl_content_validate($node){
  .......
}

You can remove a module's implementation of a hook like so:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_validate' && isset($implementations['anonymous_publishing_cl'])) {
    unset($implementations['anonymous_publishing_cl']);
  }
}


Where does Drupal 7 clear my custom set cookies and how do I stop this? I have parts of my website that are not controlled by drupal that set cookies.

When I access a drupal-run page, my cookies get cleared. I tried to investigate which script does this by placing print_r($_COOKIE) all over the place in html.tpl.php, but no luck.

Anybody know whats happening here and how I could set my own custom cookies with PHP in drupal template files?

cheers

Please find more about setting cookies using php setcookie function.

As explained in above link, please look into third and fourth params in above function

Path

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

Domain

The domain that the cookie is available to. Setting the domain to 'www.example.com' will make the cookie available in the www subdomain and higher subdomains. Cookies available to a lower domain, such as 'example.com' will be available to higher subdomains, such as 'www.example.com'. Older browsers still implementing the deprecated » RFC 2109 may require a leading . to match all subdomains.

Please check your code where you are setting cookies matches Drupal Site Domain name and Path where you are trying to access or print them.

You can set cookies in Drupal using user_cookie_save function.

For Example

user_cookie_save(array('key'=>'value'));
print $_COOKIE['Drupal_visitor_key']; //outputs value


template.php hook to add variable to view I'm trying to include the total count of a given node type into a view tpl.php file. I would like to set this variable in the template.php file, so that it is available in the tpl.php file (that way I also don't have sql queries gumming up my template files, which I'm trying to avoid.)

I'm trying to set them the variable with template_preprocess_views_view, but the reference variable never seems to be getting updated. I did some sleuthing and threw in some dpm statements, one in the preprocess function, one in the template, and the result looks like this:

template
preprocess views_view
preprocess_views_view__home_image

(The thrid line prints out the preprocess function with the view name attatached)

So it looks like the issue is the template is being called before my preprocess functions, which means the variable hasn't been updated it yet, but is that correct? Shouldn't the preprocess function be called BEFORE the template is called? Is there another hook that I can use to add a variable to views-view-fields.tpl.php?

I think you want to use views hooks, not template preprocess functions. The views query will be run before the template is processed. You can find a list of views hooks here: https://api.drupal.org/api/views/views.api.php/group/views_hooks/7.x-3.x

and from that link, and alex.designworks the hook firing order:

- hook_views_pre_view
 - hook_views_pre_build
 - hook_views_post_build
 - hook_views_pre_execute
 - hook_views_post_execute
 - hook_views_pre_render
 - hook_views_post_render


Unique form per user with custom form class Not sure if this is a related/duplicate of Generate unique form ID based on context

I am hoping I can render a unique form per user with the Form API using a custom form class.

What I've seen with \Drupal::formBuilder()->getForm(), you must provide your Form::class and this does not allow for something like:

public function getFormId() {

  $userID = \Drupal::currentUser()->id();
  $userFormID = 'form_settings' . $userID;
  return $userFormID;

}

and returns an invalid form with \Drupal::formBuilder()->getForm().

Ultimately trying to render a unique form via hook_preprocess_page() for the user to interact with.

An idea of what I have so far is a simple form with two submit items.

MYMODULE\src\Form\Form.php:

public function buildForm(array $form, FormStateInterface $form_state) {

  $config = \Drupal::config('MYMODULE.MYMODULE_settings');

  $form['description'] = [
    '#type' => 'item',
    '#markup' => $messageMarkup,
  ];

  $form['time'] = [
    '#type' => 'hidden',
    '#default_value' => time(),
  ];

  $form['form_delay'] = [
    '#type' => 'submit',
    '#value' => $this->t('Remind Me'),
    '#submit' => ['::submitFormDelay'],
  ];

  $form['form_ignore'] = [
    '#type' => 'submit',
    '#value' => $this->t('Ignore'),
    '#submit' => ['::submitFormIgnore'],
  ];

  return $form;

}

public function submitFormDelay(array &$form, FormStateInterface $form_state) {

  $values = $form_state->getValues();

  $this->configFactory->getEditable('MYMODULE.MYMODULE_settings')
    ->set('time', $values['time'])
    ->save();

  parent::submitForm($form, $form_state);

}

public function submitFormIgnore(array &$form, FormStateInterface $form_state) {

  $this->configFactory->getEditable('MYMODULE.MYMODULE_settings')
    ->set('time', NULL)
    ->save();

  parent::submitForm($form, $form_state);

}

Then grabbing the time value to see if I should show the form

MYMODULE.module:

function MYMODULE_preprocess_page(&$variables) {

  $config = \Drupal::config('MYMODULE.MYMODULE_settings');

  // Comes from another form controller in the module.
  $reminderDelay = $otherFormConfig->get('reminder_delay');

  $timeAtInteraction = $config->get('time') ?: NULL;

  $timeForm = \Drupal::formBuilder()
    ->getForm(\Drupal\my_module\Form\Form::class);

  if ($timeAtInteraction != NULL) {

    if ($timeAtInteraction < (time() - $reminderDelay)) {
      // Provide our form to page.html.twig.
      $variables['timeForm'] = $timeForm;
    }

  }

}

The form works, but of course, a single user sets it for everyone. I'd like the form/values to be unique per user.

Is it possible using the Form API?

(Working on cache contexts as suggested below, but not included above.)

Your updated post shows the issue. The issue here isn't the form, it's the underlying storage method. You are using configuration, which is for site configuration, ie configure how the site as a whole works. But you want to save values per user, not for the whole site.

What you are looking for is having a form used by all users, saving the submitted values for the user, rather than for the site.

I would suggest using the user.data service. This service lets you save data for users. You can user UserData::set() to set values, and UserData::get() to get values. Get the values in the form definition to get the default value, and set the values in the submit handlers to update them with the current values.

As a side note, if you were creating a form for configuration (which you're not), you would want to extend ConfigFormBase, which it doesn't appear you were doing, based on your code.


Hook on product page view in Drupal commerce I want to run page view event from tracking with Google Analytics/piwik on Drupal commerce using my own Module.

Which hook can i use in Drupal commerce to run my own code? I just need to find the best hook that is called when page view is fired for the product.

Since product displays are nodes, hook_node_view() is what you're looking for.


Why a successful migration is showing (0 created, 0 updated, 0 failed, 0 ignored)? I have written a custom Migration tp import redirects (D7 -> D7).

Everything is working fine. Imports were successful, rollbacks are working fine etc.

However, I am getting Processed XXXX (0 created, 0 updated, 0 failed, 0 ignored) in XX seconds (XXXXX/min) message after import.

Why is not showing the number of items created?

Is there a method in destination plugin or migration where I need to return this count or return TRUE/FALSE for each row processed or something like that?

Got answer!!

I missed the following code from the abstract class MigrateDestination:

/**
 * Maintain stats on the number of destination objects created or updated.
 *
 * @var int
 */
protected $numCreated = 0;
public function getCreated() {
  return $this->numCreated;
}
protected $numUpdated = 0;
public function getUpdated() {
  return $this->numUpdated;
}

These variables need to be updated during the import process and need to be defined/updated in class that is extending the MigrateDestination.


How can I make a node like template for a vocabulary? I have a taxonomy where I want to theme the term pages.

I only want to theme the terms pages in this taxonomy.

No matter what I do I can't see to get it to show a template file that I can then further customise.

I have a node page at /name
then I have the terms of the taxonomy using the path pattern /name/term_name

Can anyone help me figure this out, it seems strangely difficult. To the point where I am begining to wonder if some module might be derailing me.

From what I understand I should be about to make a template named something "taxonomy-term--myTaxonomy_name.tpl.php" but I can't seem to dislodge the default term view. Even with many cache clearings.

Enable the Taxonomy term Views if you haven't already, and look into theme suggestions there.

It seems you have views-view--taxonomy-term--page.tpl.php available where you can add some logic that would apply to only a certain Vocabulary.

You can also Clone the Taxonomy term Views twice, Filter to only certain Vocabulary in one Views, and to all the rest in the other Views, then use the template in the first Views for special styles.

You can use the Taxonomy Views Integrator module to assign different Views to output different term pages.


Difference between calling a service method in drupal 8 I want to know what difference does it make when i call a service this way :

$service = \Drupal::service('myservice.method');
$service->methodNameInService();

or this way (Dependency Injecton)

 public function __construct(MyService $myService) {
+    $this->myService = $myService;
   }

public function test() {
    // Call function from service
    $this->myService->methodNameInService();

}

Is this better for performance or is it just only the right way and has it zero effect on performance or something else?

Dependency Injection has several advantages when you try to create test for your code, and follow the Single Responsibility Principle.

Really, the second reason is a consequence than the first: "The code is testeable because follow the SRP"

Furthermore, IDEs can recognize better the class type (and create autocompletes, f.e.) if the class is defined using DI. In a normal IDE, $service defined in $service = \Drupal::service('myservice.method'); has a unknown class.

In some places you cannot use DI (fe. in a .module) and you need to use the static load.


Why can I choose the widget for grouped filters, but not exposed? When I create a view (block) and create an exposed filter I have the choice of a Filter type to expose between

Single filter and
Grouped filters

If I choose the Grouped filters I am presented with an option to chose the Widget type

Radios or
Select

But if I chose the default Filter type the form lacks the Widget type option.
I cannot think of any reason why the regular exposed filters shouldn't have this widget type option to chose from.
Can anyone tell me ...

Is there a reason for this?
Is there any patch that I didn't find until now that fixes this/add's the feature?

FYI:
There is a hard coded switch in the Drupal core which automatically changes the widget type from checkboxes/radios to select based on the number of options regardless of the Widget type settings in the views form (1-4 options: radios, 5+: select). That issue is patched here: Grouped exposed filter with "Allow multiple selections" ignores widget setting
Edit
I don't want the alpha version of Better Exposed Filters module like suggested by some.

I can see two possible solutions to this problem:

Solution 1: Better Exposed Filters

Install the Better Exposed Filters module. There are over 31,227 sites using it at the moment. Don't let the fact that it is in alpha hold you back unless your organization has a policy preventing you from using alpha releases.

Solution 2: Custom Code

If you cannot use Better Exposed Filters for some reason, then write a hook_form_FORM_ID_alter() to modify your views exposed form the way you want.

Sample code

Create a hook_form_FORM_ID_alter() in a custom module. In the example below, the module name is custom_general.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_general_form_views_exposed_form_alter(
  &$form,
  FormStateInterface $form_state,
  $form_id
) {
  $view_data = $form_state->getStorage('view');

  // Content administration.
  if ($view_data['view']->id() === 'VIEW-ID') {
    // Analyze the structure of your form with kint().
    // Say, the field that matters to you is "field_foobar".
    // kint($form); exit;

    if (isset($form['field_foobar']) {
      $form['field_foobar']['#type'] = 'select';
      $form['field_foobar']['#multiple'] = FALSE;
      $form['field_foobar']['#size'] = 1;
      // TODO: Do other things as necessary.
    }
  }
}


Fatal error on content save I recently set up a local version of a remote site. The remote site is allowing me to create content fine, but for some reason the local version is throwing the following error upon save:

Drupal\Core\Entity\EntityStorageException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')) ORDER BY users_field_data_2.name ASC' at line 4: SELECT base_table.uid AS uid, base_table.uid AS base_table_uid, users_field_data_2.name AS name FROM {users} base_table INNER JOIN {users_field_data} users_field_data ON users_field_data.uid = base_table.uid INNER JOIN {user__roles} user__roles ON user__roles.entity_id = base_table.uid LEFT JOIN {users_field_data} users_field_data_2 ON users_field_data_2.uid = base_table.uid WHERE (users_field_data.status = :db_condition_placeholder_0) AND (user__roles.roles_target_id IN ()) ORDER BY users_field_data_2.name ASC; Array ( [:db_condition_placeholder_0] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 770 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

This error also crops up on some admin pages, which seems to be related: Warning: Invalid argument supplied for foreach() in Drupal\Core\Database\Query\Condition->compile() (line 227 of core/lib/Drupal/Core/Database/Query/Condition.php).

I've done a handful of updates to the site since creating the local version but haven't tried creating new content until now, so it's hard to tell what started causing the error. Any suggestions on how to move forward with diagnosing this?

I realized that it must have been a database issue since the live and local sites were in sync except for some module installs -- same with the code. I pulled the live database and imported it into local and re-installed the modules one at a time. Everything is now working fine. All that I can figure is that there was an installation error somewhere along the way that didn't want to show itself.


Field Validation: 18 Years or Older I am using the Field Validation module to validate a date field that will contain a user's birthday. I want to make sure the person is 18 years of age or older. Here are the settings I was thinking of using in my validation rule. Are these correct?

Column: value

Minimum Date: now - 18 year

Depending on your requirements, Field Validation can be a good approach.  It's simple to set up, but one potential issue is that if this field is something that the user can edit, they can easily modify their birthday if the form submission is rejected.

Often this is OK, but for my site I needed to actually block users who were under 18, so I did the following.  I have a required date field, birthday, on the user registration form.

Then, I added a computed field, age, to calculate the age based on the value of the date field, birthday.  For sample PHP, you can see this Stack Overflow answer.  This is a way that you can take into account leap years, etc.

Then, I added a rule:

Event After saving a new user account

Condition Data to compare: Age less than 18.

Actions Block user

The advantage of doing it this way is that if a user registers with a birthday under 18, their e-mail address will be blocked from registering again.  Of course, this may or may not be necessary for your case, but I'm just putting it out there because other sites may have such a requirement.


Enable drupal_add_tabledrag on dynamically added rows I have used drupal_add_tabledrag to get Drupals sorting feature for a table, however, I cannot find any function to add the dragging feature to <tr> dynamically added with JavaScript to this table.

Does anyone know function Drupal provides to do this, or how you are supposed to do it?

In case anyone else stumbles across this, because of how Drupal handles forms, rows should be added in an AJAX callback, and the table should be replaced with the newly themed table. There are plenty of examples of adding new fields to a form using ajax.

If for some reason you are using the tabledrag feature outside of the form API (I don't know why you would), here is a quick method I wrote to add a row to a table, and make it draggable if the table is:

(function($){
    $.fn.addTableRow = function(row){
        // We can use this later to see if the row has been added to the table yet
        var added = false;

        // Get the ID of the table
        var tid = $(this).attr('id');

        // See if the table is set as a tableDrag table
        if(typeof Drupal.tableDrag[tid] != 'undefined'){

            // initialize order variable
            var order = false;

            // Set some variables for easier access
            var tableDrag = Drupal.tableDrag[tid];
            var settings = tableDrag.tableSettings;

            // Loop through the classes in the settings for the table
            for(var aClass in settings){

                // Loop through the settings for the class
                for(var i in settings[aClass]){

                    // check which action the class uses, we could add the other actions
                    // here if we are worried about heirarchy or matching
                    switch(settings[aClass][i].action){
                        case 'order':

                            // if this class is used for ordering, assign it to order
                            order = aClass;
                            break;
                    }
                }
            }

            if(order){

                // find the max weight currently avaiable in the table
                var max = $(this).find('td.'+order).sort(function (a, b) {
                    return +a.value - +b.value;
                }).last().val();

                // Make sure the row has the draggable class
                row.addClass('draggable');

                // Add the row to the table, we don't do this earlier so that if
                // there is a value set in the weight field it is not included in the max
                // This could be done earlier, and setting the value could be ommitted
                // if you wanted to add the row to a specific locaiton in the table
                added = $(this).append(row);

                // Set the value of the order field to max+1
                $('.'+order, row).val(max+1);

                // Add the row so that tableDrag knows about it and can run it's
                // own hooks accordingly
                tableDrag.rowObject = new tableDrag.row(row);
                tableDrag.makeDraggable(row);
            }
        }

        // If the row wasn't added, order handling isn't used, just add it to the table.
        if(!added) $(this).append(row);
    }
})(jQuery);

Pretty straight forward usage:

var newRow = $('
'+
                'Column 1	'+
                'Column 2<input class="sort-order" type="hidden" value="1"/>	'+
                '
');

$('#my_table').addTableRow(newRow);


How to show different Views for the same URL with contextual filters I have 1 View with contextual filter: /catalog/%
% - is taxonomy term and it can be several terms (I use them for Porducts groups) like: Phones, Accesoiries, Tablets, etc.
So, when Views get URL with Phones argument it show all its stuff on /catalog/phones page.

Problem is, that I also want to have another Views for Tablets, which should have the same address with contextual filters: /catalog/%. It should show Tablets staff after getting Tablets as arguments.

I can not use only 1 Views for both product categories, because Phones and tablets will have different set of fields to show.

Right now only 1 Views is shown. Second is empty.
How to fix it?

This can be done via a zero-coding solution using Page Manager (CTools), Views Content Panes (CTools) and Panels.

Delete your current view as we want to re-use its path.
Install the three modules.
Create a view as follows:

Create a view of type content (nodes) that shows content of your product type. Add a relationship to the 'taxonomy terms on node' and set it to your 'catalog' vocabulary.

Add a contextual filter of 'Taxonomy term name.' It will automatically select the relationship of 'term'. Hide the view when the filter value is not available.

Now add two 'Content pane' displays to this view.

Content pane 1: This is the view that will show tablets only. Click on 'edit' next to argument input in 'Pane setting' column. Select 'from context', and for the required context, select Taxonomy term->name.

Just above 'argument input' is a setting for 'Category'. Set it to something meaningful, such as 'View Panes - Catalog'.

This first pane will show 'tablets', so add fields that you want on this pane, and change its display Name to Tablets.

Content pane 2: Duplicate pane 1 exactly. It will show all the other terms, so alter the fields and display name.

Add a custom page at admin/structure/pages/add

Set it's path to : catalog/%term

During the wizard setup it will ask you to define the arguments (%term in our case). Set it to term name and limit to vocabulary 'Catalog' so that it looks like this:

Basically what we have done is to tell page manager what the argument %term represents, namely a taxonomy term that belongs to vocabulary 'catalog'.

When selecting a panel layout select single column.

Eventually you will get to the screen where you can add content to the single panel. Add content, and select 'View Panes - Catalog' (remember we defined a meaningful name for the category of our view panes. This is it). This will further display two content panes. You select the content pane you added first, ie the one to show tablets.

Now we need to limit it to only show for terms of type tablet. Select selection rules for your variant, and 'Taxonomy Term.'

Set it up so that it looks like this:

Now update and save your page and you can test that for the path that has an argument of tablet, it will show the view.

Now you need to add a second variant to this panel. To do this you can clone the first variant.

And all that remains now is for you to change this second panel variant slightly.

First, you need to remove the selection rule. As this is a catch-all variant, we do not need a selection rule at all.

Second, you need to remove the view from the panel pane single-column content, and replace it with the second pane that you added.

Now update and save. Make sure that the two variants are in the order: top variant has a selection rule and shows first view pane, and the second variant does not have a selection rule and shows second view pane. Page Variants are selected from top to bottom, with the first variant that matches being used.


Using php command to pass custom php.ini values into drush phar I'm struggling with adding php values into drush.phar. Last time I installed drush I used composer and for that method I could add the php.ini values into the drush.ini, but with the new way to install the drush.phar, the drush.ini doesn't seem to be supported. I've been trying to use the new method of adding php values into the drush.phar, but either it doesn't work or I am doing it wrong. Here's an example of what I tried:

php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M

When I try something like that it just gives me the drush help so I'm assuming I've got something wrong.

Here's the example from the drush docs:

php -d foo=bar drush.phar --php-options=foo=bar

I'm not familiar with using the php command, but I guess I can just go back to using composer if I am not able add a few php values to the drush.phar this way. I also need to add open_basedir with an empty value since I need my php.ini to use open_basedir. I'm not sure how this php command is suppose to handle empty values.

Hoping someone has been able to do this.

You did it exactly right -- just add the additional Drush command, options and arguments after the part you already typed in.  For example:

php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M --root=/path --uri=example.com status

That's kind of a lot of typing, so you might want to make an alias:

alias drush='php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M'

Then:

drush --root=/path --uri=example.com status


Can I just change Drupal's default timezone to test to see if some scheduled rules will fire? I need to test to see if some scheduled rules will fire as expected. I cannot change the server time, as I do not have access to do this. However, if I change Drupal's default timezone can I expedite the process? If not is there another way to do this.

Note: I cannot just shorten the schedules rules as they are hardcoded in a contrib module.

I am 95% certain that drupal is using the server's system time so changing the timezone will have no effect as far as rules are concerned.

Alternatively, you could (temporarily) hack the contrib module to test whatever you need to test and when you're sure things are working, restore the original module when done.


Is it possible to index custom page content? I have created certain pages and blocks using web services programmatically.The content of those pages is fetched from outside the existing Drupal installation and they are not getting indexed in search results.

Is it possible to index my custom page titles and links in the search results? Or is there any other way to do this?

Yes of course you can. You can use the hook_node_update_index() for this:

function YOURMODULE_node_update_index($node) {
   // here is an example that fetches content from an url and appends it to
   // to the data that will be indexed
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
   curl_setopt($ch, CURL_URL, "http://example.com/readme.txt");
   $content = curl_exec($ch);
   curl_close($ch);

   // return the extra content that needs to be indexed for this node
   return $content;
}

The above will of course only work if your custom pages are stored as nodes in Drupal. For instance if you have a node that is called contact which shows content generated externally, then you need to fetch the same content in hook_node_update_index() for this specific node.


How do I alter a view query to use "OR"? The following is the content of the $query object that is passed to a view.

[where] => Array(
  [0] => Array(
    [clauses] => Array(
      [0] => node.type in ('%s')
      [1] => node.status  0
      [2] => node.promote  0
      [3] => node.sticky  0
    )
    [args] => Array(
      [0] => test
    )
    [type] => AND
  )
)
[having] => Array()
[group_operator] => AND

I want to override it by using hook_views_query_alter(). The default operators are all AND, but I want to get the following query

[0] => node.type in ('%s') AND
[1] => node.status  0 AND
[2] => node.promote  0  OR
[3] => node.sticky  0

How do I make the last operator to use "OR"?

db_query("SELECT content_id, count(*) AS cnt FROM {votingapi_vote} WHERE value =1 AND value_type = '%s'" , "option");

How do I use the query in hook_views_query_alter()?

This is untested, but I think what you want to do within your alter function is along the lines of this:

function mymodule_views_query_alter(&$query) {
  unset($query->where[0]['clauses'][2]);
  unset($query->where[0]['clauses'][3]);

  $query->where[1] = array(
    'clauses' => array(
      0 => 'node.promote <> 0',
      1 => 'node.sticky <> 0',
    ),
    'type' => 'OR',
  );
}

This is essentially moving the promote and sticky clauses into a new where grouping, and by setting the type to 'OR', it should work the way you outline in your question.


How to process url from user input? I am creating LinkedImage field, formatter and widget so that images can be linked to somewhere.

And I have an issue with the input. The user can set internal or external links like /node/1, <front> or http://www.google.com. But the Url object that is required for link render element has no method that would work with all of these.

The Url::fromUserInput will work with internal paths but not with <front>. The Url::fromUri() will work with http://www.google.com but not with <front> or /node/1.

So I had to implement logic to distinguish the format and also I had to add validation handler into the widget telling the user that the link has to start with forward slash or with http prefix.

But I do not like this approach. Seems like this is not how it is supposed to be done.

So how can I properly construct Url object from these three types of input?

Also another issue here is that if "malformed" URL is already set (ie. it hasn't been validated via my UI validation handler) then I will get WSOD and that is just really bad UX.

Plus, as you can see, <front> is not working with any of these methods whic hrequires additional logic.

I had the same problem, so please try this:

$url_object = \Drupal::service('path.validator')->getUrlIfValid($path);
$url_object->setAbsolute();
$url = $url_object->toString();


Slideshow with touchscreen support I'm creating a website and I would to add a slideshow that works also with touchscreen on smartphones and tablets.
Could you suggest me some modules that do it?

Ok, I've found this: Flex Slider, this seems works on my android smartphone


Theme CSS won't load I'm trying to make a Drupal 8 theme and no matter what I do, the stylesheet I have won't render. Here's my libraries.yml file:

global-styling:
version: VERSION
css:
theme:
  css/layout.css: {}

and here's my info.yml file:

name: My Test Blog
type: theme
description: 'My test theme description'
package: Custom
core: 8.x
libraries:
  - MyTestBlog/global-styling
stylesheets-remove:
  - '@classy/css/layout.css'
  - core/assets/vendor/normalize-css/normalize.css

regions:
  header: Header
  content: Content
  stylesheets:
    all:
        - css/style.css

Any ideas?

TIP: Conflict when Module with same name as Theme!

Just in case someone else runs into this, if you have a module with the same name as your theme (xxx, for example), the xxx.libraries.yml file in your theme folder is ignored. Instead, Drupal looks at the xxx.libraries.yml file in your modules folder. Any files referred to by it (css, js, etc.) are also loaded from the modules folder and its subfolders, not from the themes folder.


Is there a problem defining a View using a path alias? Or did I just miss something? CONDENSED SUMMARY OF ISSUE:
I have a view with a path of /taxonomy/term/%/something that responds to a URL alias of /spec/ID/ so entering /Spec/ID or /Spec/ID/Something displays what is in the View.  If I clone the View and change the paths from /taxonomy/term/%/something to /Spec/%/Something entering a URL of /specs/ID will no longer display the view.

ADDITIONAL INFO:
I have created a View (D7 Views3) with several pages each with the path /taxonomy/term/%/sub-category where subcategory is a label for a subgroup of content for the specified term. A filter in each page limits the content to match the subcategory label.

I have created an alias for a vocabulary /specs/[term:field_specno]. The field, attached to the term, provides a unique ID for the terms relating to a client's set of standards.

If I enter a URL for /specs/term1, the view will display the correct content for term1 on a page display, with operating Menu Tabs I have defined for each page in the view. It works great except that if I select another Menu Tab, the URL changes to taxonomy/term/%/subcategory format used in the view.  This would be confusing if a user uses the URL and gets the cryptic tid instead of his ID system.  It I clone the view and change the paths to spec/[term:field_specno]/sub-categories, the view no longer displays the pages and tabs correctly.

Is there a fundamental problem in Drupal doing this or have I screwed up somehow?  Has anyone done something similar successfully?

It could be, that I'm still having difficulties understanding your question, but I have no idea why you would expect that to work?

/path/to/%term contains an argument, and as such there is essentially an infinite number of variations that could "fit" into that path.
A path alias "/pageone" to "/path/to/aterm", does not match "/path/to/otherterm", nor any other path in the system.

Each path alias must point to a specific path, and there is to my knowledge no way to automatically "Create all possible path-aliases to for a path /path/with/%arg". There is a feature request for such a tool though.


files missing in web/ folder when using composer.lock file I have run into an unexpected problem with a fresh install of drupal 8.

Initial setup

$ git clone https://github.com/drupal-composer/drupal-project dp
$ cd dp
$ composer install

This works fine, installs everything. I now repeat the same thing, and use the composer.lock file from the above.

$ git clone https://github.com/drupal-composer/drupal-project dp2
$ cp dp/composer.lock dp2/
$ cd dp2
$ composer install

This time, however, the web/folder just has folders in it, no files. In fact, a diff between the two folders shows a number of missing files including in sites and sites/default.

I thought the composer.lock file was used to simply lock the versions of the modules down.

What am I missing here?

After some investigation, I found the culprit. The composer project uses drupal scaffold to place these files. However, this does not seem to be getting executed when the .lock file is already in place when you do the composer install

To resolve this, it was as simple as running the following command

$ composer drupal-scaffold


How to get exposed filter dropdown option selected value in drupal hook I'm trying to get exposed filter selected value in hook_form_alter().

myModule_form_alter(&$form, $form_state, $form_id) {
     if ($form['#id'] == 'views-exposed-form-view-id-display-id'){
          var_dump($form['exposed_element']['#options']);
     }
}

i tried with also

$form['exposed_element']['values'],
$form['values']['exposed_element']
$form['exposed_element']

But none of them giving me selected option value.

Any help/suggestion would be greatly appreciated.

EDIT

For more clarification

function myModule_form_alter(&$form, $form_state, $form_id) {
    switch ($form_id) {
        case 'views_exposed_form':
            switch($form['#id'])
            {
                case 'views-exposed-form-soldproduct-page-1':
                       var_dump($form['exposed_element']['#options']);
                break;
            }
        break;
    }
}

Where soldproduct is my view name and page-1 is the view display id.

First of all, look up the exact filter's name. To do that open your view's builder UI and go to this exposed filter's settings page; look for the "Filter identifier" text field.

After that, you can get the filter's currently selected value in hook_form_alter():

function myModule_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'views_exposed_form'){
        $view = &$form_state['view'];
        if ($view->name == 'your view name' && $view->current_display == 'page_1') {
            var_dump($view->exposed_input['your filter identifier']);
            // OR
            var_dump($form_state['input']['your filter identifier']);
        }
    }
}


Simulating TYPO3-Template-Engine For my next drupal project I need more flexibility in content-styling, than the standard approach allows. I need to be able to build the content-body for every single node from different elements. Like in TYPO3 I need a sandbox of pre-styled elements (e.g. full screen image, two column text, 3 boxes side by side, etc) and be able du add as many different elements as I want. The markup and styles should be saved in my theme, so there should not be any html in the content fields.

e.g.

EDIT 1: Its basicly something like the Form builder what I am searching for. (see comments)

Usualy I have used an WYSIWYG editor whith shortcodes, insert module and predefined styles, but I learned that it is not a good practice.

My approach which atm only work in the theory:

I use Field collection module for being able to add unlimited blocks of the collection.
Whithin the field collection I have one select-box where I define the template_name for the collection.
Than I add all the fields I need (e.g. text, image, backgroundimage, date) to the collection
With the Conditional Fields module I controll which fields are needed/shown for every single template (see select box).

Screenshot 1 //
Screenshot 2
The theming is done in my field-collection-template file (if template_name == x, render this whithin  particular markup)

Unfortunately this is really complicated  ( I have to make a dependies for every single field in any template).

is there any better solution?

What about using entity references. You mention the field-collection approach, which has the same overhead as using entity references.

Basically you create a few node types that each conform to a different block element that you require. Then you create a master node with an entity reference field and select all of your block element node types as candidates, and set the filed count to unlimited. Then also use the inline entity form.

This will work but has a heavy server load.


Getting a field's value from an entity What I have installed on my site is the Entity API and Entityform modules. The Entityform module allows me to create forms that any user can submit and the forms fields are available for me to use in views, similar to how a content type would work.

Normally to pull a field's value from a node into my template with php I'd do the following:

<?php echo $node->field_name[$node->language][0]['value']; ?>

However this does not work with entityforms/entities.

Does anybody know of a way to do this for a field within an entityform? Some people have suggested to use devel and the dpm() function but I have no idea how to use those either.

Some specific examples on how I can get this field's value would really help me a lot.

Have you tried accessing the values with entity_metadata_wrapper?

$entityform_id = 12; // entity form id
$entityform = entityform_load($entityform_id);
$entityform_wrapper = entity_metadata_wrapper('entityform', $entityform);
// Access fields with $entityform_wrapper->field_name->value() or ->field_name->raw()
drupal_set_message($entityform_wrapper->field_my_field->value()); // for example


Can authenticated users save stories? Is there a module that would allow authenticated users to save stories they like and store them in a page containing all their personalized content (something similar to a delicious.com type service)?

I think you can use Flag to do it with some configuration and with Views.


How do I change the base URL to use a more user-friendly domain? I want to change my domain name from reallylongandnotuserfriendly.example.com to you.example.com.

Is there a setting that could expose these change to the public, without actually changing the real domain name?

You could create a Drupal alias as follows:

In the sites directory, find and rename the example.sites.php file to sites.php
Add the following line

$sites['you.example.com'] = 'name_of_the_directory_where_your_settings.php_is';

In your case, the settings.php file is likely to be inside sites in a directory called reallylongandnotuserfriendly.example.com, which means the line would be:

$site['you.example.com'] = 'reallylongandnotuserfriendly.example.com';

Just be sure that you configure your server to point you.example.com to your base Drupal installation.


How to avoid module specific jQuery plugin script running globally? This is my first time working with Drupal (Drupal 7).

I've created a jQuery plugin which populates a target div. The target div is added to the node via panelizer.

I only want to run the script for when it's needed. Just now it runs all the time. Even on the dashboard, this causes script errors.

I'm not sure what the best approach is for this.

EDIT (SOLUTION):

Thanks for the input. I decided to use a Javascript approach.

var elementExists = document.getElementById('target');

if (typeof(elementExists) != 'undefined' && elementExists != null) {
  // Script
} else {
    return;
}

From my experience it's usually best to leave this check to JS and don't bother on PHP side. Of course it all depends on your definition of best, but benefits I see are:

It's easy and stable to test for div existence with $("#myid"), opposed to more mysterious tests in PHP. Now you know that this div will appear when X is true and Y == Z. Will you remember that in two months?
Sure, we have comments. But will future developer understand what you meant? Will you be disciplined enough to write them, and do it really clearly?
It's easier for caching - if you aggregate your scripts, you will use the same aggregated file for pages with and without div, so one less check / download for browser
It lessens the chance for conflict between your module and other ones.

Modules shouldn't just overwrite [#attached] array, but I encountered some that did.
If you are using drupal_add_js instead, making sure test for conditions is run when it is supposed to might be hard, if other modules will try to reorder hooks. So this isn't a sure way to avoid problem described above.
Various caching systems might miss the conditions you use. Probably nothing as severe as Boost and Mobile Tools issue, but risk is there.
Theme shouldn't need to know about blocks - if you will leave test to theme, point above will not apply, but you risk crashes whenever theme is switched or block is disabled. Testing for it on both sides will add a lot of code.
And I'm sure there are other things I simply never encountered yet.

Of course you could say most of those are bugs in other modules, and you would be right, but being right does not help if you need your site up and running.
It's easier to quickly see scripts added via .info file than to search code for drupal_add_js or attached or... you see, there are many ways to do it in code, happy hunting if you are new developer and need to find where this one script came from.


How to override node content in Twig I have created no of nodes as content type as Article in my website(techladder.in). But I am not getting the right file where I can override the content of the file.

For example, I need to display author information above the Disqus comment section.

I was able to override the node file in my theme at following path:
theme/templates/content/node--article.html.twig as following:

     {%   set classes = [
        'node',
        'node--type-' ~ node.bundle|clean_class,
        node.isPromoted() ? 'node--promoted',
        node.isSticky() ? 'node--sticky',
        not node.isPublished() ? 'node--unpublished',
        view_mode ? 'node--view-mode-' ~ view_mode|clean_class,   ] %} {{ attach_library('classy/node') }}

      {{ title_prefix }}   {% if not page %}

          {{ label }}

   {% endif %}   {{ title_suffix }}

      {% if display_submitted %}

            {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
            {{ metadata }}

           {% endif %}

        {{ content }}

{% if teaser %}

 {% endif %}

But here, I am not able to find a file where I can override the content of the node.

Does anyone has suggestions how can I do it in Drupal 8.

content is just the render array composed of renderable elements.

If you want to break up the fields, then you need to not use {{ content }} and instead call each field where you want them:

{{ content.field_MYFIELD }}

Those fields are controlled by their field templates.

An improvement on your code would be to not check for view modes in one template, but just make each view mode a template like node--article--teaser.html.twig, node--article--full.html.twig, node--article--some-other-mode.html.twig. It will make your code cleaner.

So you'll need to debug and find what the content variable has, and just start outputting it where you want them to render in the template.


How to edit breadcrumb in drupal 7? How to edit breadcrumb info without install any drupal module?
Example: blog
Home >> blog >> admin's blog

I want to remove admin's blog

I cant find node--blog.tpl.php file.

I only can find node.tpl.php file.

Many Thank.

Check the menu_get_active_trail() and menu_set_active_trail() functions. They should be of use for what you want (retreiving and changing your breadcrumb).

Try the following in your template.php in your theme :

/**
 * Implementing theme_preprocess_html
 */
function YOURTHEME_preprocess_html(&$vars) {
    $crumbs = menu_get_active_trail();
    $count = count($crumbs);
    // dpm($crumbs);
    unset($crumbs[$count - 1]);
    menu_set_active_trail($crumbs);
}

See how it goes.