Add an enddate to my date field programmatically

Finally found it by changing the field settings' "todate":

'field' => array(
                'field_name' => 'field_van_tot',
                'type' => 'datetime',
                'label' => $t('From - Until'),
                'cardinality' => 1,
                'settings' => array(
                    'granularity' => array(
                        'year' => 'year',
                        'month' => 'month',
                        'day' => 'day',
                    ),
                    'todate' => 'required',
                ),
            ),


You are not authorized to access this page with blocks displayed

You probably need to adjust the visibility settings of your blocks (see screenshot below). You can, for instance, restrict the visibility to authenticated users only.

It is also possible to do it programmatically. See this question, for some guidance.


Copy installed modules and configuration to new installation

Question: Installing all the modules in new installation

Answer: Yes add all modules to root composer.json file so only have to run composer install or later composer update

Question: Configuration migrate

Answer:
Configure your sites sync folder 'in settings.php' and run drush cex to export the current sites config (then you can git commit the changes and deploy to new environment) and run drush cim on new environment to import changes.

Question: Data migrate

Posable Answers:
now this one can get kinda tricky and have a lot of options for this ... which depends largely on what you want to keep / what you don't.

Simple option: copy database - good old fashion export database and then import it.

Content migration option: look in to https://www.drupal.org/project/default_content_deploy  its like config import/export only for entity data (which again can be commited to repo and deployed) eg drush default-content-deploy:export and  drush default-content-deploy:import

use normal migrate api option.
use a seed database option.

really should just have all the stuff you need in a git repo then you just tag the release ... push to the environment and run some commands or have some automated scripts to run the commands for you
look in to stuff like...
https://chromatichq.com/blog/drupal-8-deployments-jenkins-github-slack
and https://hernani.pt/automatic-update-drupal8


Regions. how can I disable a region? (not disabling blocks)

The context module is a very handy way to control blocks on a site which uses them extensively. It allows you to define contexts which show and hide blocks. It will stop the blocks from even being loaded so will help performance.

It makes it much easier to define where and when the blocks appear. Rather than defining things per block you define what blocks appear per context.

This video seems to explain things well.


How to create sortable checkboxes using the form API?

I was able to get this working using a modified version of the code here http://dropbucket.org/node/204

The adjustments I made were to allow my table to be an element on a parent form and to repopulate the from my variables array...
//TODO bubble checked boxes to top

    $rows = array();
    $row_elements = array();
    $data=array();
    //$shared['articleFields'] values stored in variables table -- loaded in parent form
    //$key is name of my parent form this gets attached to

    $cc=-10; //default weights starting at -10
    //field machine names with titles
    $articleFields = array(
      'title'=>t('Headline'),
      'field_news_categories'=>t('News Categories'),
      'field_text_2'=>t('Subheading'),
      'field_photo_caption_1'=>t('Featured Photo'),
      'body'=>t('Copy'),
      'field_text_4'=>t('Featured Quote'),
      'field_keywords'=>t('Keywords'),
      'field_websites'=>t('Related Links'),
      'field_images'=>t('Additional Images'),
      'field_slideshow'=>t('Slideshow'),
      'field_video'=>t('Video'),
      'scheduler_settings'=>t('Scheduler'),
      'group_alternates'=>t('Alternates'),
      'field_text_1'=>t('Alternate Headline'),
      'field_text_3'=>t('Alternate Subheading'),
      'field_photo_caption_2'=>t('Alternate Photo'),
      'field_longtext_1'=>t('Alternate Copy'),
    );

    foreach ($articleFields as $k =>$v) {
        // Build the table rows.
        $dv="";
        $dv2="";

        //if no values are defined use default weights from -10 up
        if(isset($shared['articleFields']['elements'][$k]['weight'])){
            $dv=$shared['articleFields']['elements'][$k]['weight'];
        }
        else $dv=$cc++;

        //if no value is defined use 0 for enabled value (unchecked)
        if(isset($shared['articleFields']['elements'][$k]['enabled'])){
            $dv2=$shared['articleFields']['elements'][$k]['enabled'];
        }
        else $dv2=0;
        $rows[$k] = array(
            'data' => array(
                // Cell for the cross drag&drop element.
                array('class' => array('entry-cross')),
                // Weight item for the tabledrag.
                array('data' => array(
                        '#type' => 'weight',
                        '#title' => t('Weight'),
                        '#title_display' => 'invisible',
                        '#default_value' => $dv,
                        '#attributes' => array(
                            'class' => array('entry-order-weight'),
                        ),
                    )),
                // Enabled checkbox.
                array('data' => array(
                        '#type' => 'checkbox',
                        '#title' => t('Enable'),
                        '#title_display' => 'invisible',
                        '#default_value' => t($dv2),
                    )),

                // Name textfield.
                array('data' => array(
                        '#type' => 'textfield',
                        '#size' => 50,
                        '#disabled' => TRUE,
                        '#title' => t('Field'),
                        '#title_display' => 'invisible',
                        '#default_value' => t($v),

                    )),

            ),
            'class' => array('draggable'),
        );

        // Build rows of the form elements in the table.
        $row_elements[$k] = array(
            'weight' => &$rows[$k]['data'][1]['data'],
            'enabled' => &$rows[$k]['data'][2]['data'],
            'field' => &$rows[$k]['data'][3]['data'],
        );
    }
     //sort both the rows and the row elements on the weight value

        uasort($rows, function($a, $b) {
            return $a['data'][1]['data']['#default_value'] <=> $b['data'][1]['data']['#default_value'];
        });

        uasort($row_elements, function($a, $b) {
            return $a['weight']['#default_value'] <=> $b['weight']['#default_value'];
        });

    $id=str_replace("shared_", "", $key);
    $id="form-item-shared-".$id."-articleFields";

    // add this to parrent form
    $form[$key]['articleFields'] = array(
        '#prefix'=>'
',
        '#theme' => 'table',
        // The row form elements need to be processed and build,
        // therefore pass them as element children.
        'elements' => $row_elements,
        '#header' => array(
            // We need two empty columns for the weigth field and the cross.
            array('data' => NULL, 'colspan' => 2),
            t('Enabled'),
            t('Field'),
        ),
        '#rows' => $rows,
        '#empty' => t('There are no entries available.'),
        '#attributes' => array('id' => 'entry-order'),
        '#sufix'=>'
',
    );
    drupal_add_tabledrag('entry-order', 'order', 'sibling', 'entry-order-weight');


How to render a ctools content type programmatically?

ctools_content_render() is the solution.


Where in the database does fieldset and field instance info live?

Whether a field is required or not can vary by content type (ie, the bundle).  I am pretty sure you need to use field_info_instances($entity_type, $bundle_name).  You can then use field_info_field($field_name) on the results.  Something like:

$fields_info = field_info_instances('node', $bundle);

foreach ($fields_info as $field_name => $instance) {
  $field_info = field_info_field($field_name);
}

dpm() both the $instance and $field_info.  Everything you need should be in those two variables.  This is a snippet from a dynamic exporter I have.


The node ID of the parent feed node should be attached to each child feed-item node. Using this in either the template file, or within Views, you can get to the data you require.

For example :

In a Views listing. Add a relationship to the parent feed.
Add a new field for content title - but attach it to the relationship - this gives the parent title. Same applies for any other fields you may have added to the parent.

In template.php -- do a node_load($node->PARENT URL REFERENCE GOES HERE) this will give you access to all the variables on the parent node. If this sounds alien to you then you probably don't need it.

Hope that helps :)


Ubercart show Prices without Tax For specific Role

ubercart adds taxes in hook_entity_view_alter( uc_taxes_entity_view_alter)

So I implement hook_entity_view_alter in my module

function mymodule_entity_view_alter(&$build, $entity_type) {
  global $user;

  if($user && in_array(constant('SOME_USER_ROLE'), $user->roles)) {
    return;
  }

  // ...
}

Also unimplement uc_taxes implemetation of hook_entity_view_alter using hook_module_implements_alter

function mymodule_module_implements_alter(&$implementations, $hook) {
  if (in_array($hook, array( 'entity_view_alter'))) {
    unset($implementations['uc_taxes']);
  }
}


Why isn't a PDO driver detected on the install page?

The error could be thrown for three different reasons.

Some of the Drupal core files in the includes/database directory are missing
There isn't any extension implementing the necessary PDO drivers
The extension implementing the necessary PDO driver isn't enabled in the php.ini file or other .ini files used from PHP

To check which database driver is available, Drupal first looks for its own files in the includes/database directory, initializes an instance of a class that extends DatabaseTasks (for example DatabaseTasks_mysql for MySQL) and calls its installable() method.
public function installable() {
  return $this->hasPdoDriver() && empty($this->error);
}

protected function hasPdoDriver() {
  return in_array($this->pdoDriver, PDO::getAvailableDrivers());
}

If the method returns FALSE, the PDO driver is considered not available. (See drupal_get_database_types() for details.)
Notice that, if the PDO extension (not a PDO driver) isn't available, the error shown from Drupal is the following one.

'Your web server does not appear to support PDO (PHP Data Objects). Ask your hosting provider if they support the native PDO extension.

In that case, Drupal would also show the following message, followed by a list of one or more missing PHP extensions.

Drupal requires you to enable the PHP extensions in the following list (see the system requirements page for more information)


How do I display date and time for multiple time zones?

Try to save date-time values in UTC format and while displaying them you can use format_date function

where you will need to pass timezone value to its parameter.


$views->render() does not display node_path

aha! turns out render() only produces data saved in the database, and node paths are not saved in the DB. So my solution was to grab the node id from the rendered view, use that to get the node paths, and created a new field with that path like so:

function theme_get_view_result($viewname) {
  // views_get_views_result($viewname) produces the same result as $view->result;
  // Im just showing that I tried both
 //return views_get_view_result($viewname);

  $view = views_get_view($viewname);
  if(!empty($view)){
    $view->preview();
    return $view->result;
  }else{
    return 'empty';
  }
}

$blocks = theme_get_view_result('front_page_blog_blocks');
foreach($blocks as $k=>$v)
{
  $node_path = drupal_lookup_path('alias','node/'.$blocks[$k]->nid);
  $blocks[$k]->node_path=$node_path;
}


The password field is special in that it should only be synchronized when the password changes.  The most current version of the LDAP module can trigger field synch's either on account creation or during any account synch.  It doesn't allow the password field to be triggered only during password changes.

The password field can be unicodePwd for AD, or userPassword for other LDAP databases.

I had to modify the 7.x-2.x April 8, 2014 version of LDAP to get this to work.  Within the modifyLdapEntry function we need to know if the password field is being modified.  Don't synchronize the password field if we know the password is not changed (which is true during login synchronization).  Also, do not synchronize the password if it's not set (such as during the edit account page).

Modify LdapServer.class.php, function modifyLdapEntry(), adding global variables for the current password, and for whether or not the password is being changed.  If there is no current password but we are changing the password (such as password reset form or admin edit user form), set the password.  Also, if the current password is given and it does not match the new password (such as user edit form), set the password.  Otherwise, unset that property from being synchronized.

..

  global $current_password;
  global $changing_password;
  if ((empty($current_password) && $changing_password) || (!empty($current_password) && $current_password != $attributes['unicodePwd']))
  {
    $attributes['unicodePwd'] = ldap_servers_convert_password_for_active_directory_unicodePwd($attributes['unicodePwd']);
  }
  else
  {
    unset($attributes['unicodePwd']);
  }

..

Modify the ldap_user.module, function ldap_user_grab_password_validate(), and set the current password if it is given, and set the changing password variable if we know it's changing.

/**
 * store password from logon forms in ldap_user_ldap_provision_pwd static variable
 * for use in provisioning to ldap
 */
function ldap_user_grab_password_validate($form, &$form_state) {

   // This is not a login form but profile form and user is inserting password to update email
  if (!empty($form_state['values']['current_pass_required_values'])) {
    if (!empty($form_state['values']['current_pass']) && empty($form_state['values']['pass'])) {
      ldap_user_ldap_provision_pwd('set', $form_state['values']['current_pass']);
    }
    // Or this is a profile form where the user is updating their own password
    elseif (!empty($form_state['values']['pass'])) {
      global $current_password;
      $current_password = $form_state['values']['current_pass'];
      ldap_user_ldap_provision_pwd('set', $form_state['values']['pass']);
    }
  }
  // otherwise a logon form
  elseif (!empty($form_state['values']['pass'])) {
    if ($form['account']['pass']['#type'] == "password_confirm") {
      global $changing_password;
      $changing_password = TRUE;
    }

    ldap_user_ldap_provision_pwd('set', $form_state['values']['pass']);
  }
}


Get an Un-submitted/Active Form Field Value in $form_state?

MYMODULE/src/Form.php:

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {

  // get form config.
  $config = $this->config('MYMODULE.settings');

  // Set our count. Used in for loop below.
  if (!empty($form_state->getValue(['fieldset', 'field_count']))) {
    // get $form_state count value.
    $defaultCount = $form_state->getValue(['fieldset', 'field_count']);
  }
  else {
    // Get config count value.
    $defaultCount = $config->get('field_count');
  }

  $form['#tree'] = TRUE;

  // Fieldset item.
  $form['fieldset'] = [
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
  ];

  // Field count item.
  $form['fieldset']['field_count'] = [
    '#type' => 'number',
    '#title' => 'Number',
    '#required' => TRUE,
    '#default_value' => $config->get('field_count') ?: 1,
  ];

  // Rebuild submit item.
  $form['fieldset']['rebuild'] = [
    '#type' => 'submit',
    '#value' => 'Apply number',
    '#submit' => ['::rebuildFormSubmit'],
    '#ajax' => [
      'callback' => '::fieldCallback',
      'wrapper' => 'fieldset-wrapper',
    ],
  ];

  // Loop through our count and create form items.
  for ($i = 0; $i < $defaultCount; $i++) {

    $form['fieldset']['field'][$i] = [
      '#type' => 'textfield',
      '#default_value' => isset($config->get('script')[$i]) ? $config->get('script')[$i] : '',
    ];

  }

  return parent::buildForm($form, $form_state);

}

/**
 * {@inheritdoc}
 */
public function fieldCallback(array &$form, FormStateInterface $form_state) {
  return $form['fieldset'];
}

/**
 * {@inheritdoc}
 */
public function rebuildFormSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

This part in the $form['fieldset']['rebuild']:

'#ajax' => [
  'callback' => '::fieldCallback',
  'wrapper' => 'fieldset-wrapper',
],

along with:

/**
 * {@inheritdoc}
 */
public function fieldCallback(array &$form, FormStateInterface $form_state) {
  return $form['fieldset'];
}

Are the ajax options.


The #ajax['wrapper'] value should be id attribute, not a class, and without '#'. You can look about this here. The callback function should return a html content, a renderable array (which will replace the 'wrapper' on a call) or array of drupal ajax commands. You can try this and your code should work:

function MYMODULE_ajax_callback($form, $form_state) {
   $commands[] = ajax_command_alert(t('MYMODULE_ajax_callback fired'));
   return array('#type' => 'ajax', '#commands' => $commands);
}


How to make a discount on specific products quantity that have specific fields

Hopefully you're using taxonomy fields for your color on your shirts. If you are, then your solution is easy because Commerce Taxonomy Conditions will do the job. You can have it set to a quantity of a particular taxonomy field being present in an order and have it apply some discount.


How to to get the prices centered in the node:teaser with commerce price savings formatter?

Add this in your CSS:

table.commerce-price-savings-formatter-prices{
width: 100%;
}

Also, you can add:

.commerce-price-savings-formatter-price .price-amount{
display: block;
padding-top: 5px;
}

Prices looks much better with this.

If width:100% doesn't work try to use width:100% !important; because width is already defined in module's theme.

To remove line above price add this to your CSS:

table.commerce-price-savings-formatter-prices tbody{
border-top:0;
}

Also, if it doesn't work, use border-top:0 !important; instead border-top:0;

To minimize the space between prices add to CSS:

table.commerce-price-savings-formatter-prices-down{
margin: 0 auto;
width: 50%;
}

Important part here is width: 50%;, change this percent to see which space you want to have, the more percent is the more space will be between prices. Again, use !important if doesn't work.

You can also add this to your CSS to make prices look better (to make it equal at the bottom edge):

table.commerce-price-savings-formatter-prices-down tr td{
vertical-align: bottom;
}

Don't forget to clear cache.


Top level directory files like readme.txt are served by apache

As I understood - you want to hide the txt files on the root direcroty (e.g. Changlog.txt) from prying eyes, therefore you can search Drupal.org for that question (its there..), and you'll see 3 types of solutions:
1. Leave those file as they are ( I don't like that option)
2. Just delete those files
3. Hide them using the site's .htaccess (My favorite option)


How can I retrieve indexed facet options for a particular field using Search API?

I seem to have found the answer after some major trial and error, and some digging through the FacetAPI source code. The issue is linked to the same issue explained in the post
Display facets on non-search pages

I created a facet block in Views for each facet that I'm trying to access, and set them to "hidden" in the block settings within Views. Then by adding a block from my custom module directly below them in the same region, I was able to access the facet data using the following code:

$searcher = 'search_api@MY_CUSTOM_SEARCHAPI_INDEX';
$realm_name = 'block';

$build = facetapi_build_realm($searcher, $realm_name);
krumo($build);

The krumo output contains a render array for each facet you're trying to access, and all the facet options are available for you to access.

I hope this helps someone struggling with the same issue.


Check to see if two nodes are translations of each other

You can use translation_node_get_translations($tnid) function :

// $node is the node which translation set is needed
// this function returns an array of two node objects
translation_node_get_translations($node->tnid);

If you want to test it you need to put it somewhere (a wise place) in the code, clear your cache, and then show it with devel module.

Wish helps,

cheers,

jramby.


I think we've covered why this might not be a good idea in comments, but to change the output of the pager you just need to override theme_pager_link() in your site's theme.

You'll need to reproduce the original function almost exactly, except you'll probably want to ditch the use of pager_get_query_parameters(), and alter the url() on the penultimate line to use a fragment.


Using exposed filters as part of the rendered page's title

A also have this question. But now I'm trying this module: https://drupal.org/project/exposed_filter_data?
And this module is not working for me.

I found this:

/**
 * THEME_PREPROCESS_VIEWS_VIEW
 * @param type $vars
 *
 */
function MYTHEME_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'viewName') {
    // get var from GET
    $obj_type = $_GET['obj_type'];
    if (isset($obj_type)) {
      // obj_type is the taxonomy term, get taxonomy term name
      $tax_name=taxonomy_term_load($obj_type)->name;
      // if taxonomy term have parents
      $tax_parent = taxonomy_get_parents_all($obj_type);
      if (isset($tax_parent[1])) {
        // add parent name to taxonomy term name
        $tax_name =  $tax_parent[1]->name . ', ' . $tax_name;
      }
      //update title
      $vars['view']->build_info['title'] = $tax_name;
    }
}

And this is working!


Programmatically change block content on page render only

You should probably try

$variables['content']['body'][0]['#text']= "html content";

complete example

function THEMENAME_preprocess_block(&$variables) {
  if ( $variables['attributes']['id'] == "block-newblock" ) {
    $variables['content']['body'][0]['#text']= "html content";
    $variables['content']['body'][0]['#format']= "full_html";
  }
}


Why does my Pie Chart only show 1 out of multiple fields?

Try rearranging the fields in the views settings under "Fields" section. While you are there, you may also try use a different group field in Google Chart tools format settings under "format" section.


User registration times out/doesn't exit on live centos+nginx server

Issue was a faulty mail server. For some reason when it couldn't use mimemail properly it was choking without error, kinda annoying. Fixed by setting up a proper external mail transactor (mailjet module in my case).


How do I save patched core after new upgrade?

Normally you should never hack the Drupal core. However, there are few exceptions:

you're applying patch downloaded from Drupal.org which has been QA tested,
you're applying patch implemented by people who're extremely familiar with the Drupal code base, development practices, and security model,
you've tested the patch using unit tests (SimpleTest) included with your Drupal core and you properly document the change (e.g. by practicing proper revision control with your code).

If you decide for that, you should keep the patches well documented and ideally in your repository (e.g. one level up from Drupal docroot level, Drupal core folder, or create new patches/ folder for that).

Then each time you upgrade your Drupal core, you need to remember to apply those patches again (this should be part of your Drupal upgrade steps).

To automate this, you've the following possibilities:

using drush command to upgrade your core (e.g. as part of the script):

drush -y up drupal
find . -name "*.patch" -depth 1 -print -exec sh -c "patch -p1 <'{}'" ';'

using drush make, e.g.:

.make file` (see: Full example drupal-org.make file)

api = 2
core = 7.x
projects[drupal][patch][] = http://drupal.org/files/issues/992540-3-reset_flood_limit_on_password_reset-drush.patch
projects[drupal][patch][] = http://drupal.org/files/issues/object_conversion_menu_router_build-972536-1.patch

YAML file (see: examples/example.make.yml)

core: "7.x"
api: 2
projects:
  drupal:
    version: ~
    patch:
      - "https://www.drupal.org/files/issues/add_a_startup-1543858-30.patch"

If you're not working on make files, you can still download Drupal core files into empty folder, this will automatically apply the patch files, maybe consider running some unit test, then replace your generated files into your Drupal core instance.
upgrading and patching manually in Drupal docroot:

curl https://ftp.drupal.org/files/projects/drupal-7.4?.tar.gz | tar xvf - --strip-components=1
patch -p1 < add_a_startup-1543858-30.patch


How to change webform default email address from sender side?

You can usually find a configure link in the module list.

Looks like in /admin/config/content/webform

and scroll down to default e-mail values.

(For Drupal 6, go to yoursite.com/admin/settings/webform)


How to make an custom content entity can be refered like user in Drupal 8?

Eyal's comment is just the answer, Choose content as the reference type.


How to use token as a filter value in views

Use Contextual Filters instead of Filter Criteria.

In Drupal 8, at the time of writing this, you also have to install the views_argument_token module.

When adding a contextual filter, at the pop up window, select "Provide default value" option. From there on the remaining settings should be intuitive.


How to send email to submitter anytime webform modified

Finally I can send an email to the submitter by using webform rules module.
Event:
After a webform submission has been updated
Condition:
Data selector: form-id
Webforms: select the webform that i use
Action:
Send email:
To: <?php print $data['components']['email']['value'][0]; ?>
From: ...just leave it blank


Setting a View's Menu Item to a Sub-Menu

Okay, so if I understand correctly you have a View Page that is part of your main site hiearchy (main menu).  Unfortunately you can only assign a View (at least through the View interface) to a particular menu, but not any of the children of that menu.  This should be a feature request in the Views issue tracker.

What you need to do is go edit the Main Menu through Administration -> Structure -> Menus, list links for Main Menu, and then find your Tasks page that was dropped in their (should be on the first level) and re-position it to where you want it in your menu hierarchy.


How do I show an exposed view filter in a block only on relevant taxonomy term pages?

How to make a block vocabulary-specific
You can use the Block Visibility Groups module in conjunction with the Vocabulary Condition module (linked on that page).  Using those two modules together will give you a checkbox on the block to pick the vocabulary it should be shown for.
If you want to do it programmatically, the Vocabulary Condition module should be a good code reference.  There's also another Vocabulary Condition module (same name, ugh!) which could also be a good reference.
Alternative idea: Use different view pages for each vocabulary
If you're using the default taxonomy term view provided by core, I'm pretty sure you can customize it so that you have one page for terms with the Product vocabulary and another for the Blog category. Then you can simply expose the filter on the view page for the relevant vocabulary.


Why don't you just use the existing node type condition plugin?

That won't solve your problem if you also need the node to actually display something, but core currently just doesn't really do this for blocks, there is no UI to configure the mapping, so it only works if the context has the exact same name.

You will likely have to fall back to getting the parameter yourself out of the route match service, for now.


How to translate a node without creating a new node?

That is the way in which the Internationalization module works, when you go to translate a node the module create a copy in another language, if you want one node with the fields transalted you must look at the Entity Translation module.

You can read more in this in Node translation vs. Entity (field) translation


Tokens missing in Webform Emails after upgrading

I could solve the problem, but an issue still remains.
I have disabled Token and Entity Tokens Modules (and requested associated Modules)
... then reactivated :
The probem comes from the Advanced User Management Module : when it is enabled, most of the tokens cannot be browsed (among which the default proposed ones in the mail content).
... So, I cannot use this Module any more.


Views Template Suggestions When There are Duplicate Filenames

You could look and see in your theme registry by dpm-ing in theme_registry_alter() or by turning on devel and visiting /devel/theme/registry and seeing what entry is pointing to what file.

If you don't want to do that on production you could do it locally first and then grab the production database locally.

I would imagine that the registry was rebuilt between the two sites and the first time it picked up one of the files and the second time the other since I don't know of a designed hierarchy for two files in the same level directories in a theme folder.

Don't upvote - this is a speculative answer.


How do I get image styles to function on the original node page?

On Manage Display page click locate Custom display settings to expand for more display options. check Full Content and Save.

Now you will see the Full Display tab on right top of your content area click that to select that display and than select your desired image style.


hide certain fields on the edit form of content profile

Content permission can be quite tedious, because once it's installed you have to configure every single CCK field's permission both for view and edit. While you're connected as the admin you will always see everything but you have to test this with a normal user.

However if you just want to hide your field you can do this in several ways.

Hide them in CSS with a display: none; rule.
Hide them with a hook_form_alter()


If you don't want to change the variables on field level you can parse the content in a #post_render callback after it is rendered:

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function mymodule_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $build['#post_render'][] = function ($html, array $elements) {
    return str_replace('original', 'changed', $html);
  };
}


hook_schema is not creating database table

Use drush dre -y [module] which disables, uninstalls and then re-enables the module. The -y flag makes it even faster, avoiding you have to press y and enter three times.


Twig template name for field when content type is viewed in particular view mode

Field templates have no name suggestion for the view mode.

From the linked page:

  This page lists the conventions used for the base html structure, the
  page, regions, blocks, nodes, fields, and other core components. (It's
  good to know that it is possible to create custom template name
  suggestions using function hook_theme_suggestions_HOOK_alter.)

You have to create a custom name suggestion.

You find the view mode in the variables of the field: Getting node view mode in field preprocess


Alter a date format in a view based on another date

You can override the output using twig code:

{% if field_date1.striptags == field_date2.striptags %}
    {{ field_date1 }}
{% else %}
    {{ field_date1 }} - {{ field_vegdate2 }}
{% endif %}

Or something like this...


Views Ajax is same as the Drupal Ajax, ajax response also run the behaviors.

What you need to do is removing the once() because it will stop your event binding for the second time. For preventing the event bound twice due to the ajax, just remember to add context as scope when you search for the element with jQuery.

(function ($, Drupal, window, document, undefined) {

Drupal.behaviors.my_custom_behavior = {

  attach: function(context, settings) {

    // Sets default class for course views and toggles class when changing view.
    // Context is important here for limiting the scope.
    var view = $(".view", context);

    if ( view.hasClass("course-view") ) {
      view.addClass("grid-view"); // Sets .grid-view as default class on the view

      $(".list", view).click(function() {
        if (view.hasClass("grid-view")) {
          view.addClass("list-view"); // adds .list-view to the view class
          view.removeClass("grid-view"); // removes .grid-view from the view class
        }
      });

      $(".table", view).click(function() {
        if (view.hasClass("list-view")) {
          view.addClass("grid-view"); // adds .grid-view to the view class
          view.removeClass("list-view"); // removes .list-view from the view class
        }
      });
    }
  }
};

})(jQuery, Drupal, this, this.document);


Printing PHP variable in form element in buildForm function

It's just a silly error '#markup' => t('$opensslOut') needs to be without the '' because $opensslOut is a variable and not a string.

So use

'#markup' => t($opensslOut)


Exposed filters in Block for Page View do not filter results

Is your views filter is working when you disable ajax submit?

if No then enable -> Show the SQL query

from URL www.yourdomain.com/admin/structure/views/settings

then check query which is generating on submit of the form, you will get solution there only

try and let know status.


PDOException: SQLSTATE[HY000]: General error: 1 cannot rollback

Turns out it was a problem with my /tmp directory being full.. Devel module had filled it up.
It's something to be aware of and here is a script to notify you when /tmp is nearing full http://forums.ultratechhost.com/thread-187.html


OK, I solved it the easy way. I enabled "Output this field as a link", added the field "Content: nid" as the first field and then changed my rewritten field to this:

And now it works. Hope this helps somebody.


Drupal-7 - Lists and Custom Content Types

Organizing content with taxonomy (category) is a very powerful tool of Drupal.

  What isn't clear is when is a node not a node. For example, there are
  various support lists that I would like in my customisations, for
  example "salutation" (mr, mrs, miss, dr, revd etc) that should be user
  maintainable and stored in a database. It seems a bit overkill to
  create a separate content type and node just for this.

According to this, you can manage "salutation" with taxonomy . The"salutation" is a vocabulary and "mr, mrs, miss, dr, revd" are terms of the vocabulary. They will be stored in the taxonomy table and the path admin/structure/taxonomy/your_vocabulary will be user maintainable list page.

You can create a custom field ( term reference ) to your vocabulary ( "salutation" in this case ) for your content type.
They can be chosen from a list when user creates a node.

Same concept for your Event Type and Sub-Event Type.
The Taxonomy Manager module may help you.


Show latest content date from group content type

After a some research and hit and trial I'm able to configure views output as per requirements with Views merge row module. Below are the steps I've followed:

Install Views Merge Row module.
Create a Views with group content type.
Select Format -> Card
Add fields:

Group Title
Content Changed on (relationship content)

In card settings Select "Group Field 1" as a Group Title.
Now under views Advance-settings Select "Merge rows"
Under Merge row settings select following configuration:

Field
Merge Option

Group Title
Use Values of this field as a filter

Content Changed
Use First Value of this Field

Sort -> Ascending


How to make users with administrator role member of all organic groups?

I found How,

go to your content type and change the widget for your field "og_group_ref" from OG_Reference to Select List


Is it possible to do a Drush make custom installation profile?

You can use the OPTIONAL ATTRIBUTES

root_element[first_key][next_key] = value

  The 'projects' attribute is where you define the modules/themes that
  are to be packaged with the profile. The first key is the short name
  of the project (as seen in the drupal.org/project/{projectshortname}
  URI).

  These projects are defined using the short form definition. You can
  use this form if you only want to declare the version of the
  project. The version is the value to the right of the core Drupal
  version in a full version string. For example, if you wanted to
  specify Views 7.x-3.1, you would use:

projects[views] = 3.1

  For pre-releases, like CTools 7.x-1.0-rc1, use this format:

projects[ctools] = 1.0-rc1

  You can also specify -dev releases of projects; however, this is
  generally NOT recommended, since it results in end users getting
  different sets of files at different times that distribution is
  built, which can cause confusing bug reports. If you really must use
  a -dev release, it's better to specify a Git revision (see below).

projects[media] = 2.x-dev

Reference

Full example drupal-org.make file.
Managing Drush make files for an installation profile.


How can I remove allowed values of a list field?

Have you got revisioning on for your content types? If so then those revisions will still be using the paragraph. You'll need to delete the revisions too before you can make the change


The association is stored in openid_connect_authmap and there is a service: openid_connect.authmap to access it.

Without DI:
\Drupal::service('openid_connect.authmap')
  ->getConnectedAccounts(\Drupal::entityTypeManager()->getStorage('user')->load($userid))


render form item of type text_format in twig file

It's unsafe to use the raw filter, better use the render element

  raw

  This filter should be avoided whenever possible, particularly if you're outputting data that could be user-entered. See this page
  for more information on auto-escape in Drupal 8.

processed_text:

return [
  '#theme' => 'mytwig',
  '#thankyou' => [
    '#type' => 'processed_text',
    '#text' => $thankyou_paid,
    '#format' => 'full_html',
  ],
];

To configure the text format visit /admin/config/content/formats and read the warnings

  Improper text format configuration is a security risk.

In this case it might be better to use Restricted HTML or Basic HTML.


How to pass a literal string into drush config-set

Short answer, preface the value with an empty space (inside the quotes).

This appears to be a drush bug. This fails with the unknown option bit:

drush config-set system.site name '--max-filesize=blah'

However, if I preface the value with a space:

drush config-set system.site name ' --max-filesize=blah'

this works as expected.

Edit: It is also worth noting that drush config-edit would bypass this issue altogether, and allow the value to be set via your preferred text editor.


Print module works best when you copy the library dompdf (or tcpdf) to the module folder directly. In this was you don't need to edit the file, and the print module will detect the library automatically.

Extract the dompdf directory into sites/all/modules/print so that you have dompdf_config.inc at sites/all/modules/print/dompdf/dompdf_config.inc.
Ensure that you have write access to PUBLIC/print_pdf/dompdf/fonts directory.
Your print module should now show the detection of the library at admin/config/user-interface/print/pdf.

You should now be able to export the nodes to PDF :)


How can I pass variables from views template to node template?

Possibly use devel and kint modules.

Once both modules are enabled add {{ kint(fields) }} or {{ kint(content) }} to see what your options are for displaying your view's data. If the view wrks successfully then you should be able to display it using twig e.g. if you find field_name in kint and it output's the correct data then add <p>{{ fields.field_name }}</p> to your template


I was able to fix this. I had to go into the database and manually delete the entry filter.mailchimp_campaing from the config table.


How to migrate from Commerce Kickstart to Drupal Commerce?

tl;dr - Essentially, you're building a new theme on top of a site that is populated with content:

  Find or create a new sub-theme (that doesn't use omega_kickstart as a parent).
  Create a new home page.
  Create new blocks for menus and taxonomy terms.
  Re-implement any social features you were using.
  Examine and fix any order, user, or content related problems.
  Enable the new theme and configuration.
  Disable all of the kickstart modules.
  Test and repeat until you're happy with the results.

More information:

Let's say you disable all of the Kickstart-specific modules by running these commands:

drush -y dis commerce_kickstart_block commerce_kickstart_blog commerce_kickstart_comment \
  commerce_kickstart_inline_help commerce_kickstart_menus commerce_kickstart_merchandising \
  commerce_kickstart_order commerce_kickstart_product commerce_kickstart_product_ui \
  commerce_kickstart_reset commerce_kickstart_search commerce_kickstart_slideshow \
  commerce_kickstart_social commerce_kickstart_taxonomy commerce_kickstart_user

And then you can disable the other modules:

drush -y dis commerce_kickstart_help commerce_kickstart_migrate

Here's a picture of what your site's homepage will look like if you afterwards (assuming you're still using the same base theme):

You'll find that:

All of the home page content is gone.
The menus are gone.
The admin menus are damaged but usable. (There appears to be a one-pixel line at the top of the page that allows you to click on menu items unless your screen is extremely wide.)
All of the theming done for products is gone.

The good news is that:

All of your content is still there.
Links to existing products will work (albeit not as pretty).
Administrative functionality is A-okay.

Given the current situation, you'll probably want to go ahead and create a new theme. I suppose you could sub-theme the existing theme, but I'm not sure why you would given that everything is now broken.

The homepage will also need to be replaced. Views, panels, or a node would all be good choices, depending on your needs. The rest of the blocks and menus will also need to be created as blocks and re-added to your theme, but you'd need to do this anyway so it's probably not a big deal.

Any other customizations around comments, users, orders, etc. will need to be reevaluated and implemented as you see fit.

Once you're happy, you'll just need to test, test, and test some more to make sure you've cleaned up all the edges.


Position Block Below Content but Above Editor

Omega based themes still allow for custom regions and various *.tpl.php files. There is probably a node.tpl.php theme file in the base theme thats inherited by the subtheme your using.

The code doesnt go in the tpl.php file it goes in the preprocess function:

  How to display block in node above comments. What i have tried is:
  create region - regions[above_comments] = Above comments after in
  template.php i have added this to THEME_preprocess_node

You then output the correct block within the specific region of the theme. In the linked page they created a region called Above comments in their theme. They set a block to that region using the Blocks Admin UI and rendered it using block_get_blocks_by_region using the theme preprocess function.


Clive is right that using the drupal theme system is your best bet if you're going to be doing significant variable manipulation but if you just want to load a big blob of HTML into your module you can do it a couple of ways in PHP.

For short blobs, try the EOF method

$str = <<<EOF

Hello

$world

  ... etc.
EOF;

For longer blobs, use file_get_contents()

$myhtml = file_get_contents(path_to_module().'/my_html.tpl');


Custom default value for Webform's select options component

All you need to do, it to put the key value into the default value field, in this case 2, to make Ms. the default value of the form. This is what the default value if used for.


User information based on external database

Personally, I would fetch and update the fields on Drupal when the user logins, and update the remote database when the user in Drupal is updated. If you user Profile2 you might have to use other hooks.

An other option may be running a script outside Drupal to synchronize the two databases.


tb-megamenu how to click to open/close sub menu in mobile

Then look far, the best I found in my case has been the following:

I have overridden the method (js) of tb MegaMenu and done through the function drupal

I created a copy of tb-megaMenu-frontend.js file and called tbmega-custom.js and saved in the js folder of my theme.
What added to the system through the function drupal js_alter.
In my theme in the file called template.php

function mytheme_js_alter (&$javascript){
    $javascript[drupal_get_path('module', 'tb_megamenu') . '/js/tb-megamenu-frontend.js']['data'] = path_to_theme() . '/js/tbmega-custom.js';
}

I have adjusted the code to my needs. Just change the behavior of tbMegaMenuAction:

 Drupal.behaviors.tbMegaMenuAction = {
    attach: function (context) {
        $('.tb-megamenu-button', context).once('menuIstance', function () {
        var This = this;
        $(This).click(function () {
            if (parseInt($(this).parent().children('.nav-collapse').height())) {
                $(this).parent().children('.nav-collapse').css({height: 0, overflow: 'hidden'});
                Drupal.TBMegaMenu.displayedMenuMobile = false;
            }
            else {
                $(this).parent().children('.nav-collapse').css({height: 'auto', overflow: 'visible'});
                Drupal.TBMegaMenu.displayedMenuMobile = true;
            }
        });
    });

    //Comment this for mobile click
    //var isTouch = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion);
    //if (isTouch) {

        $(document).ready(function ($) {
            var mm_duration = 0;
            $('.tb-megamenu').each(function () {
                if ($(this).data('duration')) {
                    mm_duration = $(this).data('duration');
                }
            });
            var mm_timeout = mm_duration ? 100 + mm_duration : 500;

            $('.nav > li, li.mega').click(function (event) {
                event.preventDefault();

                var $this = $(this);

                if ($this.hasClass('mega') && !$this.hasClass('clicado')) {

                    $('.nav > li, li.mega').each(function () {
                        $(this).removeClass('clicado open');
                    });

                    $this.addClass('clicado');
                    $this.addClass('animating');
                    clearTimeout($this.data('animatingTimeout'));
                    $this.data('animatingTimeout', setTimeout(function() {
                        $this.removeClass('animating')
                    }, mm_timeout));
                    clearTimeout($this.data('hoverTimeout'));
                    $this.data('hoverTimeout', setTimeout(function() {
                        $this.addClass('open')
                    }, 100));

                } else {

                    if($this.hasClass('mega') && $this.hasClass('clicado')) {

                        $this.removeClass('clicado');
                        $this.addClass('animating');
                        clearTimeout($this.data('animatingTimeout'));
                        $this.data('animatingTimeout', setTimeout(function() {
                            $this.removeClass('animating')
                        }, mm_timeout));
                        clearTimeout($this.data('hoverTimeout'));
                        $this.data('hoverTimeout', setTimeout(function() {
                            $this.removeClass('open')
                        }, 100));
                    }

                }

            });
        });

    //}

    $(window).resize(function () {
        var windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
        if (windowWidth != Drupal.TBMegaMenu.oldWindowWidth) {
            Drupal.TBMegaMenu.oldWindowWidth = windowWidth;
            Drupal.TBMegaMenu.menuResponsive();
        }
    });
  }
 }


field_deleted_date_N and field_deleted_revision_N not removed on cron run or field_purge_batch()

If drush doesn't help and running cron doesn't help, that might mean that the field data can't be purged because the module providing the field type has been disabled and / or uninstalled.
In that case just drop the tables manually.


How can I give permission to authenticated users to edit the content type 'ABC'?

Use Devel module, especially it's Node Acces tool:

Devel Node Access (DNA)
View the node access entries for the node(s) that are shown on a page. Essential for developers of node access modules and useful for site admins in debugging problems with those modules.

It will tell you exactly what permission is missing.
To debug for particular existing user, consider adding Masquerade to the mix:

The masquerade module is designed as a tool for site designers and site administrators. It allows a user with the right permissions to switch users.

That way you will be able to see DNA report just as the exact user who encountered problem.
What you should see is 2 lists:

If these look about right
Go to Home ⏩ Administration ⏩ Configuration ⏩ Content authoring and make sure your user has the proper text format permissions:


How do i get the all the regions available in the current theme programatically?

Active ADMIN theme & active SYSTEM theme might be different.(By default active admin theme is seven & active system theme is bartik)
Get the current theme used by the below code(if you are in admin section it will return seven, else bartik)

$theme = \Drupal::theme()->getActiveTheme()->getName();

As we need the system theme, below code will do the job

$theme = \Drupal::config('system.theme')->get('default');

And pass the theme name to get all the regions

$system_region = system_region_list($theme, $show = REGIONS_ALL);

This will give you all the regions in array format

$region_list =  json_decode(json_encode(system_region_list(\Drupal::config('system.theme')->get('default'),$show = REGIONS_ALL)),true);

Second part of the question

Get the blocks in particular region . Below is the code snippet which can get the blocks placed in pre-content region:

  $blocks = \Drupal::entityManager()
      ->getStorage('block')
      ->loadByProperties(array('theme' =>  \Drupal::config('system.theme')->get('default'),'region'=>'pre_content'));


How do I receive and record Paypal transaction variables from POST?

Look at the uc_paypal module included with Ubercart for a fantastic example of this. Look at uc_paypal_menu() (in uc_paypal.module) and uc_paypal_ipn() (in uc_paypal.pages.inc).


How to have a separate image style for an image field for the 1st views row?

A solution can be Add an Attachment Display to the View, in the Attachment you can select to show only one element with a different style and you can give as position Before.

In the Page then you select to skip 1 element.

This will output something like this:


Commerce Paypal WPP Sandbox: cURL error: SSL connect error

Ran this past some Paypal support personnel. They echoed both the author of the question and Nick in the comments.

Paypal reviewed the error and offered a link to this resource, which I will quote in part:

  PayPal is upgrading the protocols used to secure all external connections made to our systems. Transport Layer Security version 1.2 (TLS 1.2) and Hypertext Transfer Protocol version 1.1 (HTTP/1.1) will become mandatory for communication with PayPal in 2016. You will need to verify that your environment supports TLS 1.2 and HTTP/1.1, and if necessary make appropriate updates.

  PayPal is in the process of upgrading the SSL certificates used to secure our web sites and API endpoints. These new certificates will be signed using the SHA-256 algorithm and VeriSign's 2048-bit G5 Root Certificate. You will need to ensure that your environment supports the use of the SHA-256 signing algorithm and discontinue the use of SSL connections that rely on the VeriSign G2 Root Certificate.

  If you are using PayPal’s Instant Payment Notification (IPN) service, you will need to ensure that HTTPS is used when posting the message back to PayPal for verification. HTTP postbacks will no longer be supported.

Related Drupal.org Issue: https://www.drupal.org/node/2616730#comment-10782646

So, it seems, Paypal is upgrading lots of their security requirements for 2016. I highly recommend you investigate deeper with Paypal's support service to see if they can make a recommendation on next steps for you.


Get Last Node Access Timestamp Per Node by User

This doesn't work because the node is cached. Disabling caching of the node wouldn't be a good idea, performance-wise. Try instead a lazy builder to retrieve the access time and create a placeholder, so that the node can be cached, no matter how often the access time is updated:
/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mymodule_preprocess_node(&$variables) {
  $variables['content']['timestamp'] = [
    '#lazy_builder' => ['mymodule_timestamp_current_user', []],
    '#create_placeholder' => TRUE,
  ];
}

/**
 * #lazy_builder callback; builds timestamp markup with current user access time.
 */
function mymodule_timestamp_current_user() {
  $timestamp = \Drupal::currentUser()->getLastAccessedTime();
  return [
    '#markup' => $timestamp,
    '#cache' => ['max-age' => 0],
  ];
}

Drupal ^9: The callback needs to be in a class implementing TrustedCallbackInterface or RenderCallbackInterface. See https://drupal.stackexchange.com/a/303039/47547 for a code example.

Statistics
This code extends the code you had so far. If you are referring to statistical node view data have a look at the core Statistics module, which provides a timestamp when the node was last viewed. However, not on a per user basis, but this gives you an idea how you can record such statistical data.


Changing URL alias of webform breaks template

Check which template name Drupal suggests after you changed URL alias.

Enable debug option so you could see template name suggestions (they shown in the html source as commented out strings).

You should see something like this:

In your case the new suggestion could be:
webform-form--feedback.tpl.php or page--feedback.tpl.php


hook_libraries_info is not in core, it is from a contrib module:

Libraries API

This module provides the external libraries. It will be ported to drupal 8 and can be used the same way as in drupal 7.

In drupal 8 the libraries, that are defined in *.libraries.yml are seperate and should not be confused with the external libraries, despite their identical name. They are mainly for js and css packages, that are specific to one module, but can also be used by other modules. They can be a replacement for the external libraries, but do not provide the full functionality.

In the long run composer will probably be the way module developers will go for downloading external libraries. But for now this is an ongoing discussion how this can be implemented.

Your reference to https://www.drupal.org/node/1996238 is a seperate issue about the replacement of hook_library_info() in drupal 8 core. This must not be confused with the external libraries defined in hook_libraries_info().


Commerce Kickstart 2 Display color as visual colour

Go to Store setting -> Product settings -> Variation types -> your content type -> manage fields -> edit color(term reference)
enable the settings under "ATTRIBUTE FIELD SETTINGS"


Actually, it was not clear but there is an option in the theme itself to put change the phrase 'Select a page' and it becomes untranslatable. You have to remove it in the theme itself and change it in the file jquery.mobilemenu.js and then translate it through Drupal.


Using a View in a tooltip for an image map hover link

You can easily use replacement patterns to achieve something similar.
Add the fields you would want as the view and then in replacement pattern you can render a views block or even customize the display via html.


Go to your view. and Click on Taxonomy term to configure the field. Make sure to select the Thousand marker as <none>.

Then you can use this as replacement pattern in your href path


Let New Users Connect with Twitter OAuth only (not Facebook)

You can look into HybridAuth Social Login

  This module integrates HybridAuth library into Drupal and allows your
  users to login and register using:

  Facebook Twitter Google LinkedIn Foursquare Yahoo Windows Live MySpace
  AOL OpenID Github, LastFM, Vimeo, Disqus, Instagram, Viadeo, Identica,
  Tumblr, Goodreads, QQ, Sina, Murmur, Pixnet, Plurk, Skyrock, 500px,
  Vkontakte, Mail.ru, Yandex, Odnoklassniki, Twitch.tv, Steam and more

You can select which all social logins you want to enable. So if you are just looking for twitter you can enable that alone.


How can I override the container.html.twig template for one submit button only?

Based somewhat on kiemi's answer, you could go for something to this degree:

<?php

/**
 * Implements hook_theme_suggestions_container_alter().
 */
function yourtheme_theme_suggestions_container_alter(array &$suggestions, array $variables) {
  $pieces = [
    $variables['element']['#type'],
    $variables['element']['#name'],
    $variables['element']['#display_id'],
  ];
  $suggestions[] = 'container__' . implode('_', $pieces);
}

This will produce a suggestion, for example, of container--view-articles-featured.html.twig

Of course, if you want it to follow true Drupal template suggestion standards, you'll want to add several suggestions with varying levels of specificity.


Thank to Clive for guide me :

This is how i make a virtual field :

First you need to create the handler for the field :

<?php

namespace Drupal\boutique\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;

/**
 * Field handler to present the path to the node.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("totalCommandeTTC")
 */
class TotalTTC extends FieldPluginBase {

    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
        parent::init($view, $display, $options);

    }

    /**
     * {@inheritdoc}
     */
    public function query() {
        }

    /**
     * {@inheritdoc}
     */
    public function render(ResultRow $values) {
       return 'test';
    }

}

I remove the query for this handler.

Then in my module file, i use the hook_views_data :

function boutique_views_data()
{

  $data['commandes_entity'] = array(

      'totalCommandeTTC' => array(
          'title' => t('Total Commande TTC'),
          'help' => t("Le total TTC des commandes"),
          'field' => array(
              'id' => 'totalCommandeTTC',
          ),

      ),

  );

return $data;
}

And the result in views after add the field with views ui :

The field is Total commande TTC.


Records with identical uid and timestamp in node_revision

DISCLAIMER : Not a Drupal Developer, just a pure MySQL DBA
Here is a sample node_revision table:
mysql> show create table node_revisions\G
*************************** 1. row ***************************
       Table: node_revisions
Create Table: CREATE TABLE `node_revisions` (
  `nid` int(10) unsigned NOT NULL DEFAULT '0',
  `vid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL DEFAULT '0',
  `title` varchar(255) NOT NULL DEFAULT '',
  `body` longtext NOT NULL,
  `teaser` longtext NOT NULL,
  `log` longtext NOT NULL,
  `timestamp` int(11) NOT NULL DEFAULT '0',
  `format` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`vid`),
  KEY `nid` (`nid`),
  KEY `uid` (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=227825 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql>

Strictly in terms of MySQL, there is nothing in place to prevent the same UID and timestamp from entering this table multiple times. The index uid is a non-unique index on the uid column. What you need is a UNIQUE INDEX to prevent this at the database level.
Run this query:
SELECT uid,timestamp,COUNT(1) ut_dups FROM node_revisions
GROUP BY uid,timestamp HAVING COUNT(1) > 1;

and this will uncover other UIDs with the same timestamp issue.
If you want to block rows from entering this table with duplicate (uid,timestamp), change the indexes as follows (making a backup first):
#
# Backup node_revision
#
CREATE TABLE node_revision_backup LIKE node_revision;
INSERT INTO node_revision_backup SELECT * FROM node_revision;
#
# Change Indexes
#
CREATE TABLE node_revision_new LIKE node_revision;
ALTER TABLE node_revision_new DROP INDEX uid;
ALTER TABLE node_revision_new ADD UNIQUE INDEX uniq_uid_timestamp (uid,timestamp);
INSERT IGNORE INTO node_revision_new SELECT * FROM node_revision;
DROP TABLE node_revision;
ALTER TABLE node_revision_new RENAME node_revision;

The UNIQUE INDEX uniq_uid_timestamp physically prevents (uid,timestamp) from appearing more than once. Check the contents of node_revision and make sure it is proper.
If it looks good, you could run:
DROP TABLE node_revision_backup;

or keep the backup.
If it does not look good, run this:
ALTER TABLE node_revision RENAME node_revision_old;
ALTER TABLE node_revision_backup RENAME node_revision;
DROP TABLE node_revision_old;

Give it a Try !!!
CAVEAT
You will need to check all modules involved that writes to the node_revision table.


The following code is used because the module is already rendering the CCK field, and wants to avoid that Drupal renders the content of that field.

if (is_array($node->content['field_svar'])) {
  unset($node->content['field_svar']);
}

Without using that code, the field content will appear twice: once inside a field set, and once outside that field set.

The last parameters used for hook_nodeapi() are described from the documentation as:

  $a3

  For "view", passes in the $teaser parameter from node_view().
  For "validate", passes in the $form parameter from node_validate().

  $a4

  For "view", passes in the $page parameter from node_view().

It means that, when the operation is "view," $a3 is TRUE when Drupal is displaying the teaser (and FALSE when Drupal is displaying the full node content), and $a4 is TRUE when the node is being displayed alone in a page (and FALSE when the node is being displayed together other nodes in the same page).
To understand the meaning of the different values given to $a4, $a4 is TRUE when Drupal is displaying, for example, the page http://example.com/node/1 (where the same page displays only a node); its value is FALSE when Drupal is visualizing the front page and there are more than one node promoted to the front page.


custom views handler to show dynamic all profile fields

This is probably done better in a preprocess function in a theme instead. However if you want to do it you ned to create a handler, something like this:

class og_group_handler_field extends views_handler_field {
  function render() {
    $og = arg(1);
    $output
    // Load the group and add to $output what needs to be displayed
   return $output;
 }
 function query() {
   // Make sure we don't add anything to the queue.
  }
}

and the add the handler to a table like nodes

function module_views_data_alter(&$data) {
  $data['node']['og_all_group_fields_from_arg_1'] = array(
    'field' => array(
      'title' => 'title',
      'help' => 'Help Text',
      'handler' => 'og_group_handler_field',
    ),
  );
}

For Drupal 6 you also need to register the handler, the link you posted illustrates how this is done.


Personally, I think the only reason for choosing PostgreSQL over MySQL is if you (or your client) is already a PostgreSQL shop and have DBAs that know PostgreSQL well and know the ins-and-outs of babysitting it.  I would also say the same also applies for choosing MySQL over PostgreSQL, assuming you aren't using any contrib modules with MySQL-only functions in them.


How to get a field value in form validate

Refering to form API Drupal 7 for #value

$form['field_a']['und']['#value']

  Used by: button, hidden, image_button, submit, token, value

  Description: Used to set values that cannot be edited by the user.

For $form_state['values']['field_a']['und'][0]['value']

  $form_state is one of the arguments passed to a form submission
  handler, or a form validation handler; its main usage is to retrieve
  the values entered from the user in the form see the content of
  $form_state['values'])

So you should use $form_state['values']['field_a']['und'][0]['value']


Adjusting Apache Solr bias based on content length?

Under bias setting you should be able to reduce the priority of the fields. So reduce the priority of the fields that is not much important, and increase the priority of the fields that you would prefer for solar to prioritize.

The settings can be found on: admin/config/search/apachesolr/settings/solr/bias

0.1 is the lowest and 21.0 is the highest rating.


You may have been blacklisted by the server you're try to send mail to.  Check this first.

To help from being marked as spam send from an address ending with your domain name.

For example: do-not-reply@example.com or notifications@example.com

Then you can set the "Reply-To" header email address to your users email using hook_mail().

Something like this maybe?

$params['reply-to'] = $user->mail;

function HOOK_mail($key, &$message, $params) {
    switch ($key) {
        case 'your-key-here':
            $message['Reply-To'] = $params['reply-to'];
            $message['subject'] = $params['subject'];
            $message['body'] = $params['body'];
            $message['headers']['Reply-To'] = $params['reply-to'];
            $message['headers']['Return-Path'] = $params['return-path'];
            break;
    }
}

It has been forever and a day sense I've looked at this last, but you may want to scope out RFC822.

Note that ['Return-Path'] is important here as well if you monitor emails for bounces (hard/soft/etc).  Where ['Reply-To'] directs replies, I believe ['Return-Path'] directs bounces and errors.


How to Setup Multilingual Section (Not Site)

Yes you are right, internationalization is made for a full website in several languages. But you will be probably be able to achieve what you want by using views everywhere.

Instead of displaying a classical node, you will display a view with 1 node inside a block, inside a panel (probably).
You setup your view to use the language your want and the content type you want, that should do the trick. It's a bit different approach if you compare it with the standard drupal approach of creating page.

To ensure that the node page is not accessible, you can use the module node page disabled.

I hope it helps

Cheers


Where do I place custom PHP code (functions, classes) when creating a theme?

The theme's template.php is used for logic and data processing. See the Drupal theming guide.

From the guide:

  For all the conditional logic and data
  processing of the output, there is the
  template.php file. It is not required,
  but to keep the .tpl.php files tidy it
  can be used to hold preprocessors for
  generating variables before they are
  merged with the markup inside .tpl.php
  files. Custom functions, overriding
  theme functions or any other
  customization of the raw output should
  also be done here. This file must
  start with a PHP opening tag "<?php",
  but the close tag is not needed and it
  is recommended that you omit it.


Drupal 7 Views - Add a wrapper around rows for unformatted list from admin panel

Assuming you know how to override theme templates (that would be a separate question) you can override the views_view_unformatted.tpl.php template and make your override something like this:

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>

  <?php foreach ($rows as $id => $row): ?>
    <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"'; } ?>>
      <?php print $row; ?>

  <?php endforeach; ?>

You could also override the views-view.tpl.php template instead and in the part that says:

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

do something like

<?php if ($rows): ?>

      <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

It's up to you which way you want to do it.


How to stop menu links being disabled after saving nodes?

Here's a quick fix:

Download version 1.7 of i18n.
Unzip it and find the folder named i18n_menu
Go to your site's modules directory (could be /sites/all/modules/)
    Find the folder i18n
Replace the subfolder i18n/i18n_menu with the version from version
1.7 you downloaded in step 1

You can also check this bug report: http://drupal.org/node/1905268


Article page url in chinese language Drupal 7

This error might appear when the MySQL database is encoded as UTF8. In that case, Unicode characters represented with 4 bytes are not accepted. The accepted reply to the following StackOverflow question explains that the database needs to be encoded using the utf8mb4 encoding and the utf8mb4_unicode_ci collation:

https://stackoverflow.com/questions/10957238/incorrect-string-value-when-trying-to-insert-utf-8-into-mysql-via-jdbc

A more complete explanation about the utf8mb4 encoding on MySQL can be found here:

https://mathiasbynens.be/notes/mysql-utf8mb4

In case you need to re-encode your existing Drupal database, there is an experimental Drush command for it at UTF8MB4 Convert.


What is the substitute for update_sql() in D7?

No, it does not exist any longer. You need to use Schema API function dedicated for what you need to be done. For example to rename field you should use db_change_field.


User Profile Image not showing correctly

Go to this link
 your_url/admin/config/people/accounts

here you will see
 field
 "Picture upload dimensions"
  do not write any dimension in this field , save it and then add profile picture for user

this works in Drupal 7


What is the php code to display a field of a referenced node in the node form of the node that references the node?

One way is to use panels, I highly suggest this method. It might be complicated at first but no coding is required.

Enable the built in panels page for the path node/%node/edit.
Add a selection rule: node (from node being edited) is of bunle 'type A'
in context configuration page of enabled panel variant, create a relation using the entity reference field you have other.
in Panels content add each field of node being edited (and submit buttons too!).

or perhaps add the general form instead of each field individually.

again in add content, node section, choose rendered entity.

or create a view with a display of type content pane (ctools views content panes has to be enabled). Add a contextual filter of type nid, choose argument input: nid from context in view's configuration and use it to render the entity in panel. while adding this view to panel, choose the node you added with relationship.

Any way, the original question:
First, implement hook_field_extra_fields. take node module's node_field_extra_field as an example. or follow this question: how should I use hook_field_extra_fields()?

/**
 * Implements hook_field_extra_fields().
 */
function MODULE_field_extra_fields() {
   $etype = 'node';
   $bundle = 'content_type_a';
   $field_name = 'the_other_entity';
   $extra[$etype][$bundle]['form'][$field_name] = array(
     'label' => t('The other entity'),
    'description' => t('Renders the related entity'),
    'weight' => 0,
  );
  return $extra;
}

Next, taking node.module as an example, implement a form alter for your content type:

function MODULE_node_form_content_type_a_form_alter(&$f, &$fs) {
  $field_name = 'the_other_entity';
  $f[$field_name] = array(
    '#markup' => $the_mighty_markup,
  );
}

Here is another example how to do it: http://johnheaven.eu/en/extending-drupals-user-contact-form it attachs fields to contact form though.

And about the $the_mighty_markup, here you have to generate output of your entity. One suggested way is to create a view, add a contextual filter on nid to it, display the fields you want. Then in your code execute the view to generate the output:

$this_node = entity_metadata_wrapper('node', $this_node);
$other_node = $this_node->field_the_other_node_er->value();
$nid = $other_node->nid;
// or simply:
$nid = $this_node->field_the_other_node_er->nid->value();
$the_mighty_markup = views_embed_view('the_created_view_of_yours', 'master', $nid);

edit:
This is how to output a view: http://codekarate.com/blog/outputting-drupal-7-view-programmatically-contextual-filters-arguments


How to load field configurations in code

The terminology is a bit confusing (as usual with Drupal), but here goes:

Field storage configurations are defined by FieldStorageConfig. To load one, do this:

$field = Drupal::entityTypeManager()->getStorage('field_storage_config')->load('node.my_field');

Field instance configurations are defined by FieldConfig. To load one, do this:

$field_instance = Drupal::entityTypeManager()->getStorage('field_config')->load('node.my_content_type.my_field');


Solr multi-select facets occurs bad request error

I think you can update to the latest dev version.

For more info you could check this issue:

https://www.drupal.org/node/2290601


Pagerer

  Features:

  multi-pane pager
  Views pager plugin
  control whether to display links to pages, to items, or to item ranges
  direct input of the page to go to through an input widget
  selection of the page to go to through a jQuery UI slider
  selection of the page to go to through a client-side scrolling pager
  links to progressively more distant pages (like +10, + 20, +100, +200)
  adaptive logic links
  specify text to be used to render page separators (like a vertical bar) and page breakers (like an ellipsis)
  supports Views' AJAX enabled pager


Copying multiple components from another webform?

You can use Webform Template:

This module allows to easily copy webform configuration from one node to another (including all webform fields). If I remember well it copies all fields, you can't select wich fields to copy.

I've used it and worked fine.

EDIT: Adding more info:

The module doesn't allow you select which fields are going to be copied. Anyway, the module's code not long and it may be easy to add this funcionality. The module also triggers some cusom hook to modify webform (hook_webform_template_insert and hook_webform_template_update).

I think this would be a good starting point.

The heavy lifting seems to be done in the webform_template_node_update (hook_node_update).

// Insert the components into the database.
if (isset($node->webform['components']) && !empty($node->webform['components'])) {
  foreach ($node->webform['components'] as $cid => $component) {
    $component['nid'] = $node->nid;
    webform_component_insert($component);
  }
}

// Insert emails.
if (isset($node->webform['emails']) && !empty($node->webform['emails'])) {
  foreach ($node->webform['emails'] as $eid => $email) {
    $email['nid'] = $node->nid;
    webform_email_insert($email);
  }
}


Create link to node in specific language

$entity->toUrl('canonical', ['language' => $entity->language()]);
Taken from this question thread


Why is my Strongarm feature immediately overridden?

I can't tell why it's telling you something is changed, but you can use Diff module to see what changed. Diff module


How to create new node programmatically, when a new user is created, in Drupal 7?

It is correct that you need to implement hook_user_insert(). The code that needs to be implemented is different from the code you would implement in Drupal 6 because the node body is a field, in Drupal 7 (see Field API).

The implementation of hook_user_insert() should be similar to the following.

function mymodule_user_insert(&$edit, $account, $category) {
  $body_text = 'This is the text contained in the node body.'; // [1]
  $node = new stdClass();
  $node->type = 'article';  // [1]
  node_object_prepare($node);

  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

  $node->title    = 'Node Created Programmatically on ' . date('c'); // [1]
  $node->uid      = $account->uid;

  $path = 'content/programmatically_created_node_' . date('YmdHis'); // [1]
  $node->path = array('alias' => $path);

  node_save($node);
}

The lines marked with [1] are the parts that you need to personalize.


Create link (url) to the full node from a Solr view (search results) with rewrite results

I found the solution by Checking Retrieve result data from Solr in the solr server configuration (Advanced tab). After checking this box I am able to use {{ url }} in my view.


Fetch user's realname (from Name Field) within database query (or an alternative method)?

The Name project used entity fields that can be queried in the DB, just like any other field. All you need to know is the machine name of field that you attached to the user entity. To use your example above:

$result = db_query("
    SELECT
        field_data_field_user.field_user_target_id,
        nf.*,
        users.name
    FROM field_data_field_user
        JOIN users
            ON field_data_field_user.field_user_target_id=users.uid
        JOIN field_data_field_MY_NAME_FIELD AS nf
            ON nf.entity_id=users.uid AND nf.entity_type = 'user' AND nf.bundle = 'user'
    WHERE field_data_field_user.entity_id = :nid", $args);

All you need to do is replace MY_NAME_FIELD with the machine name of your actual field.  The result will be rows that contain name columns associated with the user reference.


What is the right way to print variables with Twig?

PHP

->get('field_example') and ->field_example

are the same and so is TWIG

.get('field_example') and .field_example

both get the field object (field item list) from which you can get the field value(s).

This only works for the variable node (or other entities when you are in a different template) and returns the raw values from the database. For example a date field would return a unix timestamp.

In contrast the content variable contains formatted data ready to be rendered. A date field would be rendered as configured in the content type in a human readable format.

So the answer is, you print variables by using content:

{{ content.field_example }}

Use node only when you need to process the raw data in some way where the formatted output won't work, like for example if you compare two dates you want to use a unix time stamp and not the formatted output.

Both methods are language aware, so there shouldn't be any problem from this side.

If you want to translate static text in twig use the |t filter:

<h4>{{ 'Related articles'|t }}</h4>


Relation vs. References vs. Entity Reference for managing node-reference-type relationships

As of March 2012, the References module project page is now recommending Entity Reference as a replacement.

For basic node-type references, Entity Reference is certainly easier to set up than Relation.  I think a good general rule would be

  If you can do what you want with Entity Reference, use that.  Otherwise, go with Relation.


This has been answered before, but I can't mark it as a duplicate or flag.

You can use the the Plupload module to allow multiple uploads and even set limits by going into the code.


Get node ID or URL in Twig on field level

The node in a field template is the parent entity you find in element['#object'], which you can use to build the path:

{{ path('entity.node.canonical', {'node':  element['#object'].id}) }}


Instead of adding three template files for three nodes with the same content in it in my opinion will be a better solution to add the JS file conditionally using drupal_add_js

For eg:

 $allowed_nid = array(28, 1212, 38);
 if(in_array(arg(1), $allowed_nid)){
  drupal_add_js("http://www.examp.com/scripts/invitation.ashx?company=4444", "external");
 }

You can add the snippet in a hook_init function in any of your custom modules. (Best is add in a custom utility module which hold all general function to be used throughout.)
Else you can add it in your theme's template.php in the template_preprocess_page function.


How to create a view which would list related content for current article?

Ignore using fields in the View. This has been and will always be problematic IMO for 95% of Views people are making.

You need the Content ID argument from the URL so the correct node is selected, but here is where it takes a turn:

Set the view to show "Content" and give it a view mode, for instance, create a view mode called "Related Content" for nodes. In the field display for that view mode, only set the "Related Articles" field to be visible. Set its field formatter to "Rendered Entity", and create a view mode for that content type and theme it. On that content type, you would have title and body, or whatever fields you want to show (hard to tell without seeing a design).

Now the View will pull the node, render it, and in turn render the nodes that are being referenced in a view mode.

Then, you would get something like this, for example:

That is a View that looks at the current node, and renders it. The view mode has a field (Related Content), which is a node reference, and those nodes are rendering in a "Preview" view mode - and this is the result. All of the markup lives in two twig files (for the node--node-type--view-mode.html.twig) and the Views configuration is super simple.

The Views display would be a block, and you can place that block in whatever region works for you.


Users who have not uploaded a picture (also the anonymous user) will not have any object set for $account->picture. You just need to check that there is an object available:

$uri = isset($account->picture->uri) ? $account->picture->uri : NULL;

image_style_url() will return a bogus URI when passed NULL. You'll want to handle this somehow.

Note:
The user picture is already available as a field, you don't need PHP to get it.

In views 3, you must first add the "Content: Author" relationship before the User fields (including one for the user picture) will show up.


Dynamically display view block based on based on different view filters

We did something similar on our site -- on the left hand side we had a list of lesson plans, and when you clicked one, it used AJAX to dynamically update the lesson pane on the right. Sounds basically like what you want.

Here's the set up:

Make a view with both a block and a page, and configure the block so that the two show up on the same page. (example.com/my-view should show the block on the left side and the page on the right side.)

In the block body, he put the list of lessons alongside the following code in <script> tags:

$('.lesson').on('click', function(e) {
   e.preventDefault();
   // loads lesson into the content part of the page
   var contextualFilter = $(this).text(); // get the lesson title from the selection
   var AJAXPromise = AJAXLesson(contextualFilter); // get lesson from server and load into the content part of the page
   AJAXPromise.done(function() {
      // make promise, waiting for ajax call to return before changing URL and sending analytics page view
      window.history.pushState(contextualFilter, "", "http://example.com/my-view/" + SpaceEncodeString(contextualFilter)); // change URL to requested lesson with dashes instead of spaces
   })
});

Where AJAXLesson() is a function that returns a $.ajax({ ... }); object with the lesson plan data.

function AJAXLesson(lessonName) {
   // loads lesson from server
   return $.ajax({
      url: 'http://example.com/views/ajax',
      type: 'post',
      data: {
         view_name: 'myview',
         view_display_id: 'lessons', // this'll be different for you
         view_args: SpaceEncodeString(lessonName), // removes spaces and replaces with dashes
      },
      dataType: 'json',
      success: function(response) {
         if (response[1] !== undefined) {
            document.title = lessonName; // change page title
            $('#block-system-main').html(response[1].data); // CRITICAL: paste lesson in content
         }
      }
   });
}

Your code will look different, but that's the basic concept anyway.


How to order by a column with NULL values in it due to leftJoin?

One solution I found is based on this response:
https://stackoverflow.com/a/4326579/1214689

$query->addExpression('ffp.delta IS NULL', 'featured_delta_is_null');
$query->orderBy('featured_delta_is_null');
$query->orderBy('ffp.delta');
$query->orderBy('fp.delta');

Since sorting on the featured delta will place items with Null values at the top of the list, we need to sort featured delta in two pieces, first by those that aren't NULL (by converting to a boolean, those are lower than the ones that are NULL), then sort on the actual delta for those values that aren't null, this will leave all the other values out to be sorted by the delta on the non featured ('field_publications') field.


List field: translated values are not translated

Ok, it seems that it was just a weird cache thing. I cleared the cache several times after changing these translations. Now the translated values of the select list appear without setting the field to be translatable.


How to use % arguments in Easy Breadcrumbs "Paths to replace with custom breadcrumbs"

There is a patch here in progress to allow wild cards in breadcrumbs:

https://www.drupal.org/project/easy_breadcrumb/issues/3051106


How did you migrate the content from the nond-drupal tables to nodes?  Module or custom code?

I would suggest a 'custom' migration routine/module (if it is a lot of data you can do this as a cron and/or batch job - that is a separate discussion).

Any case, in your custom routine, when you migrate each record (so read a record form your table and create a new node) from items and actions - you will be able to 'capture' the node id (nid) if the new node.  Save this value to your 'old' items/actions tables (new field required).  Now when you step through your item actions table you can use the nid saved in items and actions as reference values.


Your theme may create node--view--CONTENTTYPE.tpl.php but per content type theme suggestions are not provided out of the box. Your theme layer or a custom module typically provides the theme suggestion, there are a ton of tutorials online about this.

I recommend installing Devel Themer to inspect the View theme template file usage on the page for Teams. Then see why/if the Managers is failing by visiting that page.

Then look through your theme sourcecode and custom modules to see what is providing the hook_theme suggestions.


Having trouble using responsive feature of Superfish

I ran into the same problem a while ago, and wound up writing some javascript/css to convert a multi-level superfish menu into a windowshade-style menu. It wasn't very elegant, though, and I later found the Responsive Menus module - it was very easy to set up, from what I remember, and worked with Superfish right out of the box. It also provides several styles of mobile navigation -- though not a select menu, if that's specifically what you want.


What to do if we want a input format for select options of a webform?

I recommend the chosen module.

https://drupal.org/project/chosen

Its goal is to make input element a little more user friendly.

See here: http://harvesthq.github.io/chosen/


This depends on if you are trying to get the value of the field or the rendered output of the field.

If you just want the value of the field you can do this in the same way in Drupal 7. Instead of

 $node->content['field_name']['#value'];

you need to specify a language and the a number for the field value you want (even if the field doesn't accept multiple values).

 $node->field_name[$node->language][0]['value'];

If you have the entity api module installed you can use the entity_metadata_wrapper function which is a little cleaner: http://drupal.org/node/1021556

If you want the rendered output, use node_view:

 if (arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_view(node_load(arg(1));
    print drupal_render($node['field_name']);
  }

The rendered output will give you the properly themed output, something closer to:

"

field value

"


How do I change the edit form layout for a custom field type

This is off the top of my head, so there might be a few kinks.
The way I would do it would be to:

Add a new class to each of the form elements that your module produces
Create some CSS to pad the top/bottom of elements with this class
Tell Drupal to include this CSS file whenever the form elements are on the page

In your Widget file add the following to each element to add an additional class to the form elements.

'#attributes' => [
  'class' => 'address_widget_class',
],

To add CSS styles to a custom module, you will need to create a few files and directories.

module/module.libraries.yml
module/css/style.css

In your CSS file, add the following to add 10 pixels above and below each item.

.address_widget_class {
  margin: 10px 0;
}

Next, you need to tell Drupal that the CSS file exists. In the module.libraries.yml file, add the following code.

style_name:
  version: 1.x
  css:
    component:
      css/style.css: {}

Finally, to include the library when the element is used, add the following to your Widget.

$element['street']['#attached']['library'][] = 'module/style_name';


I believe this module will do the trick:

ImageCache Actions

  Effects provided

  ...

  Aspect Switcher - lets you perform different actions or use different    dimensions based on whether the image is 'landscape' or
  'portrait'


Is this possible? Dynamically changing fieldsets on node creation

You probably could apply some woodoo to save the data :) But : you would have hard times retreiving it. Node displays only the defined fields, Views only show the fields and so on.

I would suggest not using webform, but simply defining those quizes as new node types and save them, together witha reference to a record about the answer (if it is important).

It might be handy to use eck instead and create an entity type and bundles for each quiz - so you dont have to deal with all the settings on node, just the fields.


Yes that is possible. Download the modules from: https://www.drupal.org/project/commerce

You can not install the install profile (https://www.drupal.org/project/commerce_kickstart) on top of an existing Drupal website.


Drupal 8: Pdf (print) search results (search_api)

You can use hook_entity_view_alter() to hidden PDF export link. Sample

<?php

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

function examples_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity->getType();
  $mode = $display->getMode();
  //Replace node type with text **page**
  if ($type == 'page' && $mode == 'search_result') {
    unset($build['entity_print_view']);
  }
}