Multistep ajax form, rebuild form and replace contents with the current step

You dont' have to call drupal_get_form explicitly, instead mark form to rebuild.

In your ajax powerd element define two attributes: #submit, and #ajax.

#submit references the function that makes the action related to the submission  (in your case changing the step value to 2 in form state). Also, set $form_state['rebuild'] to TRUE.

#ajax, where you set the ajax parameters and the PHP function that will return the result form the built form (in this case, the rebuilt one). When this fucntion is called form is build (or rebuilt) and you only have to return the form part you need.

Take into account that in the #ajax attribute you can set the HTMl element that will be replaced by the answer, so you don't need to use ajax commands.

<?php

  funtion my_form_builder($form, &$form_state) {
     if (empty($form_state['step'])) {
      $form_state['step'] = 'step_1';
     }
     $step = & $form_state['step'];
     // build step 1
     if ($step == 'step_1') {
       $form['first_submit'] = array(
         '#type' => 'submit',
         '#ajax' => array(
           'callback' => 'form_first_ajax_callback',
          ),
         '#executes_submit_callback' => TRUE,
         '#submit' => array('my_form_builder_callback'),
       );
     }
     // build step 2
     if ($step == 'step_2') {
       $form['elem_2'] = array(...)
       $form['elem_2_1'] = array(...)
     }
     return $form;
  }

  function my_form_builder_callback($form, &$form_state) {
     $current_step = & $form_state['step'];
     // store values...
     // move on to the next step
     $current_step = 'step_2';
     $form_state['rebuild'] = TRUE;
  }

  function form_first_ajax_callback($form, &$form_state) {

  $commands[] = ajax_command_replace('#main-content', render(form['element_to_return']));
  return array(
   '#type' => 'ajax',
   '#commands' => $commands,
  );
  }

Example uses the ajax commands aproach.

Check the Form API internal workflow illustration.


For Drupal 7, you can use the Field Weight module to change the field order per node.
http://drupal.org/project/field_weight

I've used it with no trouble.


If specific means fixed, you can use fixed value for context filter.

Add contextual filter Content: Nid.
Allow multiple values for this filter in More fieldset.
Input your NIDs as a default value, where + means OR:

In some cases Nodequeue can be useful.


Why Views Slideshow JCarousel plugin isn't available on view format settings?

There is nothing wrong. jQuery Cycle is the default library used by the Views Slideshow Cycle module.

Look instead at "Widgets" on the format settings screen. The relevant configuration options will appear by selecting "Pager" under either Top Widgets or Bottom widgets.

From the Views Slideshow JCarousel project page:

  Currently provides a JCarousel pager widget.

and

  Under the Format heading, click "format" and select "slideshow". You
  should now be able to select and configure your jcarousel slideshow.
  Pager options are on this configuration screen, not under views "pager
  settings". To decide where you want your pager to go, you can tick the
  pager widget checkbox beneath the area you wish to show it. your
  choices are "top" or "bottom" of carousel.

Note: If using Views Slideshow Cycle, you will need to download the jQuery Cycle plugin.


Is there a way to turn off the paypal checkout button in /cart view in drupal 7 commerce?

If found a simple way to disable the button through rules.

Edit the configuration of the Paypal EC payment method and add a condition to the rule:

Data Comparison / Commerce Order...state / Equal to 'Checkout'

In this way, when the order is still in Shopping Cart state the payment method is disabled.


A way to determine where a URL is being generated?

In Drupal 6 many different things use the PathAuto module to quickly create URL Aliases for your content.

Automatic generation of aliases, the code that controls the administration and application of patterns, the database schema definitions & more can be found within the module.

To answer your original question, it depends on what is creating that alias, a node or view or taxonomy page or whatever, but more times than not pathauto will be involved.

To see the automatic alias settings go to : admin/build/path/pathauto


How to get path of an element of a kint printed array?

you need to install and enable Search kint module


Drupal 7 View tab on user profile empty as default?

The user view tab should include the default user entity_view information as per

user_view and
user_build_content

Normally that's information such as the history / length of time since registration and other default content.


Node edit form shows cached or previous title while editing node, after updating node?

I have switched to below for cache and removed memcached completely. All problems solved with this.

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

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

Thanks!


How to add custom input type button in forms?

It's not converting it to a submit button type, they are different

Form items of type "button" will trigger the form submission but won't trigger the hook_form_submits like a form item of type "submit" does. It's eseentially a blank button apart from hook_validate is called but in there you can do whatever special functionality your button is supposed to do


How to access a contributed module Information from drupal.org

An update URL is formatted as:

http://updates.drupal.org/release-history/[project-name]/[api-version]

So for Views v7, for example, that would be:

http://updates.drupal.org/release-history/views/7.x

I think that's as much information as Drupal.org makes available about modules via its API. You won't find a structured way to query information about hooks, for the same reasons we talked about in your similar recent question


Form in controller does not render as usual

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

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

example.routing.yml:

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

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

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


What is the correct way to implement a custom block with twig template?

You're almost there. In your WzmSocialIconsBlock.php return the following:

return array(
  '#theme' => 'block_wzm_social_icons',
  '#url' => $sUrl,
  '#urlencoded' => $sUrlEncoded,
);

You might also want to simplify your hook_theme by letting it autodetect your template by name:

return array('block_wzm_social_icons' =>
  array(
    'variables' => array(
      'url' => null,
      'urlencoded' => null
    ),
);

And name your template templates/block-wzm-social-icons.html.twig.


Drupal can't create image styles for files located in theme directory

core module Image Style allow only images from

public:// file system (sites/default/files).

For using image styles with any other images, you should install the Imagecache External module.

  Imagecache External is a utility module that allows you to store external images on your server and apply your own imagecache (D6) / Image Styles (D7).


How To Assign Breadcrumb To Commerce Kickstart Omega Collection Or Category?

Version:
First, i usually work with the latest Crumbs version from the 7.x-2.x branch.
If you have problems with the latest version, you should report them in the issue queue. But then you can downgrade either to 7.x-2.0-beta13 or to the 7.x-1.x branch.
Upgrade and downgrade should work fine (I think), but you should clear the caches if you do. Also I don't guarantee if your Crumbs settings are all kept or some of them are lost. Let me know in the comments :)
(Probably this paragraph will soon be obsolete)

Entity parent settings:
I don't remember how much of that is in the 7.x-1.x branch. But in the recent versions, you go to admin/structure/crumbs/entity-parent/taxonomy-term and configure the parent path. That's it.

Plugin weights:
The plugin will be available as crumbs.entityParent.taxonomy_term.categories on the weights configuration form. But probably you don't need to do anything there, the plugin will already be enabled through the general wildcard "*".


How to create a relationship between user and some content type?

but I want to keep record of this, it mean the property detail page would always shows the previous tenant and owner information. And later that I want to show the reviews of user under owner and tenant tabs.

The initial question sounds simple but the added comment turns it
into a fairly complicated site build which I believe is outside the
scope of StackExchange questions. I'm just going to give the OP a brief overview of what I would do. Mods, feel free to edit or whatever you need to do.

So along with normal fields like images, locations etc., you need a place to store all of the information relating to each owner or tenant in each property.. The screenshot below gives a basic example of this.

Field Collection will let you store this information. You should have one field collection for owners and another for tenants. All reviews etc. of each person will have to be inside a field collection. Or reference a field collection using the module below.

Entity Reference will let you reference the people and vice versa. You'll use this a massive amount on a site like this for almost everything.

Entity Forms + Rules should allow tenants / owners to create property and also add themselves to a property by creating field collections from form data. You don't want to give them the ability to change other people's data so forms are essential.

Entity Reference Prepopulate will be essential for pre-filling form data and then disabling or hiding fields. This way, people can't view the workings of your site and more importantly, add and edit whatever they like. (for a regular end-user anyway).

Etc. Etc. Etc.

Anyways, that should be enough for you to look at for a couple of months. Good luck!


Error when using LDAP Views within Rules

I solved the problem by another way :

Within Rules :
First action : create a new entity (user) set the account name, set the account email with a fake value in the email.
Second action : unblock user (if blocked, the user account will not be synchronized from LDAP)

Then , when the account is created, the Drupal account is automatically synchronized from LDAP and get the good email.

(In LDAP configuration , be sure to configre LDAP User / BASIC PROVISIONING TO DRUPAL ACCOUNT SETTINGS/ Drupal Account Provisioning Events to  "Create or Synch to Drupal user anytime a Drupal user account is created or updated."


As @tenken says, on the WYSIWYG profile edit page, under the 'CSS' panel, in the 'CSS path' filed you can link to a CSS file to be used on the edit view.

/admin/config/content/wysiwyg/profile/PROFILE-NAME/edit


How to input search terms via a separate form on a content page to a Views Exposed Filter on a different page?

It is possible to use dpm() to understand the form data. In a custom module, you can use hook_form_alter() to act on the exposed filter form.

It would look something like this:

function example_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    dpm($form);
  }
}

You can then set the action.

function example_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $form['#action'] = '/path-to-panel';
  }
}

Just beware that this will alter all the exposed filters on the site. You can create a different if statement to target them more specifically if you have more than one.


Set datetime timezone when posting data via JSON api

In DateTimeNormalizer, the inferface format is RFC3339, which is Y-m-d\TH:i:sP as an input format string.  It also accepts the ISO8601 PHP string, which is Y-m-d\TH:i:sO

Try using strings like in your request '2020-02-20T13:15:00+01:00'.

What I suspect is happening, is that since you aren't specifying the UTC offset, it is being interpreted as '+00:00'

The denormalizer also allepts a format string with the request to parse the value.  I believe it is called format

See also DateTimeNormalizerTest and EntityTestDatetimeTest for some more examples.


if empty statements in views fields or field templates

First of all, there is no such thing as $empty in views-view-field.tpl.php

Second, if you're not printing anything when the output is empty, then there is no need to add an else statement. Thus, this should do the trick:

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

<?php print $output; ?>

<?php endif; ?>

The first line means if NOT empty, in PHP ! = not.


Here is a good tutorial in Custom buttons on CKEditor or Adding CKEditor Plugins Manually in Drupal .
Before asking the question you should have let us know what you have done so far.

If you were checked the links, you would see that in the Adding CKEditor Plugins Manually in Drupal and Add Plugin Part of CKEditor Module section it explained where to put the plugin.


How can I check in Drupal 8 an externally set $_COOKIE?

For external cookies please try with $_COOKIE['cookie_name'].

if (isset($_COOKIE['cookie_name'])) {
  print($_COOKIE['cookie_name']);
}

The code will print out the value of the cookie if present.

For a more specific answer please explain your question.Ty!


How to get rid of a style attribute so my nivo slider will show up?

https://www.drupal.org/node/229348 Gives a lot of good information on the subject.


comment_admin_overview() is a form function in Drupal 7 (it was a theme function in 4, 5 & 6).

You can use hook_form_alter() to make your changes instead.


Use the built-in aliasing built into the path module:

Navigate to /admin/config/search/path/add
Add /node/add/survey to Existing system path
Add /make-survey to Path alias
Click Save

The new /make-survey alias will now map to your survey add form.


Most efficient way to do simple Entity API queries by node id and content type?

I don't know how your module URL/API is structured, but if your module route has something like myapi/foo/bar/(id) to return a node object, you could upcast it instead. Here is an example from the node module:

entity.node.version_history:
  path: '/node/{node}/revisions'
  defaults:
    _title: 'Revisions'
    _controller: '\Drupal\node\Controller\NodeController::revisionOverview'
  requirements:
    node: \d+

{node} will be upcast to a node object and available in the incoming request to the receiving class.

See: https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes

So when you pass that to the receiving method:

use Drupal\node\NodeInterface;

class ExampleController {
  public function foo(NodeInterface $node) {
    if ($node->getType() != 'application') {
      // do something, throw Exception, etc?
    }

    // Otherwise this node is an application type.
    return $node;
  }
}

There may be a way to expand on this in the route definition, so you can upcast the node and ensure it is a specific type before doing anything else, eliminating the checking in the method - but I am not sure.

Perhaps:

https://symfony.com/doc/3.4/routing/requirements.html
https://symfony.com/doc/3.4/routing/conditions.html


How to view PDF files in a modal/overlay

PDF Reader does not require you to create node. It only requires you to have file in a field, in any kind of entity. If your file is managed, something uses it (in usage table). just expose that data to entity api, make file a field and you are good.

If you want to avoid entities, this module is open source. Use it as a learning tool. Borrow it's code. Give credit where credit is due, and use as you need.


Print an object value from a twig template?

You can get the created value from the entity profile:

{{ profile.created.value }}

or formatted:

   {{ profile.created.value|format_date('long') }}


Where to modify the logic that calculates the height of a collapsible fieldset?

Are you sure it can't be solved by CSS? Try adding some padding.


how to a translatable string in drupal theme?

The first step to translate a string used from a module, or a theme is using t() for every string that needs to be translated. Remember that the first argument given to the function is a literal string containing a phrase in English. This means that the following calls to t() are not correct.

// The string is a concatenation of literal strings.
$error = t('This example, ' . "doesn't work.");

// Also in this case there is a concatenation of literal strings.
$errno = 15;
$error = t("Error number $errno received while translating a string.");

// This could work, provided that another function calls t() using a
// literal string that is equal to the string returned from the function.
$error = t(mymodule_get_error());

The second step is providing the translation of the string passed to t(). If the theme is hosted on Drupal.org, then the translation will be provided from translators on http://localize.drupal.org.
Otherwise, you need to translate the string on admin/build/translate/search.

You can look for the string to translate searching for untranslated strings, or entering a string.


Display comment box to the author of the node being referenced using panels

Database query would help you.

function my_module_get_author_by_nid($node_nid) {
  $author = '';
  if (is_numeric($node_nid) && $node_nid != 0) {
    $uid = db_select('node', 'n')
        ->fields('n', array('uid'))
        ->condition('nid', $node_nid, '=')
        ->execute()
        ->fetchField();
    return $uid;
  }
}

// And then a slight change in your code

    global $user;
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      // Get the nid
      $nid = arg(1);

      // Load the node if you need to
      $node = node_load($nid);
    }

     // Get Reference Node Nid
    $reference_nid = $node->your_reference_field_name[$node->language][0]['target_id'];
    // Get Author for reference Node
   $reference_author =  my_module_get_author_by_nid($reference_nid);
    if($node->uid == $user->uid || $user->uid == $reference_author){
      return TRUE;
    } else {
      return FALSE;
    }


I don't think you can force javascript to only run once. In addition to big pipe, any lazy loader, ajax form update (consider entity reference fields), or other ajax functionality on the page can trigger javascript to run again.

This is the issue that jQuery.once() addresses, and the reason it is used. It adds a class on the element, then executes on elements that do not have the class and adds the class. I expect you could reproduce this with something like the following.

const usaButton = document.querySelector('[data-sales-switcher="83"]');
if (!usaButton.classList.contains('node-page-filters-sales-once') {
  usaButton.style.border = '6px solid orange';
  usaButton.classList.add('node-page-filters-sales-once');
}


How do I get a URL variable in a template?

Ok nevermind. On the other stack I mentioned the function was

function riptide7_preprocess_page_title(&$variables) {
  $variables['url'] = $_SERVER['REQUEST_URI'];
  $variables['#cache']['contexts'][] = 'url.path';
    echo "What?!";
}

and I just had to change preprocess_page_title to preprocess_page


Commerce-Marketplace : Members tab in store's page doesn't show up

Problem resolved after this update : https://www.drupal.org/node/2284457#comment-8962135


How to define path in anchor tag in blocks?

You can use the base_path() function to get the url with trailing slash '/'


How to change all iterations of a string to another word?

Method 1: Edit settings.php file

Pros

Quick method for small number of strings.
Less accessible in cases where you want to retain some control even after granting administrator access.

Cons

English only.
No admin pages, requires access to files on server (FTP / SFTP / SSH).
Difficult to delegate changes to non-developers.

Procedure

Edit settings.php for the site in question.

You'll need to either download the file, edit it, and re-upload it, or edit it in place on the server. Of course, make a backup.
Either way, you'll probably need to temporarily change the permissions of the file and its containing folder to to give you "write access". Be sure to take note of the permissions and change them back to what they were afterwards.
The default settings file is in drupal_root_folder/sites/default/settings.php

Look for this code at the bottom

# $conf['locale_custom_strings_en'][''] = array(
#   'Old string 1'      => 'New string 1',
#   'Old string 2'      => 'New string 2',
# );

Remove the comment marks ('#') and add string replacement assignments:

Method 2: String Overrides module

Pros

Admin page for managing string replacements.
Uses access permissions. Easier to delegate management of replacements.

Cons

Yet another module to install, update, and administer.
Possible performance hit and more difficulty to deploy (stores replacements in the database).
Uses access permissions. Harder to restrict changes when you have to give administrator access to others.

Procedure

Install and enable the module.
Follow the instructions / documentation for adding string replacements.

Method 3: hook_boot()

Procedure

Implement the hook_boot()
Use the same array as in the settings.php.

/**
  * Implements hook_boot().
  */
 function mymodule_boot() {
   global $conf;
   $conf['locale_custom_strings_en'][''] = array(
     'Old string 1'      => 'New string 1',
     'Old string 2'      => 'New string 2',
   );
 }

Method 4: Replace all the strings in the database

Procedure

Dump the database to a text file.

mysqldump -u user -p databasename > ./db.sql

Run a sed command to find/replace target string

sed -i 's/oldString/newString/g' ./db.sql

Reload the database back into MySQL.

mysql -u user -p databasename < ./db.sql

Note: All commands are bash commands on Linux, but you can replace them with another method.

References:

https://www.drupal.org/node/522036
https://stackoverflow.com/q/11839060/3653989


The user-profile.tpl.php file won´t be recognized in my Drupal 7 installation

You could try adding your content in the user profile template preprocess function instead.

e.g, in template.php:

/**
 * Implements hook_preprocess_user_profile
 */
function THEMENAME_preprocess_user_profile(&$variables) {
  // Fetch relevant user account
  $account = $variables['elements']['#account'];
  // Add content to user profile render array
  $variables['user_profile'][] = array(
    '#type' => 'markup',
    '#markup' => 'Hello world'
  );
}

After adding a new preprocess function, clear theme registry cache, e.g at Admin > Performance > Clear all caches


on delete of one field delete other field too

You can use hook_field_delete to determine which field is removed, and if its "yours" - find out which field you need to delete next and delete it

function hook_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
   if ($field['field_name'] == 'YOUR_FIELD_NAME') {
       //do some stuff to determine which
       //field you need to delete
       //and delete it
       //how to remove the field - the link below
   }

}

how to remove the field


How to get the Bootstrap 3 Datepicker to redirect to an URL when a date is picked?

You can redirect using ajax forms and ctools, first of all you will need to add #ajax property to your form field so the code will be :

function rbg_date_picker($form, &$form_state) {
  $form['date'] = array(
    '#type' => 'date_text',
    '#bdtpicker' => TRUE,
    '#date_format' => 'Y-m',
    '#datepicker_chain' => array(
      'my_interval_end[date]' => 'next',
    ),
    '#datepicker_options' => array(
      'viewMode' => 'months',
    ),
    '#ajax' => array(
      'callback' => 'SOME_FUNCTION_NAME',
    ),
  );
  return $form;
}

The rest is easy, in callback function you will need to have some code like below :

function SOME_FUNCTION_NAME($form,$form_state) {
  $time = $form_state['values']['date']; // maybe need ['und'][0]['value']
  //Some code to fetch desired values from date like month or year
  ctools_include('ajax');
  ctools_add_js('ajax-responder');
  //Some code to fetch desired values from form and compute 'some-valid-url'.
  $commands[] = ctools_ajax_command_redirect('some-valid-url');
  print ajax_render($commands);
  exit;
}


Importing dates TO and FROM using Feeds module

Nevermind, I discovered these can be handled by specifying the Date: Start and Date: End fields in the Feeds importer itself; sweet.


Adding placeholders to the user login block's username and password input fields

In twig it's difficult to target a specific input field. You can do this more efficient in a form alter hook, which you can use in themes too:

mytheme.theme

function mytheme_form_user_login_form_alter(&$form, $form_state) {
  $form['name']['#placeholder'] = t('placeholder for username');
}


Drush install fails within Vagrant Puppet

The drush.pp you are using is out of date.  I have used that one successfully in the past, but just a few days ago, Drush switched to using Composer to install, so running drush status will no longer download the console table.  Instead, you must run composer install after pulling Drush, or just install Drush via composer.  See the Drush project page for details.

The Drush Puppet module you mention will need to be updated to adjust for this change in procedure.

Note:  The drush.pp you are using would probably work if you told it to check out one of the Drush 6.x tags instead of using master (the default).  Haven't tried that, though.


What function should I use to truncate a string?

truncate_utf8() is present in all Drupal versions; just check that the parameters are the same.


mkdir permission denied error when running Browser based test

Maybe the Permission problems section of Running PHPUnit tests can help you:

Note: functional tests have to be invoked with a user in the same group as the web server user. You can either configure Apache (or nginx) to run as your own system user or run tests as a privileged user instead.
To develop locally, a straightforward - but also less secure - approach is to run tests as your own system user. To achieve that, change the default Apache user to run as your system user. Typically, you'd need to modify /etc/apache2/envvars on Linux or /etc/apache2/httpd.conf on Mac.
Example for Linux:

export APACHE_RUN_USER=<your-user>
export APACHE_RUN_GROUP=<your-group>

If the default user is e.g. www-data, the above functional tests will have to be invoked with sudo instead:

export SIMPLETEST_DB='mysql://root@localhost/dev_d8'
export SIMPLETEST_BASE_URL='http://d8.dev'
sudo -u www-data -E ./vendor/bin/phpunit -c core --testsuite functional
sudo -u www-data -E ./vendor/bin/phpunit -c core --testsuite functional-javascript


That should be the contents of your public file system, which will usually be placed at PATH_TO_DRUPAL_ROOT/sites/default/files


If a pager is missing, then appears when using another theme, does that narrow the problem to the original theme?

I stumbled on tostinni's answer in Pager disappears when adding "GROUP BY" in the SQL query.

  Your query with the GROUP BY is incorrect, MySQL is lax enough to let you write this kind of queries but it is by no way recommended. When you use a GROUP BY clause you should group all the columns without a aggregate function.

I then fixed two queries that have poorly formed GROUP BYs, but my pager was still missing. I bust out Devel's query logging feature; the offending SQL query resulted to be used by the Nodequeue module. I checked the bug reports for that module, and found the one about that query: Grouping error" when creating a simple queue (PostgreSQL).


How can menu title be included in breadcrumbs?

You can make use of drupal_get_title

  The title is displayed on the page and in the title bar.

Alter breadcrumb code accordingly.


Print Entity Reference Value from Entity Meta Wrapper

You can access entity reference values by calling entity metadata wrapper API on the reference field.

For instance, if you have a node with a field which references a profile2 entity,

$wrapper = entity_metadata_wrapper('node', node_load(1));
$profile_wrapper = entity_metadata_wrapper('profile2', $wrapper->field_profile->value());
print $profile_wrapper->field_about->value();

or if you prefer rendering the entity,

print render($profile_wrapper->view());


_preprocess_views_view__ specify view name

In Drupal 7 this preprocess function will not automatically get picked up as it did in Drupal 6. There is a workaround posted here if you want the same behaviour as Drupal 6. For the issue.


How can i show only content type fields in block or how can i call a add content type page in a block

here is your module: Form Block. And here is a quote about it from the module's project page):

  Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.


managed_file upload clearing $form_state

I recently encountered the same problem. I found that data is erased in function - drupal_validate_form(). I have not fully understood why this is happening, therefore, just went bypassed the problem. I have rewritten my code so that the code section that erased the data in drupal_validate_form() is not executed.

My code:

  $managed_file_processing_fn = array_merge(
    element_info_property('managed_file', '#process', array()),
    array('ccw_managed_file_process')
  );

  $form['customization']['main']['request_design']['upload_design'] = array(
    '#type' => 'managed_file',
    '#progress_indicator' => 'bar',
    '#upload_location' => 'public://',
    '#upload_validators' => array(
      'file_validate_extensions' => array('jpg jpeg gif png zip rar tar'),
    ),
    '#states' => array(
      'visible' => array(
        ':input[name="type_of_upload"]' => array(
          array('value' => strval(CCW_GET_HELP)),
        ),
      ),
    ),
    '#process' => $managed_file_processing_fn,
    '#default_value' => $upload_design,
  );

/**
 * Process managed_file.
 */
function ccw_managed_file_process($element, &$form_state, $form) {
  // When AJAX is execute we ignore form validation.
  $element['upload_button']['#limit_validation_errors'] = FALSE;
  $element['remove_button']['#limit_validation_errors'] = FALSE;

  return $element;
}

Topic with the same problem on drupal.org:
https://www.drupal.org/node/2311199

Also, I noticed that in Drupal 8 the behavior is the same.


How do I use only a taxonomy term in the path alias?

I gave this a try and the following pattern seems to be working:

[node:field_tags:0:entity]/[node:title]


Try the Entity translation actions module.
https://www.drupal.org/project/entity_translation_actions


You can use the addClass() method of the attribute class:

{%
  set classes = [
    'my-class-1',
    'my-class-2',
  ]
%}

<input{{ attributes.addClass(classes) }}>

You can either pass an array like the example above or pass a single class in the method directly: attributes.addClass('my-class').

For reference see the Drupal docs: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates


Entity alteration to prevent entity from being indexed by search_api

When he says "better done with data alterations" he is referring to the "Data Alterations" fieldset / section in the "Workflow" tab for each index in the UI and that is accessible in code through hook_search_api_alter_callback_info().

You can see a patch that uses this (it doesn't use the hook but the original function because it is being added to the actual search_api module but you get the idea) to not index unpublished nodes: http://drupal.org/node/1507882

I think his audience for this comment is other contributed module makers. You can imagine it would be extremely confusing for a user if certain items didn't get indexed because a module they turned on used that hook.

If you are trying to exclude nodes from being indexed (be aware that you can use the "Node Access" data alteration which will keep unpublished nodes from being returned for searches for users who don't have content editing access) you can use that hook checking for the node ids and unsetting them as in the example function.


Drush: difference between pm-update pm-updatecode

pm-update also runs the update.php script to take care of any database schema changes that a module may need (same as drush updatedb), pm-updatecode doesn't.  Under many/most circumstances, you can just run pm-update.


Contextual filter on entity reference field in indexed view

If you want to show the jobs for that particular office on your job page, you might want to use a parameter. you need to pass the nid of that office to the url.

Create a link similar to this:

  $nid = arg(1);
<?php
    $l = l( t('More Jobs'), 'list-of-jobs',   array('query' => array('field_office' => $nid)  ));
    echo $l;
        ?>

your entity reference field is "office" right? use that field for your contextual filter. then use Views Contextual Filter Query module to get the parameter from the URL. In my example, it's field_office.

Hope this helps!


One way to go about this is block preprocess function to retrieve the block's current node context & insert the relevant variables to be used by your Twig template. For example:

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function MYTHEME_preprocess_block(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  if (!is_null($node)) {
    $uid = $node->getOwnerId();
    $user = \Drupal\user\Entity\User::load($uid);
    if (!is_null($user)) {
      $username = $user->getDisplayName();
      $variables['$username'] = $username;
      // {{ username }} will be available within block.html.twig.
    }
  }
}


Commerce customer only defines a commerce_customer_profile entity type (not commerce_customer), so changing the second line to this should fix it:

$billingWrapper = entity_metadata_wrapper('commerce_customer_profile', $billing_profile);


Can't override module css for Mega Menu in Zen theme

For something like this, I would suggest you first to unset the css file in the module with hook_css_alter. After that, you can use the css you added in the theme, you don't need two css files with the same info loaded.


Apache Sorl Add Custom Term Indexing with Hierarchy

You don't need custom code to achieve this, quoting from here:

  There's a wonderful little checkbox in the Search API workflow tab
  which enables it.

  Head to:

  admin/config/search/search_api/index/your solr server/workflow

  (You'll need to have created a server to get to this.)

  And then tick the box "Index Hierarchy".

  In callback options select the taxonomy field where you would like
  searching for the parent to include the child.


how to show ubercart fields in manage fields section of content type

It sounds like you might need to create a relationship between the content node and the product node. In the content node, you will only see a reference field pointing to the product node, which usually holds all the constructs you are looking for.


How to use EntityFieldQuery etc. to return a particular field efficiently?

The safest way to get a field value in Drupal is to load the whole entity using the API - Drupal is a modular system and this allows other modules to interact with the data. There are ways (see Clive's answer) to load the field with the API without having to load the full entity - but this is still much less efficient than a raw SQL query.

The question however is how often you need to run this inefficient code. Presumably you only need to run this code when entities have been modified - so while caching entities is not an option, you could well cache your map and only rebuild it when an entity has been modified (ie. on cache clear).

If your entities are modified very often, then rather then rebuild your map every time, you could use hook_entity_update and then edit that entitie's entry in your map - so continuously modify your map.

This approach may or may not be faster than using an SQL query every time you need your map - it depends on how often entities change and how often you generate the map.

That being said, it is extremely unlikely that Drupal 7's core database schema is going to change at this stage - you'd be quite safe using direct SQL queries (in particular if this is your own code as opposed to a module you want to release).


In what cases should I personally sanitize input & output when using the Database Abstraction Layer

If you use db_query() all the time without directly inserting variables, but using the arguments.

For example this is right: db_query("SELECT * FROM {node} WHERE nid = :nid", array(':nid' => $nid)); it's perfect, you don't have to care about something else (except critical bug directly in Drupal).

On the other hand, if you do it directly: db_query("SELECT * FROM {node} WHERE nid = $nid"); you expose your site to SQL Injection.

From my own experience, Drupal alone (without other modules) is very secure and many times we tried to hack it with professionals.


It sounds like your relying on CAS to provide an access check to the URL path. Webform supports limiting access to a webform by drupal Role.

If your user has authenticated via CAS and is logged into the site simply limit the webform access to users with Authenticated Users or any non-Anonymous user role.


How to select a random user from a list of users that have flagged a content?

Well I finally did it. The modules used were:

Rules
Flags
Views
Views rules (This one was the key, allows to execute a view inside a rule, even as loops.)

Two thins were done, first, a component which would be executed every hour, and second, inside that component, every hour, a winner would be chosen for every content that had a contest date matching the hour.

Creating scheduled component

Create a rule set component, which receives a parameter of type date.

Add a rule action schedule component evaluation, in this component created, and set as the value, the component you are editing, this will program this component to be executed one hour after it is executed.
Save everything, and go to Settings > Rules > Components and press "execute", with the value "now".
Component now is being executed every hour.

Selecting random winner

Install all the modules listed above.
Create a simple component that receives a user, and a node as parameters, then add the conditions you need, and finally add an action which sets the winner field inside the node as the user given.
Create a view and add a "Rule" display, this will be like the first query.
Lets call it "Select content programmed for now", and filter it by a given date, then add the fields that will display, "nid" is the most important.
Change the section "edit field info", inside "Rules settings", setting the type of the output, choose "Node" type for the nid (this gives the reference to the node instead of a number).
Create another view, called "choose random winner", make it receive a "nid" and return the list of flagged user "uid", sort it with a global random criteria, and set max results with 1.
Repeat 4 for this view, but with "User" type.
Go to the component which executes every hour, add a view loop action in your rule.
Select the view that filters the content for the current date.
Add a view loop inside that loop, with the new rule.
Add an action containing the component created at the beginning with the parameters you now have available.


Drupal 7 out of the box will recognize these if you add them to any menu. It will automatically hide/reveal them based on their context.

Create two menu items, one pointing to user/login and one to user/logout


Render a Views table row ID using a field as the ID value

Try this to add an id attribute with your SKU based on the $view->result output:

 <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?> id="<?php print $view->result[0]->commerce_product_sku; ?>">


How to add my own images to the views slide show?

First you need create a content type for your slider (admin/structure/types/add), let alias it slider, then add your desire fields to it ( maybe a image field and title as a slider slogan ), then create a image style for your slider in admin/config/media/image-styles/add ( create a image style according to your slider image in your design), then   in views  change filter to show only images form slider content type.

For more details do  "How to Build Drupal 8 Slideshows" step by step.


Where is the $email_text variable set on ubercart?

It's set in template_preprocess_uc_order(&variables) in the order module ($variables['email_text']).

If you're looking to override this variable for your site it can be overridden by defining a function MYTHEME_preprocess_uc_order(&variables) in your theme's template.php


How do I nest two field in my node.tpl.php?

Here is the code to solve problem

  $image = field_get_items('node', $node, 'field_text_multiple');
  $text = field_get_items('node', $node, 'field_multiple_second');
  foreach ($text as $key => $value) {
    $second_field[] = field_view_value('node', $node, 'field_multiple_second', $text[$key]);
  }
  foreach ($image as $key => $value) {
    $output = field_view_value('node', $node, 'field_text_multiple', $image[$key]);
    print render($output);
    print "
";
    print render($second_field[$key]);
    print "
";
  }


I just got it working by changing the page's it was viewable on. Not really sure why that fixed the issue, but it did.


The error message you quote has nothing to do with Display Suite.  It is caused by a bug in the Link module (as should be obvious from the error message you quote).

Here is a link to the relevant issue ticket.  If you read through the long list of messages, you'll see that the fix for this bug was commited to the dev branch of the Link module on May 23 2013. It is not in the "recommended" release.  The "recommended" release of the Link module is from February 9 2013, so it is quite old.

Try to install the dev branch of the Link module, and see if things improve.


I managed to use:

$html = drupal_render($form);

Just like you would do in Drupal 7. Not great, but solves my problem.


Drupal doesn't have hooks that are invoked when a session ends, probably also because the code would not be able to understand if the session cookie is not present because it expired (which means the session ended) or because the browser has not been used to log in on a Drupal site.

Drupal invokes a hook when the user is logged out, either because the user clicked on the Log out link, or because the user was forced to log out, which is what happens when the site is in maintenance mode and the account isn't exempted from being automatically logged-out.
Drupal 7 and Drupal 8 invoke hook_user_logout() when the user is logged-out, and the code invoking the hook also destroys the user session.

Since you are talking of cache to clear, if you are using Drupal 8, you can also investigate if there are cache tags or contexts that tell Drupal to invalidate the data when the session is destroyed.
Cache contexts lists session.exists as context that can be associated to cache data. I didn't test it, but from the context name, I take it invalidates the cache data when the session doesn't exist, which is what you are trying to achieve. (See also Cache API for more information on cache tags and cache contexts in Drupal 8.)

As side note, a Drupal session doesn't normally end when users close their browser. It would happen when using an incognito window with Google Chrome, or the equivalent of other browsers, but when you are not using that, the session doesn't end when the browser is closed, or when the browser tab is closed. (If that were to happen, it would mean logging off the users.)


How do I migrate an image field with migrate 2 module on drupal 6

Okay so I figured out what was wrong. I needed to put the site url in front of the path in my db.

  public function prepareRow($current_row) {

    $source_id = $current_row->page_id;

    // This adds the images to the image_gallery field
    $result = db_select('migrate_ror_pages_images', 'pic')
      ->fields('pic', array('filename_path', 'title'))
      ->condition('page_id', $source_id)
      ->execute();
    $current_row->images = array();
    foreach ($result as $row) {
      $image_data = array(
       'path' => $row->$GLOBALS['base_url'] . filename_path,
       'alt' => $row->title,
       'title' => $row->title,
       'description' => $row->title,
      );
      $current_row->images[] = drupal_to_js($image_data);
     }

The line that needed to be changed was the one regarding the path to the image. I was using a relative path /sites/default/.../filname.jpg and I needed to use a full path:

           'path' => $row->$GLOBALS['base_url'] . filename_path,

So if you are trying to import images/files you will need a full path to the image not a relitave one!

Hopes this helps someone.

//Craig


Using Drupal's session inside a PHP script

In instances where I've had to do things like this I've done the following. It's worked for D6/D7 without any warnings for me.

  $current_path = getcwd(); //Current app path

  //Remove any HTTP headers/output
  header_remove();
  ob_clean();

  //Bootstrap Drupal w/ dir change
  //$drupal_root being the root Drupal install path
  define('DRUPAL_ROOT', $drupal_root);
  chdir($drupal_root);
  require_once "$drupal_root/includes/bootstrap.inc";

  /*Execute Code Dependant on Drupal Environment */

  chdir($current_path); //Return to existing app path


Hiding regions for a node page without creating a unique twig file for that node?

4k4 suggestion to use the preprocess_page Drupal-function can be done like this:

Preprocess functions go in your themes themeName.theme file, you may need to create this file if your theme does not have one - be sure to clear the Drupal cache after adding or changing code in this file.

function theme-name_preprocess_page(&$variables) {
  // Set the node ID if we're on a node page.
  $nid = isset($variables['node']) ? $variables['node']->id() : '';

  // Unset a region for one node ID.
  if ($nid == '7') {
    unset($variables['page']['sidebar_second']);
  }

  // Unset a region for multiple node ID's.
  if (in_array($nid, ['1','2','3'])) {
    unset($variables['page']['sidebar_first']);
  }
}

If you would rather use CSS (not a bad technique at all), you can add path classes to body also from theme-name.theme, but this time via the preprocess_html function:

use Drupal\Component\Utility\Html;

function theme-name_preprocess_html(&$variables) {
  // Add path classes to body.
  $path = \Drupal::request()->getPathInfo();
  $path_args = explode('/', $path);
  if (count($path_args) >= 3) {
    $variables['attributes']['class'][] = 'path-' . Html::cleanCssIdentifier(ltrim($path, '/'));
  }
}


programmatically change link URL in view

I don't recommend to use views php module,

Menu item with callback:

The idea here is to override all the links of the titles in your view with one link which pass an argument to custom menu callback, then in the callback, you write your PHP code which does the routing.

to implement this solution you need to do the following:

1- Override the link in the view

2- Create callback using hook_menu():

/**
 * Implements hook_menu().
 */
function mymodule_menu() {

  $items['my-routing/%node'] = array(
    'title' => 'Custom callback',
    'page callback' => 'my_custom_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

3- Create your custom callback to do the routing:

function my_custom_callback($node) {
  switch ($node->type) {
    case 'product' :
      drupal_goto('project/' . $node->nid);
      break;
    case 'post' :
      drupal_goto('blog/' . $node->nid);
      break;
  }
}


Show either a node or a blocks page at frontpage

I agree, the block layout gets quite messy when you try to do this. Another option would be a separate twig template for the front page.

Create two new regions frontpage_auth and frontpage_anon and fill them with the blocks you want to show. Don't configure the visibility here. Just place the blocks.

Modify page.html.twig, so that {{ page.content }} is enclosed in a twig block maincontent:

{% block maincontent %}
  {{ page.content }}
{% endblock %}

Then create a new twig file for the front page

page--front.html.twig

{% extends "page.html.twig" %}

{% block maincontent %}

  {% if logged_in %}
    {{ page.frontpage_auth }}
  {% else %}
    {{ page.frontpage_anon }}
  {% endif %}

{% endblock %}

where you display one of the two regions dependent on the variable logged_in.

For the node you can use the Main page content block or you can put the node in a view and use this view as a block.


Change node content after logging in under the same URL alias (showing other content for authenticated users)

You can do this with views using the technique in this blog post: Making a view show different content to different users based on role


Features - Custom User Fields Not Available after Import

Solution

You have to add the corresponding field instances in feature as well. The field instance name should be in this format:

[entity_type]-[bundle]-[field_name]

In your case, they should be:

user-user-field_first_name
user-user-field_last_name
user-user-field_title
user-user-field_email

Sub Question 1

  Despite this, when going to Configuration > People > Account settings, going to "Add existing field" does not list the newly imported fields to that list. They also are not available as "Existing Fields" when modifying a Content Type.

Answer

You cannot find existing fields because there is no field instance attached on the field base. Drupal won't be able to load those field base without field instance.

Sub Question 2

  On top of that, when attempting to create a field with the same machine name, it states that it is already taken.

Answer

The field base is stored in database and also the table is created. So Drupal will stop you from recreation.


How to use the same URL alias for all translations of a node?

As pointed out by @Rockabelly, this is a bug with Drupal core.  For now, there is a patch to fix the issue.


How to create a hit counter for each published node to find out how often a specific node has been viewed?

There is a settings page at admin/reports/settings, try looking there first.

Also, look in the node_counter table instead of accesslog.  The query should actually be as follows ($nid being the node ID of the node which you want records for).:

SELECT totalcount FROM {node_counter} WHERE nid = $nid;

On another note, I'm pretty sure if you enable the Statistics module, you can simply pull the node's page view count out in Views.


Inline entity form module fails when creating a new node and the reference method is Views

See patch located
Drupal core patch
#42 works with Drupal 8.9.2 give that a try, it should fix your problem.


If after running the permission checks drupal doesn't find enough items to fill your view it will not show the pager (for any user role). You should check why there aren't enough items for the view.
Did you check for the number of items on a page (in the view). Is the pager set to be on (in the view). There are chances that you forgot to check some of these settings. It happens.


If you are willing to give it a try to "replace node_access AND drupal filters with one solution" (as per one of your comments), then have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site).
What are the features of the Group module versus Organic Group module?

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Add CCK field to panel / page (from page manager)

In short, no. Pages are not entities (or nodes in D6) and so cannot have fields, CCK or D7 core, on them.

It's possible that FAPE does what you want, since it allows you to stick an Entity directly into a Page, but that's D7 only.


Add custom CSS code for a textbox in form

I do it like this:

function the_form($form, &$form_state){
     $form['price'] = array(
       '#type' => 'textfield',
       '#title' => 'What is Your Price?',
       '#size' => 100,
       '#maxlength' => 10,
       '#required' => TRUE,
       '#prefix' => '
',
       '#suffix' => '
',
     );


A better understanding of contextual filters led me to a solution.  I used a contextual filter to limit which pages showed the menu, then used a filter to control the items.


You can easily output taxonomy term based information by going to admin/structure/views/add and under "Show" choose "Taxonomy terms".


See if this will help: How can I implement AJAX form submission?

It's a pretty decent checklist for ajax form operations.


Implement sticky footer for acquia_marina

The CSS solution should be implemented the same way in Drupal 7.

Here is the javascript code updated to Drupal 7.

(function ($) {
Drupal.behaviors.acquia_marinaStickyFooter = {
  attach: function (context, settings) {
    var footer_height = $('#footer').height();
    var footer_pos = $('#footer').position();
    var window_height = $(window).height();
    var page_height = $('#page').height();
    var page_pos = $('#page').position();
    var page_total = page_pos.top + page_height;
    var footer_new_pos = window_height - footer_height - page_total;
    var test = footer_height + page_total;
    if (test <= window_height) {
      if (footer_pos.top < window_height) {
        $('#footer').css('position', 'relative');
        $('#footer').css('margin-top', footer_new_pos);
      }
    }
  }
};
})(jQuery);


Is Drupal appropriate for what I want to do?

f you don't have any plans to expand the site in near future, then Drupal is an overkill.
The whole system is just too big for your purpose, and offers lots of functionality your friend won't ever need: permission system, roles, user profiles, content types, fields, forum, and comments. Especially as you don't have any CMS experience, Drupal will take the most time to setup, and you will need to learn a lot during the process.

I suggested WordPress because it is generally used for such websites by designers, takes less time to setup, and there are much more available themes and non-developer user tutorials. IMO, this would be the fastest option to setup.

Lastly, a custom CMS might be the best fit for this. If you don't have any ideas what to use, take a look at these frameworks: Codeigniter, Laravel or Yii.

Or, if you want to make it fun for you, use some micro framework: Flight (PHP 5.3+), or Slim (PHP 5.2/5.3). Pair it up with some tools/libraries for ORM/AR like Paris and Idiorm, RedBean, and/or an "unframework". If you want to get really fancy, add an MV* JS library like Backbone.


The answer was - the node fields are not available and you have to reload the node, like so:

$nodef = node_load($data->nid);
$el = $nodef->field_electronics_description[und][0][value];

if ($row->view != NULL ||  $el != NULL) {
   return FALSE;
}
else return TRUE;


WSOD "The provided host name is not valid for this server"

You need to add your domains into the array as per your first example. I.e.

    $settings['trusted_host_patterns'] = array(
  '^www\.yourdomain\.co\.uk$',
  '^yourdomain\.co\.uk$',
);

Then clear the caches and the message should go away. It may be that you're missing the comma after your second entry.


How to create a single page application in Drupal?

You could use the Ajax Regions module.

It allows you to load specific regions via Ajax, thus load your whole website on one single page


Get Order Object on Checkout Complete Page

The hook hook_uc_checkout_complete() is the function you're looking for. However, you're going to have problems here since the function runs after the page display.

One way to get around this is override the theme function on the complete sale page:

function THEME_uc_cart_complete_sale($variables) {
  $order_json = json_encode($variables['order']);
  drupal_add_js('jQuery(document).ready(function () { var order = '.$order_json.'; console.log(order); });','inline');

  return $variables['message'];
}

This will execute JS code with the order object upon sale completion.


How to use #element_validate and #value_callback in Drupal 8

To use an instance method for #element_validate/#value_callback etc you need a callable. e.g.

$form['upload'] = array(
  '#title' => t('Upload Images'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://image_example_images/',
  '#element_validate' => array(
    array($this, 'file_generic_settings_max_filesize'),
  ),
);

You'll need to mark file_generic_settings_max_filesize() (which if you were being a stickler for standards should really be named fileGenericSettingsMaxFilesize) as public to accommodate, as your class won't be invoking the method.

Documentation for this is ongoing, the change notice is here.


Correct permission for site, default and files folders?

Actually the permissions should be

sites -> 755
sites/default -> 755
sites/default/files -> 775
sites/default/settings.php -> 444

See the top 3 answers to this question for some great details.


Use https://www.drupal.org/project/metatag module to modify page titles (among other things) per content or content type.

To modify what google analytics displays as title is beyond the scope of this forums


Warning: Illegal offset type in drupal_add_js() (line 4184 of C:\EasyPHP-5.3.8.1\www\lfp\includes\common.inc)

I realized the issue - In the info file I was writing scripts[all][] = filename, the same way you do it with css files. The correct syntax is scripts[] = filename.


Is there any way to access the user tables on drupal?

The users are saved in the database table 'users'.


Import legacy site URLs via url_alias table

For storing aliases use Drupal\Core\Path\AliasStorage:

\Drupal::service('path.alias_storage')->save($source, $alias, $langcode);

But it should be no problem, if you inserted the rows by hand. Check, if all source paths and aliases have a leading '/'. And that langcode is set to a language like 'en' or 'und' for undefined.

Then clear the cache. It is enough to invalidate the cache tag 'route_match':

drush ev '\Drupal\Core\Cache\Cache::invalidateTags(['route_match'])'


Perhaps the lack of activity is an indicator of the obscurity of my problem, but Storify is a very popular tool so I imagine someone else might also have this issue. Here is how I solved it, thanks to a couple of colleagues helping me think creatively about this. Unfortunately my solution only works for one tool, but it could be made to work for any service with a consistent embed code.

Make a new field called Storify slug that contains the URL of the storify after storify.com/.
Add the embed code to the field's template. Below is field--field-storify-slug.tpl.php

<?php foreach ($items as $delta => $item): ?>
  <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>

    <iframe allowtransparency="true" frameborder="no" height="750" src="//storify.com/<?php print render($item); ?>/embed?header=false&amp;border=false" width="100%">

    [<a href="//storify.com/<?php print render($item); ?>" target="_blank">View on Storify]

<?php endforeach; ?>

I added the storify-story ID to deal with some bad behavior where the Storify script was rewriting the DIV it was in and adding clear: left; as in inline style.


How to show only current user registration list in Node registration view?

Add Configure contextual filter.

Select the Name field.

Checked "Provide default value".

Type select box select: User ID from logged in user.

Refer


This is a couple months late, but I encountered the same issue and wanted to answer this in case someone runs into the same problem.

Basically, Features will not show menu links unless the link path is identical.  So, the paths on the site you're importing to have to be identical to the ones from you're exporting from.  If they are different, nothing shows.

If you open up the links.inc file you'll see:

 $menu_links['menu-primary:node/1'] = array(
   'menu_name' => 'menu-primary',
   'link_path' => 'node/1',

You can manually modify the link path to make things show up, but obviously this isn't ideal.  Hopefully this gets addressed down the road...really a killer in my opinion.


How to display custom token in custom block

Place the formatted text in a render element processed_text:

 $content = [
    '#type' => 'processed_text',
    '#text' => $config['my_field']['value'],
    '#format' => 'content_manager',
  ];

  return [
    '#theme' => 'simulator_block',
    '#content' => $content,
  ];

Configure the text format to include the token filter.


Modify parent entity from within custom field formatter

You can do this from inside the field formatter.  Each of the $items passed into the viewElements method has a getEntity() method that will give you the entity.

class MyFieldFormatter extends FormatterBase {

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $entity = $items[0]->getEntity();
  }

}

However, this is not recommended since it inverts the normal control flow. In normal situations, everything needed to render a field is a value on a column in the field itself.  Grabbing the entity is icky, but is definitely possible for strange edge cases.


Does aggregating JS/CSS interfere with my drupal_add_js()?

Yes, drupal will definitely miss your custom JS scripts in it's js aggregation build phase, if you're loading JS on different pages. This is because by the time a user (or you) hits the other pages, the aggregated js file has already run previously, and created the cached JS file it thinks is all it needs. It uses this cache file until the cache is cleared or the crontab is run.

A couple of options are to either:

try using the drupal_add_html_head() function to add the js when ever you want, or,
write some js to detect what library is needed (perhaps based on a data attribute element in the markup), and then conditionally load the other js via the getScript method.

Good luck.


Turns out this can only be done programatically in a module.  Here is an example in case its useful for someone else:

function HOOK_views_query_alter(&$view, &$query) {
    /***** Owner ****/
  if ($view->name == "policy_listing" && $view->current_display == "policy_by_owner") {
    //alter the query so role reference fields are sorted by the role name rather than role id (rid)
    //replace the rid with the actual owner name
    $query->fields['field_data_field_policy_owners_field_policy_owners_rid']['field'] = "name";
    $query->fields['field_data_field_policy_owners_field_policy_owners_rid']['table'] = "role";
    $query->fields['field_data_field_policy_owners_field_policy_owners_rid']['num'] = 2;

    //add the join to the role table
    $join = new views_join();
    $join->table = "role";
    $join->left_table = "field_data_field_policy_owners";
    $join->left_field = "field_policy_owners_rid";
    $join->field = "rid";
    $join->type = "LEFT";
    $join->extra = array();

    $query->table_queue['role'] = array (
      'alias' => "role",
      'table' => "role",
      'relationship' => "field_data_field_policy_owners",
      'join' => $join,
    );
  }
}

In this case I am replacing rid with the actual name of the role in the view so the sorting works.  Obviously, replace HOOK with your module name.


How can i hide "Save and Publish" button to editor role only?

You can use two ways.

Simple ways. Enable module Content Moderation in core and set permission by roles.
Use function hook_form_node_form_alter()

global $user;

if (in_array('editor',$user->roles)){
   $node->status = FALSE;
}

Drupal 8 have some different. Global user replace by
\Drupal::currentUser()

and $user->roles replace by

\Drupal::currentUser()->getRoles()


The proper way to assign a theme function to a form using hook_form_alter() is like this:

function footer_menu_form_footer_menu_node_form_alter(&$form,&$form_state,$form_id){
  $form['#theme'] = 'pz_footer_menu_node_form';
}

I can't tell if you're using Drupal 6 or 7; you're using the arguments property in your theme declaration which is only valid in Drupal 6, and also the render element property which is only valid in Drupal 7.

Judging by the out of memory error I'm guessing Drupal 7. As you call drupal_render() on the the $form object in your template file, it runs that variable back through the same theme function, and you end up with an infinite loop.

Try changing the last line in your template file to this:

<?php print drupal_render_children($form); ?>

That should stop the error from happening.


hook_form_alter() to put multiple radios in a table

I think you can define a wrapper element as type table. The core user permissions form does this, and I think is similar to what you're trying to build:

 $form['permissions'] = [
  '#type' => 'table',
  '#header' => [
    $this->t('Permission'),
  ],
  '#id' => 'permissions',
  '#attributes' => [
    'class' => [
      'permissions',
      'js-permissions',
    ],
  ],
  '#sticky' => TRUE,
];
foreach ($role_names as $name) {
  $form['permissions']['#header'][] = [
    'data' => $name,
    'class' => [
      'checkbox',
    ],
  ];

In your case, I think you'd define something like $form['sow'] as a '#type' => 'table' which will be a wrapper element that all the checkbox (or radios) appear under.

Then loop through your fields (these will be similar to how the user permission form loops through each permission, creating a row).

foreach ($fields as $low) {
  $form['sow'][$low]['description'] = [
    '#type' => 'item',
    '#title' => $low['title'],
    '#description' => ...,
  ];

  // Now loop through each assignment. This will be similar
  // to how the user permission form loops through each role
  // for each permission.
  foreach ($assignments as $assignment) {
    $form['sow'][$low][$assignment] = [
      '#type' => 'checkbox', // Or 'radio', depending on the need.
      // Other form element details here too.
    ];
  }

Then, for each assignment (these will behave similar to each role in the user permission form)


Created a development/test server from an existing site, struggling with permissions errors on Cent OS 6 server

The best to fix the permission issue is run the fix-permission script available at https://drupal.org/node/244924

First download the script from here and than run the script as:

sudo bash fix-permissions.sh your/drupal/path your_user_name

Note: The server group name is assumed "www-data", if it differs modify it in the script code

Drupal official doc for file permission is available at https://drupal.org/node/244924

Generally Recommended Permissions for Drupal Files and Folders is following:

drupal/sites/default                                        750
drupal/sites/default/files (including sub folders & files)  755 or 770 *
drupal/sites/default/settings.php                           400 or 440 *
drupal/sites/default/default.settings.php                   400 or 440 *
drupal/sites/all/themes (including sub folders & files)     755
drupal/sites/all/modules (including sub folders & files)    755

* depends on system setup. Some extra modules and/or server rules may require different permissions.


You can create multiple path aliases for a single node, but you can not re-use existing path alias to point to different node.

If Child 1 and Child 2 in your example point to the same nodes, then I I am not sure if I understood your problem correctly, because you can create multiple menus to point to the same nodes. Let's say you created both child nodes associating them with Main menu checking on the Provide a menu link in node's Menu settings. Then you could just create a new menu on admin/structure/menu and add menu items for the same nodes replicating the same or creating new path aliases.

Another way is to let Pathauto generate whatever path aliases you want for the first menu, then programmatically copy its items and override the second menu items with theme_menu_tree().


Multiple/Bulk Image Upload Tutorial? Plupload etc

Install Multiupload Filefield Widget and, if you're so inclined, Multiupload Imagefield Widget.

Make sure your PHP upload limit will allow all the files to upload.


How to exclude some keywords from a search with Search API?

I believe the "custom_search" module can do that. http://drupal.org/project/custom_search

Although I don't know whether the exact boolean syntax is used, I know the module offers two ways to search in the way you want:

With three different text fields (one for OR, one for AND, and one
for WITHOUT)
With one text field (By using some kind of syntax like
you described)


What approach for showing custom user fields on a node?

Ok, I'm only using drupal 6 but I think these answers can lead you to a solution:

With the core profile module there is a block "Author information"
You can use the Author Pane module but it doesn't have a stable release for D7 yet.
You can use views to build an author block:

If you're using profile from core:

  Create a user view
  Set the argument to User: uid
  Choose "Provides default argument" set to "User ID from URL" and check "Also look for a node and use the node author"
  Add your user profile fields.

If you use Content Profile

  Create a node view
  Set the argument to Node: Nid
  Choose "Provides default argument" set to "Node ID from URL"
  Create a relationships to retrieve the content profile
  Add your content profile fields.


How can I simplify the use of flags with Views Bulk Operations?

Instead of using the "Flag (or unflag) a node" action directly, create new a rules component and show it in your administrative view.

Navigate to Configuration » Workflow » Rules » Components
Click on Add new component , choose Rule from the components plugin drop-down menu.
Choose a name (e.g. Approve), add a parameter with the type node.
Add a condition, choose Node is flagged from the drop-down menu.
Choose the appropriate flag, select the node-parameter for the node, choose site:current-user for the user on whose behalf the flagging-action will be performed, select negate such that the condition will evaluate to true when the node is not flagged.
Add an action, choose Flag a node from the drop-down menu.
Choose the appropriate flag, select the node-parameter for the node, choose site:current-user for the user on whose behalf the flagging-action will be performed.

Edit your administrative view, configure bulk operations such that the Approve operation is shown instead of the Flag (or unflag) a node


How do I verify emails on a contact form?

For validating an email just use client side validation in that case. mdn form validation
This will use the browsers checks for valid email and not send the form to you unless it’s valid.
For verifying an email I would say use Drupal accounts (that already has a superior methode for email verification.)
Btw. you can not check if email is valid at all.
The protocols involved do not allow a check like that.
What you can do is try and send a message and hope it arrives at the other end.
This would be a (as suggested) double take. But whether you are allowed to do so is another matter (it could be considered spam by local law). Safest bet is to either require an account or to to not validate it at all. (Possibly with a block list). And remember, do not make the cure worse that the disease. A mail validation could do that (quite a few sales people found that out)


CSS is not aggregated anymore - how to debug?

I am extremely sorry, but I have found out that the problem was not caused by Drupal.  It seems that the a proxy has been installed by the ISP that automatically compresses pages and rewrites stylesheets to be included into the page directly.

The pages work correctly when being fetched via other networks.


Drupal 7 - How to get AJAX response displayed in a ctools modal?

Checkout Documentation on: http://api.drupal.org/api/drupal/includes!ajax.inc/7
or: http://drupal.org/node/1635198#comment-6120546 on how to render drupal messages.

For more Information about ctools modal you may check: Example to display webforms (webform.module) within CTools modal windows

Or what about a tutorial like: "Ajax modal windows, the easy way"


“Realname” module is not creating “pretty URLs” for new users?

congratulations on inheriting someone else's work, it was really well documented, right? ;-)

All joking aside, the realname module is used to display alternate names instead of the username.

To get the /user/firstname-lastname urls you would use the pathauto module and configure the "pattern" accordingly. Instead of "user/..." you might want to use the "member/..." to keep things a bit separated. I bet pathauto is already used on your site.

Just change the pattern, delete all user paths and re-create them in a batch.

I also suggest you check all the additionally installed modules and read up on what they are supposed to do. No worries, you'll learn quickly, just use this site a lot. And try to improve your "accept rate" a bit to get more answers ;-)


hook_init() is not working in my custom module

Hook implementations are cached in Drupal 7. After implementing a new hook, you need to clear the cache. See What method is used to clear caches in the Drupal? for ways to do that.


How to edit a profile field from the node add form

You're on the right track.  It should be a pretty straight forward thing to implement.

I would add a custom submit handler to the node form for your issue content type.  Grab the submitted values for the geolocation field.  Load the user using user_load(), if the value has changed, the update it and call user_save().


What's the difference between using $this->t('text') and t('text') in a block plugin

To be exact on your question: there's no difference in internal implementation.

But as a best practice, you should be using $this->t instead of the global t wherever possible. If you check the function, t is returning a new TranslateableMarkup object.

If your class says $this->t is not defined, you can add the StringTranslationTrait to add the behavior or inject it as a dependency.

  Using this trait will add t() and formatPlural() methods to the class.
  These must be used for every translatable string, similar to how
  procedural code must use the global functions t() and
  \Drupal::translation()->formatPlural(). This allows string extractor
  tools to find translatable strings.

  If the class is capable of injecting services from the container, it
  should inject the 'string_translation' service and assign it to
  $this->stringTranslation.

So as a best practice rule, you generally do not want to mix procedural within OOP unless completely unavoidable (e.g. native PHP functions).


Menu link that is author nodeid specific

You should use tokens in your menu-item for it to change dynamically. Install Menu Token module. From the module page-

  Menu Token allows to use both global tokens and entity ones: node, user, term, etc.

Then allow your menu path to use tokens and set something along node/[node-id]/edit as your path.


z-index Drupal 7 Skeleton Boilerplate discriminating roles?

I was too quick to post the question and I apologize, since the answer is all over the internet, and for those going through the same issue:

YOU MUST add position relative or absolute to all items involved in the z-indexing. Ot the z-index won't work.

Also why was Firefox not rendering things right? I had added a skeleton class to the search box template, but had not added a clear right after.

As to why it was rendering things right when i was logged in as an admin, but not when I was anonymous, remains a mystery.

Hope this is useful for those having identical issues.


8 How to set a value for select list, While using $entity->set('field_name_type_select_list', ["Se_the_optional_value"]); Programmatically?

You can use hook_ENTITY_TYPE_presave as in hook_ENTITY_TYPE_update

When saving existing entities, the entity is assumed to be complete, partial updates of entities are not supported.

use Drupal\node\NodeInterface;

function mymodule_node_presave(NodeInterface $node) {

  switch ($node->getType()) {
    case "article":

      $node->set('field_set_color', ["red","green"]);

      break;

  }

}


Is the creator of a flag stored in the database?

Yes, it's stored in the flag_content table, in the uid column which is defined as

  The user ID by whom this content was flagged.


The zen subtheme accomplishes this by adding this to its theme_preprocess_node function:

function foo_preprocess_node(&$variables, $hook) {
  ...
    // Optionally, run node-type-specific preprocess functions, like
  // foo_preprocess_node_page() or foo_preprocess_node_story().
  $function = __FUNCTION__ . '_' . $variables['node']->type;
  if (function_exists($function)) {
    $function($variables, $hook);
  }
  ...
}

If you have a content type called 'news', then you would be able to create a function called foo_preprocess_node_news in your template.php file.


Background Images Paths are Changed when CSS Aggregation is On

Thank you @jessehs from Drupal.org.

His solution, which worked for me, is the following:

  Long story short, the problem was that Adaptive Theme appears to be
  doing a "pre-caching caching" of the compiled CSS files in the
  sites/default/files/adaptivetheme/ directory.

  The way to get the aggregated files to actually build is to clear all
  caches and immediately save the theme's settings form at
  /admin/appearance/settings/[themename], then do another cache clear,
  just for good measure.

Also included at the source is a helper module that will flush these files when you flush the cache.

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


Get a views result using PHP code, and iterate the proper way

It's not very different from what you do, but here's example code from a project of mine, showing how I usually do it

$view = views_get_view('a_view');
$view->preview('panel_pane_1', array($node->nid));
foreach ($view->result as $tid) {
  print $tid->taxonomy_term_data_taxonomy_term_hierarchy_tid;
}

Based on the function documentation

  To be called externally, probably by an AJAX handler of some flavor. Can also be called when views are embedded, as this guarantees normalized output.

I've always assumed that preview() is the proper way to do it, and it has served me well on a number of occasions.


Your options are:

Feeds module - You can check the doc here.
Export the content from source into csv or json. On the target (D8) either you can use Migrate module to handle the migration but requires custom coding.
Create a json endpoint that will expose the content and in your target (D8) server consume that endpoint. You can then get the content by using Guzzle.

Example...

$request = Drupal::httpClient()->get($url);

See this page for more info.

P.S: I have no experience building with D8 yet but my suggestions above I guess is still applicable.


How to embed a quicktab instance in a page?

After creating the quicktabs, you can render the quicktab programatically from the template file of that page.

Please put the below code inside your template file:

  $quicktabs = quicktabs_build_quicktabs('myquicktab');
  print render($quicktabs);


Thanks @4k4. Your comment started me poking around in ajax_view.js which ultimately led me to the cause. My issue was that my display ids had multiple underscores in a row, e.g. listing__large. If I update the display id to large_listing everything works fine. I guess multiple underscores in a row aren't supported in the display ids, and I'm guessing also with view ids.


What is the equivalent of drupal_set_content()?

The equivalent of drupal_set_content() is drupal_add_region_content().

  Adds content to a specified region.

  Parameters

  $region: Page region the content is added to.

  $data: Content to be added.

Notice there was a bug in Drupal that didn't allow this function to work, since drupal_region_content() was not properly called. (See Content added via drupal_add_region_content() is not added to pages.) It has been fixed on March 2015; if you are using any version earlier than 7.36, drupal_add_region_content() will not work.


How do I get the route name of a view page?

The correct routename for view is view.VIEW_MACHINE_NAME.PAGE_MACHINENAME(in another word "view.$view_id.$display_id" ) . try something like following

use \Drupal\Core\Url;

$url = Url::fromRoute('view.VIEW_MACHINE_NAME.PAGE_MACHINENAME');
$form_state->setRedirectUrl($url);

and for your case

$url = Url::fromRoute('view.team.page_1'); // page_1 is my guess as to your page name, please replace it with your page machine_name

Lean more : How to formulate the route name

after @4k4 comment, Also you can redirect form to custom router with URL

just need use $form_state->setRedirectUrl($url)


Finally I have done this reminder this way.

module_load_include('inc', 'webform', 'includes/webform.submissions');
$submissions = webform_get_submissions(nodeid);

and checked roles while printing node data in loop and get edit link through $base_url; and print into simple tabular format. Let me know if any query in it.

Thanks for the support.


I am unable to get 'file' #type to appear in my form

Does this look wrong to you:

  '#type '        => 'file',

it's not '#type'


CAPTCHA default for Blog post forms does not work in Drupal 7

Following the same post you saw, this time use "comment_node_blog_form" as your form id, or "comment_node_CONTENT_TYPE_form" if your content type is not called blog


Synchronicity! I just answered this question which I think is essentially the same question. I don't have any experience with Profile2, but I think this advice is applicable. Hope this helps:

How to create an entity reference view that contextually filters based upon current user ID


You should enable PHP Filter modules under CORE . Go to /admin/modules and find PHP Filter module and enable

It allows embedded PHP code to be evaluated


this question was cross-posted on drupal.org and it got an answer there.
it basically explains that session submission is meant for this.


Search api, postprocess processor: how re-run the query?

I managed to do something, despite not being optimal: in the postprocessSearchResults when necessary I send a RedirectResponse with new search params thus "reloading" the page and "re-running the search.
  /**
 *
 * @SearchApiProcessor(
 *   id = "my_processor",
 *   label = @Translation("A label"),
 *   description = @Translation("A description"),
 *
 *   stages = {
 *     "postprocess_query" = 0,
 *   }
 * )
 */
class MyProcessor extends ProcessorPluginBase {

  //Skipped constructor and boilerplate code

  /**
   * {@inheritdoc}
   */
  public function postprocessSearchResults(ResultSetInterface $results) {
    if ($results->getResultCount()) {
      return;
    }

    $query = $results->getQuery();

    if ($query->getProcessingLevel() != QueryInterface::PROCESSING_FULL) {
      return;
    }

    $request = $this->requestStack->getMasterRequest();
    $request_query = $request->query;
    $sdm_empty_result_automatic_search = $request_query->has($this->requestQueryTag) ? $request_query->get($this->requestQueryTag) : FALSE;

    /*
     * Necessary to identify between user search and ones run by this class.
     * E.g. if the user is on "article", and does a new search, it must stay
     * on "articles" if there is any result.
     * However if there are no results, the class must redirect to the fist
     * content type and so on until all are searched
     *
     */
    $next_type_value = NULL;
    $condition_type_value = $this->sdmSearchQueryHelper->queryGetConditionValue($query);
    switch ($condition_type_value) {
      case 'prodotto':
        $next_type_value = 'scheda_espositore';
        $sdm_empty_result_automatic_search = TRUE;
        break;
      case 'scheda_espositore':
        $next_type_value = $sdm_empty_result_automatic_search ? 'article' : 'prodotto';
        break;
      case 'article':
        $next_type_value = $sdm_empty_result_automatic_search ? NULL : 'prodotto';
        break;
    }

    if (empty($next_type_value)) {
      return;
    }

    $query_params = [
      'search_api_fulltext' => $query->getOriginalKeys(),
      'sort_by' => 'title',
      'f' => ['content_type:' . $next_type_value],
    ];

    if ($sdm_empty_result_automatic_search) {
      $query_params[$this->requestQueryTag] = $this->requestQueryTag;
    }

    $response = new RedirectResponse(Url::fromRoute('<current>', [], ['query' => $query_params])
      ->toString());
    $response->send();

     /**
     * todo
     * can't use the following logic but had to do all the previous because I have overriden the default url_processor,
     * so there is always a "default" content type if none is selected.
      * So unfortunately I can't run a generic query to search for all the results.
      * For a "standard" search implementation the following one could be a good starting point
     */
    /*
    $original_query = $query->getOriginalQuery();
    $original_query->addTag($this->queryTag);
    $this->sdmSearchQueryHelper->addConditionToQuery($original_query, 'facet:type', ['type' => 'scheda_espositore']);
    $results = $original_query->execute();

    $items = $results->getResultItems();
    $iterator = $results->getIterator();
    */

  }


This is a good article on what trying to do...

http://www.pixelclever.com/how-theme-specific-blocks-drupal


How can I use View modes for entity without bundles?

tl;dr: If your entity annotation contains an admin form, field UI will work.

This is what they would mark on Quora as 'Questions That Contain Assumptions' and those questions usually contain false assumptions. In this case 'bundle of' doesn't even appear in the field UI directory anywhere. Instead, here's how I'd found the answer to your question -- it's not hard at all. First look in core/modules/field_ui/field_ui.routing.yml. Nothing. Well, it's dynamic, if it's dynamic then it's going to be in core/modules/field_ui/lib/Drupal/field_ui/Routing/ and it is. Let's look in RouteSubscriber.php in that directory:

foreach ($this->manager->getDefinitions() as $entity_type_id => $entity_type) {
  $defaults = array();
  if ($entity_type->isFieldable() && $entity_type->hasLinkTemplate('admin-form')) {

Now a quick counter check on the Node annotation and see, under links, there's "admin-form" = "node.type_edit" so that's that.


How to add a condition (rule) to skip questions when using the Quiz module?

To get this to work using the Rules module (which I'd also use for this), you should ALSO use the Conditional Rules module. Some more details about this module (from its project page):

  ... provides Rules plugins for conditionally altering execution flow directly inside a group of actions.

Some examples of using the Conditional Rules module:

"How to check whether one's current User Points are negative with the Rules module?" contains an example of a rule (in Rules export format) with an action that uses Conditional Rules with a typical "if"-part and "else"-part.
a screenprint of a rule with an action that uses Conditional Rules, though only with an "if"-part here, no "else":

So by using both of these modules, you could use a Rules Action to redirect (= jump) to either question 2 or question 7, based on the answer (yes or no) provided to question 1.

This would answer your question for "question 1". By creating up to 10 similar rules (1 for each question that has a similar requirement), you should have a solution for all other questions that would need it also. However, you should be able to take advantage of other facilities that the Conditional Rules module offers (by constructing complex conditions as a condition set and then use those in the condition elements). So that you include all the required logic (for all your 10 questions) in a single Rule.


I think that this module will do the trick: Subscriptions.


hook_modules_enabled called before hook_menu

So, here's the solution. Hopefully it helps save someone else some time. As it turns out, hook_menu() is not invoked during module enabling. As such, I had to force a menu rebuild which invokes hook_menu() and ensures all the proper routes exist prior to building my menu links.

base.module>

/**
* Implements hook_modules_enabled()
*/
function base_modules_enabled($modules) {
  menu_rebuild(); // <--- Added this line to force hook_menu() to be called first
  $links = [];
  foreach ($modules as $module) {
    $module_links = module_invoke($module, 'operations_menu');
    if(is_array($module_links))
      $links = array_merge($links, $module_links);
  }
  foreach ($links as $link) {
    menu_link_save($link);
  }
}


SearchApiQuery - possible to remove a filter?

I found the solution, but be careful: it is very tricky! Ideally, it should be special method in the SearchApiQuery class itself, or method in class-wrapper, which will be used everywhere in code...

My solution based on ability to access private members of classes, passed to __constructor function:

class SearchApiQueryFilterAlter extends SearchApiQuery
{
    public $altered_query;
    function __construct(SearchApiIndex $index, array $options = array())
    {
        if (isset($options['original_query']) AND isset($options['filter_alter'])) {
            $options['original_query']->filter = $options['filter_alter'];
            $this->altered_query = $options['original_query'];
        } else {
            parent::__construct($index, $options);
        }
    }
}

Property $altered_query will contain original query with modified filters.

Usage example:

function product_list_search_api_ranges_minmax_alter($variables, $order)
{
    /** @var SearchApiQuery $query */
    $query = $variables['query'];
    $filters = $query->getFilter();
    $new_filters = $query->createFilter();
    foreach($filters->getFilters() as $filter){
       if(!$filter->hasTag('facet:field_product:commerce_price:amount_decimal')){
            $new_filters->filter($filter);
        }
    }
    $options = array(
        'original_query' => $query,
        'filter_alter' => $new_filters
    );
    $filter_alter = new \Drupal\product_list\SearchApiQueryFilterAlter(new SearchApiIndex(), $options);
    $variables['query'] = $filter_alter->altered_query;
}

In this example all filters has been copied to the $new_filters, except one with special tag. Then, we pass original query and new filters to class constructor through $variables. And empty SearchApiIndex, which is nesesary. Finally, in $filter_alter->altered_query we have the query with deleted filter condition.


Views Slideshow, show alternating content types

In broad strokes, you could use Views' views_pre_render() hook to reorder the result of the View, eg...

function YOURMODULE_views_pre_render(&$view) {

   switch ($view->name) {

      case 'NAME_OF_YOUR_SLIDESHOW_VIEW':

        // to figure out what you have to work with, take out when done debugging
        drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>');

        // and here are the broad strokes... cycle through $view->result and
        // grab all the "rows" and re-order them by whatever business logic
        // you need, in this case even or them by content type instead of whatever
        // logic it is sorted in originally.  it you then set $view->result to this
        // new order, it will then be rendered by the Slideshow in that order

        break;

      // other Views might go here

   }

   // other code might go here, too...

}


Update webform submitted data through the DataBase?

Yes, that should be perfectly safe to do.

Take a backup first just in case, clear the cache after you've done it, and that should be fine.


Create categories with their own teasers and sliders

I would recommend a content type for the slideshow and the article. For the categorization do you use taxonomy and Views for filtering and sorting.
I can recommend https://www.drupal.org/node/394094


You should expand the code in your question a little.

First you need to get the assigned uid with something like:

$assigned_uid = $node->field_assigned_user[LANGUAGE_NONE][0]['target_id'];

Then you need to load the user object:

$assigned_user = user_load($assigned_uid);

Then you have access to the value:

$percentage_split = $user->field_percentage_split[LANGUAGE_NONE][0]['value'];

To help visualize the $node and $user objects and how to access the information, you can put the print_r() function into a php-enabled block in your footer.

EDIT:

I looked at your code, and you should not try to do everything in a single statement. No wonder you are having problems. Break it out step by step like this:

// Get the assigned User ID from the node object

$assigned_uid = $node->field_assigned_user[LANGUAGE_NONE][0]['uid'];
// Load the user object for the assigned User.
$assigned_user = user_load($assigned_uid);
// Get the Percentage Split from the user object for the Assigned User (default to 0).
$percentage_split = (isset($assigned_user->field_percentage_split[LANGUAGE_NONE][0]['value'])) ? $assigned_user->field_percentage_split[LANGUAGE_NONE][0]['value'] : 0;
// Get the remaining values from the node object, defaulting to 0 if not there.
$other_ins = (isset($node->field_other_ins_[LANGUAGE_NONE][0]['value'])) ? $node->field_other_ins_[LANGUAGE_NONE][0]['value'] : 0;
$vb = (isset($node->field_vb[LANGUAGE_NONE][0]['value'])) ? $node->field_vb[LANGUAGE_NONE][0]['value'] : 0;
$finder_s_fee = (isset($node->field_finder_s_fee[LANGUAGE_NONE][0]['value'])) ? $node->field_finder_s_fee[LANGUAGE_NONE][0]['value'] : 0;
$broker_fee = (isset($node->field_broker_fee[LANGUAGE_NONE][0]['value'])) ? $node->field_broker_fee[LANGUAGE_NONE][0]['value'] : 0;
$dlc_franchise_fee_hst = (isset($node->field_dlc_franchise_fee_hst[LANGUAGE_NONE][0]['value'])) ? $node->field_dlc_franchise_fee_hst[LANGUAGE_NONE][0]['value'] : 0;

// Do the math.

$value = ($other_ins + $vb + $finder_s_fee + $broker_fee - $dlc_franchise_fee_hst ) * $percentage_split;

You also seem to be trying to use D6 data structures (won't work in D7), and it will also not work to try to give a function array keys.


How to calculate difference between two dates using Global PHP field?

The function date() is a formatting function, if you want to use date_diff() your code needs to be something like:

$today = new DateTime();
$load = new DateTime($data->field_field_date_loading[0]['raw']['value']);
$diff = date_diff($load, $today);


The theme hook you'll want is menu_link__book_toc_123, where 123is the node ID of your book's outline node.
For the wrapping markup, use menu_tree__book_toc_123.

You can also find the ID by inspecting the navigation list:


How to add profile image into user profile

In Drupal 6 the, goto solution for this is the Content Profile module which allows you to add CCK fields to your user profile (in Drupal 7, the fields API allows you to do this in core):

  This module builds user profiles as content (aka nodes), which opens
  the opportunity to use all the powerful modules for content for user
  profiles too, e.g. the Content Construction Kit (CCK). It's intended
  to be simple and useful, but extensible by further modules.

You will also want to install the imagefield module to be able to add an image upload CCK field.


You want the Default Content for D8 module, which provides drush commands to export and installs the content on module install. From its project page:

Default content gives your module and install profile a way to ship default content as well as configuration. Powered by core's serialization, rest and hal modules.
Features

Supports entity-references between content.
Supports files if you have File entity
Easily export your content and its dependencies to yml using drush commands.


Even with the extraneous jQuery ready function within the behavior, it should still work. I guess it depends on what code resides within the javascript function and if all the jQuery selectors actually exist at that point. I would change two things to make it more "drupal"

Per my earlier comment, remove the jQuery ready function from within the attached behavior function
Attach the form javascript using the Form APIs #attached property. See here for more info.


Adding classes to menu items to signify what level they are

You can use theme_menu_link() in Drupal 7.

function MYTHEME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  $element['#attributes']['class'][] = 'depth-' . $element['#original_link']['depth'];

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

Here I added:

$element['#attributes']['class'][] = 'depth-' . $element['#original_link']['depth'];

Which will provide a class on the list item with the menu depth.


You just need to execute the command with the "destination" parameter:

$ drush cex sync

as CONFIG_SYNC_DIRECTORY is the same as $config_directories['sync']


How can I see the query that's being run?

The views_plugin_query_default class has a query() method that will take the parameters currently held in the object and provide you with a standard SelectQuery (un-executed of course).

Since the SelectQuery class implements the magic __toString() method you can then cast it directly to a string, which will be the SQL query itself:

$select_query = $query->query();
$query_string = (string)$select_query;
dpm($query_string);