How to programmatically change a Views page's html  separately to its on-page title?

I think what you're looking for is hook_preprocess_HOOK where HOOK is either html, page or both.


How to delete all parent references of a taxonomy term?

Answering to myself. Taxonomy hierarchy is known to be detached from terms. For example when loading term you don't get its parents. This was confusing to me and I thought setValue() just doesn't work. But the truth is that it works perfectly.

To get the code from above working, only a minor edit is required - it's using 0, not NULL:

$term->get('parent')->setValue(0);

This deletes all the hierarchy the term has and writes one record to the taxonomy_term_hierarchy table - with zero parent.

If you need to delete the hierarchy manually you can use deleteTermHierarchy():

\Drupal::entityTypeManager()->getStorage('taxonomy_term');->deleteTermHierarchy($tid);

but be warned that the term will disappear from the lists on /admin/structure/taxonomy/manage/<vocabulary>/overview page since it's missing any hierarchy now. To fix this you need to add a record to the taxonomy_term_hierarchy table with zero parent. And that's exactly what setValue(0) does - deletes hierarchy and adds that record.


AJAX Throbber - Keep throbber image but delete Please wait... message?

@Jimajamma answered the question correctly in the first comment.

 $form['my-model']['#ajax']['progress']['type'] = 'throbber';
 $form['my-model']['#ajax']['progress']['message'] = NULL;

Must explicitly be set and configured within the ['#ajax'] form element.


Drupal 6 - specific template if node contains specific form element

The relationship between nodes and webform components is maintained in the webform_component table so you should be able to get the data directly from there:

$sql = "
  SELECT COUNT(*)
  FROM {webform_component}
  WHERE nid = %d
  AND value = '%s'
  AND type = 'hidden'";

$args = array($vars['node']->nid, $field_value);

$count = db_result(db_query($sql, $args));

if ($count > 1) {
  // The webform has a hidden field with the correct value
}


How can I alter the 'submitted by username' for a comment?

Solution

A solution is to not use $submitted, but to use $author and $created separately in comment.tpl.php.


How do I get all available form field types?

The core fields are provided by hook_elements so you can just invoke that hook to get a list of all field types in the site using module_invoke_all():

 $all_types = module_invoke_all('elements');

The array keys of $all_types are the machine names of the elements, each of those points to another array containing the element information.


How can I limit users to one account each? (Or, how can I detect users who have multiple accounts?)

You can not. Only limitation is Useraccount with one Emailadress. But if the same User Logs in with a different name and a disposable email adress, you can not verify if it is the same User. Something like undisposable will help. But it's not the solution.

Also if 200 Users use the same Proxy/same IP, you will limit them.


How to permit users to view unpublished nodes which they didn't create?

Solution 1

I would "set the permissions 'Access the content overview page' ...", and combine that with using the Rules module to prevent "the Reviewer can modify all contents". Read on for more details about how to do so.

Create a rule (using the Rules module), that is a variation of the rule I included (in export format) in my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?".

These are the changes to that rule to make it work for this case also:

Append /edit at the end anywhere there is already something like node/% (I assume when somebody tries to edit a node, they use a node with  /edit at the end, though any variation of that should work in a similar way).
Add a Rules 'Condition' to verify that the current user trying to do such edit does NOT have role "Editor".
You probably also need to add another Rules condition like "content is of type" (i.e. 'article' in your case, something that is not mentioned in your original question, but in an extra comment). That way the rules action does NOT apply for ay other content type.
Change the "Message" (in the Rules 'Action') to something that fits your needs.
Modify the Rules 'Action' to fit your own requirements, e.g. to issue a redirect to some other page.

Note that the Rules Event is "Drupal Is Initializing" ... Otherwise you are, for sure, "too late": you don't want the rule to be triggered after the edit session has been started already, instead it should be triggered before that. I.e when Drupal is getting ready to start an edit session.

Haven't experimented/tried creating this rule (= variation of the rule in the answer I mentioned above). But pretty sure it'll work.

You may also want to look at my answer to "https://drupal.stackexchange.com/questions/182958/how-to-limit-appearance-settings-based-on-roles-permissions/182959#182959" for another example of a rule, which uses some techniques similar to what you'd need here.

Solution 2

Solution 1 should work, but its weakness is that it's based on "Bypass Content Access Control". Personally I do not like that either. So I agree with your comment about that (a comment which has been removed via moderation). But hey, it's "a" solution to answer "your" (original) question.

If it was up to me to implement a "real" solution for the challenge you're trying to solve, I'd go for a plan b, as further detailed below.

Have a look at my answers to either of these questions:

How to implement a multi step approval with webforms/entityforms based on form components?
How can I allow anonymous visitors to submit content?

These answers explain how you can implement a workflow that is pretty (though not exactly) similar to what you are looking for.

To do so, it "only" requires you to use these modules (and regular content types):

Rules.
Node Convert.
Flag.
Content Access (already suggested in the previous answer also).

And by using such approach, it does not require modules like "Webform" or "Workbench" (modules that are typically involved for these kinds of workfows).

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module.

Note: This "Solution 2" is also how I implemented a variation of your question on 1 of our own sites: it starts from an Issue (= problem or feature request), evolves to a Recipe (= instructions about how to get something to work) and ends with a Software solution (= a plugin or so, whereas the Recipe becomes part of the documentation). Node Convert and Content Access do most of the work for this, and even works in D6 ...


How can I disable parent menu link to be non-clickable?

Install the Special Menu Items module. You can add menu items that are placeholders or separators but aren't clickable. It is found on the drupal module site: https://www.drupal.org/project/special_menu_items


Maybe this is a render array and you need to use link['#text'] here (sorry if I'm on the wrong track).

Edit: If {{ link.text }} worked on subsequent tries, then my answer is definitely wrong, and the reason for your problem was probably related to caching or something.


The safest way is to use field_get_items() like this (which will handle any languages):

$xmlPath = '';
if ($items = field_get_items('node', $node, 'field_3d_model_xml_path')) {
  $xmlPath = $items[0]['value'];
}

If you want to access it like you currently are (sometimes it is useful to do so but in your case I don't think so, this is just to be more complete), use the LANGUAGE_NONE constant for the 'und' language instead of hard coding it, like this:

$xmlPath = DRUPAL_ROOT . "/" . $node->field_3d_model_xml_path[LANGUAGE_NONE][0]['value'];


How can I auto tweet any node of a specific type to Twitter?

I ended up doing this with Rules, Rules Bonus Pack, Views, Flag & Twitter Modules.

Set up a Rule that is:

Triggered during Cron runs.
Has no conditions
Loads a list of Node IDs from Views (Rules Bonus Pack)
Posts to twitter based on the first NID in the view.

For my view, I made a flag called Tweet This attached to my node type, and the view displays nodes that have this flag.  You could use a different method to grab the list of nodes you want to tweet, such as filtering by date posted (get older content based on a given date) or number of views (popularity).

Good luck!


Data in field_revision with Create new revision unchecked

Is this how it's suppose to work?

It depends on which storage backend you use. The default sql backend works this way.

It shouldn't effect speed (much) but will instead effect data storage which usually isn't a problem.
Drupal will not completely delete a field, but instead mark it as deleted. If you want to completely delete it, you need to delete it from the field_config and field_config_instance tables.


How do I download a dynamically-created file in a form submission?

I was off-track in even trying to do this with AJAX, as Clive mentioned in his comment. Instead, I just made it a normal submit button, and then overrode the form action. The result is that the data is downloaded as a file, the form doesn't reload, and the data output section doesn't update, which is the desired behavior in this case.
The button, along with a new format element:
$form['download']['format'] = [
  '#type' => 'select',
  '#options' => $this->getValidFormats(),
  '#title' => $this->t('Select format'),
  '#weight' => '0',
];
$form['download']['download'] = [
  '#type' => 'submit',
  '#value' => $this->t('Download'),
  '#weight' => '10',
];

The submit function:
public function submitForm(array &$form, FormStateInterface $form_state) {
  switch ($form_state->getValue('op')->__toString()) {
    case 'Download':
      $this->download($form, $form_state);
      break;
  }
}

And the relevant part of the download function:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

$response = new Response($file_content);
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'data.' . $format);
$response->headers->set('Content-type', $content_types[$format]);
$response->headers->set('Content-Disposition', $disposition);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Content-length', strlen($file_content));
$form_state->setResponse($response);


I recommend checking out the Webform module.  It seems like the best way to handle this type of functionality.


You don't. At least not in Views. That's not the task of the client, that's the task of the server. Set a proper collation for the column and / or table. If you really wanted to, you can write a sort handler to use ORDER BY collation but changing the collation with ALTER TABLE is the right thing to do.


The answer is that "Commerce Product Bundles" (https://www.drupal.org/project/commerce_product_bundle) is never recommended since it circumvents large portions of Drupal Commerce. You should consider using line item fields or https://www.drupal.org/project/commerce_bundle if bundling is important to you.

Note: Custom line item fields also suffer from not having ajax updates. The community effort to make this a reality can be found here: https://www.drupal.org/node/1541886 and a video that describes an interesting use case for line item fields is here: https://www.youtube.com/watch?v=j9KsyvQZaAY


Filter the nodes by language output by the view

one work around is to re-enable the i18n module, to access the filter again, then use some hooks ( like hook_form) to hide and set the default values for the i18n options in the node form if you want to remove those options from the user interface.


context block visibility - disable block for certain role

Perhaps this module might do the job for you https://www.drupal.org/project/hide_block_by_role doing a quick google search suggests that this would be the ideal module for you

Hope that helps

Seamus


Integration of two sites (one is Drupal-based, the other isn't)

If you want to do your authentication externally to Drupal, you could use the Secure Site module.  You'd still need mod_auth_cookie to avoid double-password entry, but at least the username and password would be the same.  I don't see mod_auth_cookie anywhere out on the internet any more, but I've got the code and could re-publish. As I mentioned in my comment above, it needs a little work.

Another way to avoid double password entry would be to put your sites at example.com/drupal and example.com/other, and protect all of example.com with Apache basic authentication.


I agree that redirecting a 404 page is a bad idea.  One way customize error pages is the blocks404 module.


How to capture value of a field in a node

What u can do is, pass leg_id in the function definition, like:

function get_committees($leg_id = '') {
if(empty($leg_id)) {
$leg_id = 'NCL000208';
}
...

and in the content of block inside block_view, u can call this function, with leg_id, if u are sending leg_id through url, then u can get the leg_id from url using arg() function, and then passing it to function.

But since u want to get Leg_id from node, what u can do is:

if (arg(0) == 'node' && is_numeric(arg(1)))
$nodeid = arg(1);
$node = node_load($nodeid);
$field_leg_id = $node->field_name_field_leg_id['und'][0]['value'];

and sending $field_leg_id to function get_committees($field_leg_id)

// Edited

You can do the same by calling menu_get_object(), it will return you an array, what u can do is:

$menu_obj = menu_get_object();
$leg_id = $menu_obj->field_name_field_leg_id['und'][0]['value'];


Dynamic site title based on role and/or content type

As much as I know the site name is being output with $site_name in a basic Drupal 6 page.tpl.php file and is also part of the $head_title variable. To change them dynamically you could use template_preprocess_page() in your template.php file. Assuming you want to change one or both of those variables based on the user role you could use the following example:

function mytheme_preprocess_page(&$variables) {
  global $user;
  if (in_array('administrator', $user->roles)) {
    $head_title = explode(' | ', $variables['head_title']);
    $head_title[1] = 'Title for admin';
    $variables['head_title'] = implode(' | ', $head_title);
    $variables['site_name'] = 'Site name for admin';
  }
}

Both the head title and site name variables are modified for the 'administrator' role in this case. It should be relatively simple to make this work for all roles the way you want if writing some custom code is not an issue.


How to change number of item per page in taxonomy page?

Go to Admin > Structure > Views. Enable the Taxonomy Term View :

In views configuration change the pager settings as you want.


How to insert a custom search fields in a views page

On your view, all you simply need to do is add a filter criteria and expose it to the user. So you add a filter criteria of your content type, that you will not need to expose since thats the one you want to search on.

If you are searching on the title, you add a filter criteria, select content:title, it takes you to the next selection, select expose to visitors. You can also choose what operator to use and if need be, you can also expose the operator. See screenshot


How to connect to drupal 7 using web service?

Your use case can be achieved using Services module easily.

All you need to do is write a hook_service()

refer http://drupal.org/node/118126 Or just look into the services module's any child module, may be user_services.

Do this,

Write a service that exposes all your query parameters as fields.
Accept these parameters into your web service callback and perform your business logic.
Return your results, this is just a return statement, no JSON conversion here.
ex: return $output.
//$output contains your array or data structure that you have as a result of your queries.

Now, how to convert the data to JSON. ?

Services module will provide you intermediate servers,  XML-RPC, JSON. (these are by default, there are more avaialable on drupal.org). These servers function as end points to whom you can connect using external applications or entities. ex: http://www.domain.com/services/json.

Thats it, the flow will be,

You connect to the endpoint, URL http://www.domain.com/services/json. Pass the data in JSON.
the JSONserver will convert that into PHP and will pass it to your web service callback.
You do the processing and return the data to the web service in PHP.
The server converts the data into JSON again.
This is handed over to the HTTP request that requested the processing in the first place.


Programmatically hide comment and view tabs

A more generic solution could be Tab Tamer.

  Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.


Programmatically adding registration type (Entity Registration module)

Registration _type is just an entity type so is exactly the same as creating any other entity:

$registration_type = entity_create('registration_type', array(
    'name' => 'flake',
    'label' => 'Flake',
));
entity_save('registration_type', $registration_type);

Sometimes it helps to create an entity via the UI provided with a module and then load and inspect it to help understand what values can be provided.

For example after creating a registration type visit /devel/php (make sure devel module is enabled) and run this code:

dpm(entity_load_single('registration_type', 1));

You should see an output similar to this:


How to clear or rebuild a cached block for a specific user?

This data is stored in the block_cache bin under the cid format:

<MODULE_MACHINE_NAME>:<BLOCK_MACHINE_NAME>:<THEME_MACHINE_NAME>:u.<UID>

Knowing that, you can build some wrapper function for cache_clear_all() that will delete any arbitrary UID's cached block:

function clear_user_block_cache($uid, $module = 'MYMODULE', $block = 'MYBLOCK', $theme = 'MYTHEME') {
  cache_clear_all("$module:$block:$theme:u.$uid");
}

You can invoke this function call whenever the user takes the relevant action.


How to "freeze" a View at the time of publishing?

I thought about the relationship angle and couldn't find one but I have been known to be blind in the past to things in front of me and instead went the hook_views_pre_view() route...

function YOUR_CUSTOM_MODULE_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='last_sunday_and_now') { // or whatever your View is named

    // see what we have to work with...

    $filters = $view->display_handler->get_option('filters');
    drupal_set_message('
Before: ' . print_r($filters, TRUE) . '
');

    // here on my box it is 'date_filter' so let's change things up

    $filters['date_filter']['default_date'] = // set this to whatever you want instead of "Last Sunday"
    $filters['date_filter']['default_to_date'] = // set this to whatever you want instead of "now"

    $overrides = array();
    $overrides['filters'] = $filters;

    foreach ($overrides as $option => $value) {
      $view->display_handler->override_option($option, $value);
    }

    // let's see what we have...

    $filters = $view->display_handler->get_option('filters');
    drupal_set_message('
After: ' . print_r($filters, TRUE) . '
');

  }

}

It's up to you to define the logic of what to set the dates to, but if this is sitting on a node, you can grab the post date of it via menu_get_object() pretty readily and then use any of the various date and time functions to create the dates.


How to get the installed version of a module?

You can use the global function drupal_get_installed_schema_version():

$update_hook_count = drupal_get_installed_schema_version('mymodule');


URL alias for File field on a Content Type

Well attachment links module does exactly what you want, this module is still being maintained, the fact is that there is not a new stable release for this module, but the manteiners are solving issues in the issues queue, and they commit changes to the 7.x-1.x-dev download that version and you will see it works like a charm. Check also Upload replace module is good also use the 7.x-1.x-dev version of this module. Both modules are for the same purpose but they do it in a different way.


How to attach external library in twig file with parameters?

In your theme.libraries.yml file add below lines

theme.social:
  js:
    'https://d.line-scdn.net/r/web/social-plugin/js/thirdparty/loader.min.js' : { external: true, defer: true, async: true }

In your twig file

{{ attach_library('theme.social') }}

Clear cache & it works :)


You should be able to run the action "Fetch entity flag count" against the entity you're dealing with. In Rules you can have variables to store that and compare later.


How to alter textfield auto-submit delay?

I tried different ways to do that, this working one was suggested by Andy in comments to a close but different issue, thanks to him !

In fact CTools autosubmit has a hardcoded delay on submitting fixed to 500ms.

A possible way is to switch auto-submit.js to your own modified copy. However if you do this, you'll need to check if auto-submit.js has changed every time you do an upgrade to CTools. :

function neptune_js_alter(&$javascript) {
  if ($some_condition) {
    $new_autosubmit = drupal_get_path('theme', 'YOUR_THEME') . '/js/auto-submit.js';
    $javascript['profiles/commons/modules/contrib/ctools/js/auto-submit.js'] = drupal_js_defaults($new_autosubmit);
  }
}

And set your value into auto-submit.js :

//Lines 87 and following
    var timer = 3000;
          .keyup(function(e) {
            if ($.inArray(e.keyCode, discardKeyCode) === -1) {
              timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
            }
          })
          .bind('change', function (e) {
            if ($.inArray(e.keyCode, discardKeyCode) === -1) {
              timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
            }
          });

To be more flexible you may want to add an attribute to the input you need to change :

function MODULE_form_MYFORM_alter(&$form, &$form_state, $form_id) {
  $form['MY_INPUT']['#attributes'] = array('class' => array('ctools-auto-submit-delayed'));
}

And then change value for this class only

    var timeoutID = 0;
    var timer = 500;
    if ($(this).hasClass('ctools-auto-submit-delayed')) {
      timer = 3000;
    }
    $(this)
      .bind('keydown keyup', function (e) {
        if ($.inArray(e.keyCode, discardKeyCode) === -1) {
          timeoutID && clearTimeout(timeoutID);
        }
      })
      .keyup(function(e) {
        if ($.inArray(e.keyCode, discardKeyCode) === -1) {
          timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
        }
      })
      .bind('change', function (e) {
        if ($.inArray(e.keyCode, discardKeyCode) === -1) {
          timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
        }
      });

This would be more elegant & flexible to pass directly the timer value to js, but I have no time to think more about it.

PS : there is an existing patch about that issue but it returns errors in my config.


How can I load a menu programmatically with an active trail set by a provided URL?

Inject the menu.active_trail dependency along with menu.link_tree:

private $activeTrail;

/**
 * {@inheritdoc}
 */
public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, MenuLinkTreeInterface $menu_tree, MenuActiveTrailInterface $active_trail, EntityTypeManagerInterface $entity_type_manager, Request $current_request) {
  parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

  $this->menuTree = $menu_tree;
  $this->activeTrail = $active_trail;
  $this->entityTypeManager = $entity_type_manager;
  $this->request = $current_request;
  $this->alias = $this->request->query->get('alias');
}

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $configuration,
    $plugin_id,
    $plugin_definition,
    $container->getParameter('serializer.formats'),
    $container->get('logger.factory')->get('rest'),
    $container->get('menu.link_tree'),
    $container->get('menu.active_trail'),
    $container->get('entity_type.manager'),
    $container->get('request_stack')->getCurrentRequest()
  );
}

Now instead of:

$tree = $this->menuTree->load('menu_id', new MenuTreeParameters());

get the active trail ID's just before building your menu and pass it in as part of the parameters:

// Change this to menu machine name.
$menu_id = 'menu_id';

// This should return an array.
// Array contains menu link uuid's, keyed by the uuid's iirc.
// For example something like:
//   'menu_link:abcdefg_123' => 'menu_link:abcdefg_123'
$activeTrailIds = $this->activeTrail->getActiveTrailIds($menu_id);

$params = new MenuTreeParameters();
$params->setActiveTrail($activeTrailIds);
$tree = $this->menuTree->load($menu_id, $params);

This should return you a menu tree with correct active trails.


Pages are not accessible, menu links are not displaying properly

As I have noted in the comments of the first answer, the issue was due to a change in versions of PHP. The bug was previously reported here.


You should update the HybridAuth library to the latest version


Route callback for RegisterForm results in Call to a member function getEntityTypeId() on null

I believe the problem is here:

_form: 'Drupal\mymodule\Form\RegisterByRole'

You need to use _entity_form rather than _entity, as the RegisterForm is actually an entity form for the User entity, as described in the Entity declaration for \Drupal\user\Entity\User:

"form" = {
  ...
  "register" = "Drupal\user\RegisterForm"
},

But to do this, you'll have to register a new form op for that class. You can do this in hook_entity_type_alter():

function hook_entity_type_alter(array &$entity_types) {
  $user = &$entity_types['user'];
  $user->setFormClass('role_registration', 'Drupal\example\Form\RegisterByRole');
}

Then, back in your route, you'll remove _form and instead implement_entity_form, setting it to to user.role_registration:

_entity_form: 'user.role_registration'


I haven't run into this issue again. I think a Drupal update resolved the problem.


User registration silently fails - how to debug?

Recommended steps to trace the error:

Look at watchdog (which you did)
Look at the systems php and apache (or whatever you use) error logs
Take a local copy of the site and start digging

You can find your system logs (php and apache) by looking at the php info under "Admin > Reports > Status > PHP".

For local debugging: http://ratatosk.net/drupal/tutorials/debugging-drupal.html

My first point of entry would be the form definition. You could try for example to add an #after_build callback that get's called once the form has been fully build, and then check which validation and submit handlers are registered.

In your case I would suppose though, that you don't need to go that far. It's probably pretty basic error that will show of in the system logs.


How do I test a paragraph bundle entity reference with Behat?

I needed something similar so I implemented a context for paragraph support.

Install using composer require miiimooo/behat-tools

The follow the installation and usage here: https://github.com/miiimooo/behat-tools

In your feature you can then write:

Feature: Content
  @api
  Scenario: Paragraph creation through Drupal 8 API

    Given a "my_paragraph_type" paragraph named "my_arbitrary_name":
      | title             | Lorem ipsum |

    Given I am viewing a "page" content:
      | title            | Dolor sed         |
      | field_paragraphs | my_arbitrary_name |


How can I accurately determine when a customer is on the "Review" step in Commerce?

A good place to look for example code related to the checkout form is CheckoutController.php. Its formPage() function ensures the form for the correct checkout page is built by comparing the checkout step requested in the URL to the checkout step the order last advanced to, ensuring the customer isn't trying to directly navigate to a later step than it's entitled to.

You can see that it uses the a route matcher to get the named 'step' parameter from the URL, and you can do the same thing in your own code. Typically you'd inject the route matcher into the checkout pane class, but a quick and dirty solution to fetch the current route matcher from the container is:

$container = \Drupal::getContainer();
$route_matcher = $container->get('current_route_match');
$step_id = $route_matcher->getParameter('step');

This will functionally do what you've done by looking at the URL directly, to be honest, but it's a bit more structured way of doing so.


How to finally disable comments on content type?

As juampy wrote, node_revision should be updated as well. You need to execute 2 queries:

Step 1:

UPDATE node SET comment = 0 WHERE type = 'your_content_type'

Step 2:

UPDATE node_revision nrev
INNER JOIN node nd ON nrev.nid = nd.nid AND nd.type = 'your_content_type'
SET nrev.comment = 0

Step 3: Clear cache


How do I enable modules in a Simpletest-Selenium test (Selenium module)?

It should work completely the same. You should be able to enable modules passing arguments to setUp().

Implementation of the setUp() method for DrupalSeleniumWebTestCase is

protected function setUp() {
  $modules = func_get_args();
  parent::setUp($modules);
  //...
}

So everything passed to it is passed to parent setUp method that should enable modules for you.


Drupal 6: Allow external site to authenticate via Drupal

If you have access to the same cookies as the Drupal site, you can pull the session ID out of the SESS* cookie. Then check the sessions drupal table for the uid.

The session cookie name is a little more challenging to predict as it is "SESS"+ an md5 hash of the session name from the host domain URL or cookie_domain setting in settings.php file. Given your full control over the site, it shouldn't be hard to work with that though.


Have you checked out the role delegation module? Sounds to me like your already using it but I may be wrong. It allows users with certain roles to act like the administrator. You can limit which roles can be granted.


Avoid duplicate product while using variations

It sounds like you reference multiple products per display node, so adding that relationship results in multiple rows. A real easy solution is to filter by the delta value from your product reference field so that only the first referenced product results in a row being shown. Ideally we'd add another filter that let you filter by the default delta value, as that can differ from 0 if altered via code.

The filter you're looking for should read something like: Content: Product (field_product:delta) and you should set the filter value to 0. No need to expose it.


Create a field linked to a vocabulary with Drush

You are missing Entity type. See the documentation from drush

  Create fields and instances. Returns urls for field editing.

  Examples:  drush field-create article                Define new
  article fields via interactive prompts.                        open
  drush field-create article         Define new article fields and
  then open field edit form for refinement.   drush field-create article
  Create two new fields.
  city,text,text_textfield
  subtitle,text,text_textfield

  Arguments:  bundle                                    Content type
  (for nodes). Name of bundle to attach fields to. Required.
  field_spec                                Comma delimited triple in
  the form: field_name,field_type,widget_name. If widget_name is
  omitted, the default widget
                                             will be used. Separate multiple fields by space. If omitted, a wizard will prompt you.

  Options:  --entity_type                             Type of entity
  (e.g. node, user, comment). Defaults to node.

As you can see the entity type defaults to node . So you have to specify the entity type as taxonomy_term.

  drush field-create ABC myfield,text,text_textfield --entity_type=taxonomy_term


How do you make an existing variable (from a module) available for use in my__node.tpl.php? D7

The only variables different template files have in common are the ones returned from template_preprocess(), or hook_preprocess(). See also _template_preprocess_default_variables(), which defines the default values for some of those variables.


Select list of node titles for a view exposed filter

Look into the Finder module in addition to creating a View Page.

From the Finder module project description:

  Typically Finder is used for these purposes:

  As a search tool to find a group of nodes or users.
  As a way to navigate to a specific node or user page that matches criteria.
  As an alternative to exposed filters for a Views module display.

  Specific example uses of Finder:

  An autocomplete search on node titles in order to find a node.
  A select list of all the possible values for a particular content field
  in order to get a list of corresponding nodes.
  Multiple groups of radio buttons and checkboxes with taxonomy terms to find nodes that match all the selected terms.
  An autocomplete search on usernames in order to go to a user profile.
  A multi-step wizard form to whittle down a pool of potential results by asking questions on one step that will reduce the possible answers on the next step.

Finder should be able to pick and choice, or filter, what shows up in the that Select list.


There is no FormBase::buildForm() method. FormBase implements FormStateInterface, and the method FormStateInterface::buildForm() exists. So when you extend FormBase, you must implement buildForm(), however you do not/cannot call parent::buildForm(). Instead, you must build the form array yourself, and return that.

This differs from ConfirmForm which has a buildForm() method, which is why when you extend ConfirmForm you can call parent::buildForm().


When you say "what he had fill in my custom registration form" do you mean that fc_home_city, fc_pin and fc_loan have equivalent fields on the user entity (probably called something like field_fc_home_city, etc)?

If so then I don't see why  you are trying to populate those fields with code.  One of the main advantages of the Rules framework is that you can can use the token selector system to pass in values nested into the objects you have to hand without having to write a line of code.

For example if you wanted to pass in the field_fc_home_city value of the current logged in user to the "Home city" field then you'd enter "account:field-fc-home-city" into that field and then every time it executes, that token will be replaced with the correct value for the current logged in user.

If it's not the logged in user you want to work with then so long as the component receives the user account as a parameter then you will be able to use the system to get the values from that user entity.

The javascript drilldown mechanism on the fields should help you get to the right token, otherwise you can press "Switch to direct input mode" and find the token in the "Replacement patterns" fieldset.

A good overview of how it works can be found here.


Add Taxonomy Term automatically based on term from user's account

This sort of thing is generally handled through contextual filters in your view. Views, Panels and Page Manager work well together to manage passing contextual filters to a view for filtered output, but there is a bit of a learning curve involved.

I'm not generally one for video tutorials, but I found this one to be a good introduction to this methodology: http://drupalize.me/videos/overview-page-manager-series

If you want a quick-and-dirty way to achieve this, use the module views_field_view https://drupal.org/project/views_field_view and do something like this:

in your forum posting view, set a contextual filter on your state term reference field tid
create a new view based on users, and add a contextual filter on "User: Uid"
on the contextual filter configuration page, under "when the filter value is not available" select "provide default value"
under type, select user id from logged in user
add a field for the state term reference field tid
add a field Global:View ( provided by the views_field_view module ), with these settings:
View: your forum postings view, as modified with contextual filter above
Display: Master
Contextual filter: [tid]

This should now display all forum postings whose state of residence matches the currently logged in user's state of residence.

note that if you are on a page URL that points to a profile of a different user, and you've set it up so the view is visible on this page, it will show all postings for THAT user, as the view will be able to grab a uid from the URL. ... so ... that may be a benefit or a drawback, depending on your intent.

Best'o'luck

disclaimer: written on short sleep. hope i got all the i's dotted and t's crossed


How to get node title using this query on template?

You shouldn't do queries like like that. You should use EntityQuery. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/function/QueryInterface%3A%3Acondition/8.8.x and EntityFieldQuery to search Content Type for text and select matching Nodes
EntityQuery will return the nids. Then use the node storage's loadMultiple to get the node themselves. Typically something like Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids)
I would expect the Node title would be gotten in your loop with {{ oneItem.title }}.
If that's not working I suggest installing and enabling the devel module, and sticking {{ dump(filters) }} in your custom template to investigate the structure you're getting


If you want to autorotate images based on their EXIF information, you can use the Autorotate submodule provided by Imagecache Actions.

Enable the Autorotate submodule and then add an Autorotate image action to each of your image styles.  This will automatically rotate the images and hopefully give you the results that you expect.

Note that this submodule requires the Exif PHP extension to be enabled.


Showing latest news article from taxonomy

Download the Views PHP module:

  This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.

In Views:

create a View of News Content Type, as a block and set it up to show all entries for now in the format and layout you desire
add a contextual filter for the Category field
Provide a default value, PHP code:

$node = menu_get_object();
return $node->field_category['und'][0]['tid'];

The first line retrieves the page object (which should only ever be a News Lift node if the block is set up properly), then returns the term ID associated to the current node as a contextual filter to the view. This assumes a single language site.

Under /admin/structure/block set the view-block to show where you want on the page, limit it to show only on the content type News Lift


How can I prevent certain roles from editing other roles?


Added field to Basic Page Content Type is not displayed in the page

There is nothing special about putting fields on the Basic Page.

However, to be visible, you have to make sure that the field is not <Hidden>.

To check that, go to the Manage Display  panel for the bundle (content type) you've got problems with.


In Views you can group by a particular field if the display allows fields (table, not teaser, etc). Under the Settings for Table for example you can choose the field to group the results:

The field has to be present in the list of Fields, but can be excluded from display if desired.


How can I change page title in node with some options?

You can fix all the things with
RouteSubscriberBase
https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones...

...

/** @var Route $entityUserEditForm */
$entityUserEditFormRoute = $collection->get('entity.user.edit_form');

// Change default user details entity form and title.
if ($entityUserEditFormRoute) {
  $entityUserEditFormRoute->setDefaults([
    '_entity_form' => 'user.complete_registration_form',
    '_title' => 'Complete Registration Form',
  ]);
}


Creating a new content type places random options on the content type page

Those options are shown to the administrator users by default; if you log in as a regular user, you don't see them. You can enable and disable them in permissions "node / administer content".


how do I configure a view to make two fields be inline

Hide the two fields in the views ui, then add a Global: Custom text field (make sure it is below the two hidden fields). In this field's text box you then add the two hidden fields back via replacement patterns (that's why it needs to be below the two hidden fields, else it will not see them), and wrap them in inline html or html that you will style inline.

You can use unformatted list format.

To make two rows out of three inline you will just use CSS with :nth selector. Else you can override the theme template for views (in advanced section). You copy and paste the template, then rename it to a proper suggestion. In that template it uses a loop to write the rows. You can rewrite that so that it loops over three at a time, prints two inline, one as block-level element.


Is there a way to make image and text alternate between rows?

Create a custom module as follows:

In sites/all/modules create a directory: ds_odd_even

Add a file ds_odd_even.info under that directory.
Add the following text in that file:

name = "Display Suite Odd Even Output"
description = "Display Suite Odd Even Output."
core = "7.x"

Add a file ds_odd_even.module under same directory.
Add the following text to that file:

<?php

function ds_views_row_adv_past_client($entity, $view_mode, $load_comments) {
  static $i = 0;
  $custom_view_mode = ($i++ % 2) == 1 ? 'left_client' : 'right_client';
  return render(node_view($entity, $custom_view_mode));
}

Install the module as usual. Note the function name above. It is based on the pattern: ds_views_row_adv_YOUR_VIEW_MACHINE_NAME. This is the view name from the admin/structure/views UI page, not the display name from the right hand advanced column on a view. Hence the view that this is based on has a machine name of past_client. If you add more pages and blocks to this view, the view's machine name still stays the same. Each page or block will get a display name in addition. IT IS NOT THE DISPLAY NAME that you add to the function.

Create two view modes in Display Suite.
1. left_client
2. right_client

Add two column layout to both, with alternating image and body placement.

In your view (machine name past_client) set to show Display Suite as format, and in setting select under Advanced View Mode 'Use the advanced view mode selector'.

Clear your cache for good measure. And that is it.

There is no way I see to differentiate on different displays on the same view, unfortunately. You may explore CSS as an alternative, and use the nth-child() selector to alternatively float the display suite regions left or right (make sure you have greater specificity in the cascade or use !important)


Here is an issue on Drupal Groups: http://groups.drupal.org/node/96639.

Possible solutions:

Check if your system is Ubuntu (the installation script assumes that
it is)
Remove everything in /var/aegir and run the installation script again.
Run 'mysql_secure_installation' command and finish it successfully. Aegir
checks for security flaws during installation and block it if, for
example, you have anonymous users enabled in mysql.


To add mime types without hacking core files, you will want to create a new module and use the hook_file_mimetype_mappings_alter.
For example assuming you name your module oftmimetype then like this:

<?php
/**
 * Implements hook_file_mimetype_mapping_alter().
 */
function oftmimetype_file_mimetype_mapping_alter(&$mapping) {
  // Add support for oft.
  $mime_type = 'application/x-font-otf';
  // If the mime type does not already exist, add it.
  if (!in_array($mime_type, $mapping['mimetypes'])) {
    $mapping['mimetypes'][] = $mime_type;
  }
  // Get the array index for that mime type and assign the extension to it.
  $mapping['extensions']['oft'] = array_search($mime_type, $mapping['mimetypes']);
  }
}
?>


how to have conditional Help text for a listbox field

You don't have to code for this. You can use Conditional Fields to achieve it.

You can then use "Manage Dependencies" section (alongside manage display) to set the dependencies:

Then you can see the different fields being enabled or disabled depending on the entered input:

List option "No" Result:

List option "Yes" Result:


There's an issue queue going on drupal.org for this - https://drupal.org/node/2093533

It looks like the module maintainer may have fixed the chrome issue with the latest dev version


How do I link to a local/internal file in Drupal 7?

This is a solution for Intranet deployments only.

Install the Any Menu Path and the Filter Allowed Protocols modules.

Enable both modules and add "file" to the configuration  > text format > allowed protocols.

Edit the link in your menu to read file:///directory/file.html. Check the box labeled "No Path Validation" and save.

If it still doesn't work, check to make sure your browser doesn't need extensions or privacy settings adjusted to accept the file:/// protocol.


taxonomy_node_get_terms(arg(1)) kills layout in page.tpl.php

taxonomy_node_get_terms() needs a node object as the first argument; arg() returns a part of the URL (which is just a string).

You can use the menu_get_object() function to get the current node (if available) so it would be easier to use that:

$node = menu_get_object();
if ($node) {
  $tax = taxonomy_node_get_terms($node);
}


Unable to save term "Big Honor for Branford's Le Petit Café"

This code works perfectly for me:

$term = (object)array(
  'name' => "Big Honor for Branford's Le Petit Café",
  'vid' => 1
);

taxonomy_term_save($term);

No errors, and the term is saved as expected. So it looks like the issue is something to do with your server configuration. Without more details it's impossible to say what that problem might be though.

UPDATE

Turns out this a multibyte encoding issue. Wrapping the string in utf8_encode() will fix it:

$term_name->name = utf8_encode(urldecode("Big%20Honor%20for%20Branford%27s%20Le%20Petit%20Caf%E9"));


Count of users who are logged in per day

Well in other to achieve this, you will be using a combination of modules.

Use the counter module for gathering that kind of statistics. Another option is to enable the statistics module in Drupal core

  Counter module counts how many visitors on your website. This module
  provides real time counting. All data saved to database.

And with google chart tools and the views module create a chart

  Display live data on your site using Google Chart Tools Google Chart
  Tools module provides a simple API to Build custom interactive SVG
  charts. The module contain an example module which demonstrate how
  this module can be use.


Adding more values to Drupal user status

By default, I don't think there's any way of doing this.  The user status is used by other parts of user.module (as well as x amount of contrib modules), so extending it could cause conflicts there.

What you could do however, is add a custom status field to your users and use that.  You'll get most of the normal benefits of the Drupal user status, but it'll be as extensible as you need.

Combine it with Field Permissions to prevent users from being able to see or edit (or either one of those options) themselves should you need to.

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

If you still want a user status that disabled the user account, then you could create a value on your custom status field (let's call it Disabled and then configure a Rule that says:

  Event:

  After saving a user account After updating a user account

  Condition:

  Use data comparison to se if *field_my_user_status* is equal to
  disabed

  Action:

  Block user account

*NB If you do this, don't forget to create an opposite rule that enables the user account based on your field value :)


Create a custom module that defines a block with that form as the content. You can then place that block anywhere on your site using the standard Drupal interfaces (blocks configuration, Panels, Context, etc.).

There are many readily available resources on creating custom modules that define blocks. The Drupal.org Module Developer's guide is a great place to start, as well as the Examples module, which includes a sample module for defining blocks that can be easily copied and customized.


Latest Saved Content keeps appearing on the front-page despite being configured in "content" and "content type"

By default drupal's frontage shows latest content published on site. In drupal this is a /node path which is a view in drupal 8 and a page in drupal 7. If you are using drupal 8 it will be as easy as justmodifying the view. In drupal 7 you can set a different front page in the system configurations and the latest published won't appear any more.


Is it possible to create multiple submission forms for one content type?

The proper way to do this in Drupal is using multiple content types, but if you want (for whatever reason) to still stick to your solution, you can write a custom module, and modify that one before rendering.

Here's an example using the default page content type and hiding the body. Use the Devel module, and dsm() to inspect the form.

function mymodule_menu() {
  $items['mymodule/add'] = array(
    'title'=> 'mymodule add',
    'description' => 'add content',
    'page callback'=>'mymodule_form',
    'access arguments' => array('add content'),
    'type'=>MENU_NORMAL_ITEM,
  );

  return $items;
}

function mymodule_form() {
    global $user;
    $node = new stdClass();
    $node->uid = $user->uid;
    $node->type = 'page';
    node_object_prepare($node);

    module_load_include('inc', 'node', 'node.pages');
    $form = drupal_get_form("page_node_form", $node);
    hide($form['body']);
    dsm($form);
    return drupal_render($form);
}


How to exclude current node from a block view?

One option is to clone the block, make it show everything (remove the contextual filter and the exclude setting) and in block configuration (via admin/structure/block) configure it to show on all pages except node/*.

Another option, if you want to have everything in one display and don't mind using php, is to use Provide default value > PHP code:

if (arg(0) == 'node' && is_numeric(arg(1))) {
  return arg(1);
} else {
  return 0;
}

The exclude checkbox must be on.

So this is giving the sql the node id to be excluded, normally the current node id, and when there is no node id, the node id to be excluded is 0, in other words don't exclude anything as there is no nid 0.

Without checking that the second argument is numeric, this wouldn't work on the default front page as it would have 'node' but not have nid.


In this resource http://drupal.org/node/726282 you will find a very useful description about CCK fields and his relation with the function to alter forms, called hook_form_alter(). in few words, you must also use an after_build() function.


I'm getting a page not found error when trying to visit my custom form

Problem 1: Incorrect namespace. The class name should not be included in the namespace. Your namespace should be:

Drupal\lookup\Form

Problem 2: The name of your class is not the same name as the routing file (capitalization).

Class name: lookupform

Routing file: _form: '\Drupal\lookup\Form\lookupForm'

(Capital F)

Problem 3 (credit: laymannx) - you're visiting the wrong path. Should be visiting /lookupform (after fixing the above problems).


How do I cache the result of db_query()?

Doesn't mattter for caching if you use views or db_query(). Caching works always the same, how the data is fetched when the cache misses is completely up to you.

Build a cache ID to identify your cache entry. Can be a simple, hardcoded string or something complex based on arguments and so on.
Check if can load from the cache.
If not, rebuild data and put it into the cache with the desired expiration time.

To see some examples, you can look at the functions that use cache_get(), for example variable_initialize().

If your function is called multiple times then you probably want to combine it with a static cache, see for example archiver_get_info(). And if the data rebuilding is really slow, you can prevent it from happening multiple times by using the locking framework as variable_initialize() does.

Note that caching a single query only makes sense if it's a slow one, because a cache_get() is also a db query unless you use an alternative cache backend like Memcache.

And lastly, Views has caching already built-in and can be configured in your view. So that might be an option as well.


Remove order from Field Collection set in form

Well, as Rupesh suggested in his comment, i was able to use CSS for hiding the Order column in my form:

First, i specified an ID for the fieldset field in my module's node_form_alter() function:

$form['field_user_details']['#attributes'] = array('id' => 'user_details');

Then in my CSS, i used these lines to hide the Order column:

#user_details table th:nth-child(2) { display: none; } /* Hide the Order column Label */
#user_details table td.delta-order { display: none; } /* Hide the Order column */


How to tell if a Webform field has been hidden by conditional rule

Assuming you know the numeric id of your field (for example let's say it is 5)

If $submission->data[5] is an array,
then the field was submitted. The array may contain an empty string, which means the field was left blank.

If $submission->data[5] === NULL
then the field was not submitted because it was hidden by a conditional rule, or was excluded from the form for another reason (e.g. the user did not have permission to see it).


open_basedir restriction in effect despite file directory within web root

The key here is that PHP is attempting to create the temporary file in a public directory. If you refer to the your PHP settings, find out what is specified for the 'upload_tmp_dir'. Use a phpinfo() call to display this, also available in the Status Report by clicking on the PHP version number. This directory has special privileges that open_basedir will not block. Set your drupal temp directory to this path explicitly and it should work.


What should I use to implement a shopping cart process?

Here are a few typical solutions for implementing an online store:

Drupal Commerce, or its related Commerce Kickstart.
Ubercart.

However, as per your "Simple shopping cart experience", it looks like none of these is what you're looking for. So here are some other modules you may want to look at (excerpts are from their project pages):

Basic Cart:

... a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.

Rules:

Allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).

Flag:

Flag is a flexible flagging system that is completely customizable by the administrator.

The 'Basic Cart' implements the cart, while with the 'Rules' and 'Flag' modules you can implement appropriate business logic (which does not require any PHP coding skills).
If you're not familiar (enough/yet) with Rules, then checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organised in 7 chapters.
Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module.


Memory Size issue is coming while we have increased a lots of Memory

1073741824 bytes = 1GB, so that should be more than enough. I have my development machine set to memory_limit = 256M, which is already pretty much, and I never run into exhausted memory problems.

Your error is probably caused by a mistake or some very inefficient logic in your code. There are a couple of things you can do to find the problem, like:

Switch to a standard theme, to narrow down if the theme is causing the problem.
Disable modules you added recently, one by one, to see which module is causing the problem.
Search for loops in your code that may keep running indefinitely.
Use a step debugger (like Xdebug) to find the point in code where the problem is caused. (Xdebug takes some setting up, but installing it is well worth your time.)
Use a profiler (like XHprof) to see where your memory is going. (Installing and learning XHprof takes time, but if the other methods don't work for you, it can probably answer your question.)


How to pass a parameter/argument to webform using clean urls?

You could solve this using mod_rewrite in your .htaccess file. Try something like

RewriteCond %{REQUEST_URI} ^/path/to/your/webform/(value)$
RewriteRule ^.*$ /path/to/your/webform?param=%1 [L]

This way you can do many things but you can't configure that with the drupal UI. Here's an example with more paramters:

RewriteCond %{REQUEST_URI} ^/path/to/your/webform/(value1)/(value2)/(.*)$
RewriteRule ^.*$ /path/to/your/webform?param1=%1&param2=%2&param3=%3 [L]

Check out the manual.

EDIT: your comment example should look something like that:

RewriteCond %{REQUEST_URI} ^/myform/(\d+)$
RewriteRule ^.*$ /myform?i=%1 [L]

The exact regex at the end depends on your parameters. If you expect only numbers like 1 or 0125 \d+ should be fine. Check out this cheatsheet for more/other char-classes and regex stuff.


SQL + Drupal: how to filter correctly using SQL within a Drupal Database?

I'll make an attempt but I haven't quite identified the problem yet. Does your result set deviate from the expected? Is there an error? Answers to those could make it easier to assist.

A Unix timestamp is simply the number of seconds since Jan 1st, 1970.

The query

SELECT type FROM node
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y') = 2011
    AND FROM_UNIXTIME(created, '%m') = 07;

works for me; it returns all nodes of type 'page' created in month 7 of year 2011. These queries also work:

SELECT * FROM node -- all pages from July
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y-%m') = '2011-07';

SELECT * FROM node -- all pages from May, June, July
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y-%m') BETWEEN '2011-05' AND '2011-07';

SELECT * FROM node -- all pages from weeks 33, 34, 35, 36, starting on Mondays
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%u') BETWEEN 33 AND 36;

SELECT * FROM node -- all pages created between 8 morning and 4 afternoon
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%H') BETWEEN 8 AND 16;

However, you can also use PHP to generate a Unix timestamp from a date, then simply compare that with the stored values (following is untested):

$t1 = mktime(0, 0, 0, 5, 1, 2011);
$t2 = mktime(23, 59, 59, 7, 31, 2011);
//$t2 = mktime(0, 0, -1, 8, 1, 2011); // 1 second before midnight Jul 31/Aug 1st.
SELECT * FROM node -- all pages from May, June, and July
    WHERE TYPE = 'page'
    AND created BETWEEN $t1 AND $t2;

I would suggest you take an exact query you're trying to use and execute it directly against the database in order to determine if the problem is with the query or something else. If it is the query, play around in there until you get the desired result or ask for help.

NB: Drupal expects tables to be enclosed in braces, in case it needs to handle table prefixes. This means the first query (in Drupal) should look like this:

SELECT type FROM {node}
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y') = 2011
    AND FROM_UNIXTIME(created, '%m') = 07;

If you don't use table prefixes it's not necessary (that is, it should still work) but it's good practice to always include them regardless.


Hide the block on the "node/add/my_content_type" page

Try this

$node = menu_get_object();
return isset($node) && $node->type == 'your_content_type' && arg(2) == '';

Edit: forgot about the third parameter


Contextual filter is an an argument to the view, for example through the path or block/plugin context.

It is not visible to the user, it's visible to Drupal.

If you want something to be visible to the user, you need to instead add a filter and then tick the checkbox to expose it, creating a so called "exposed filter". That should then show up in a filter form.


why does hook_menu produce a menu that belongs to the system module?

The only way to remove a menu item defined from a module in hook_menu() is, apart from removing its definition from the module's hook_menu(), removing it with hook_menu_alter().

function mymodule_menu_alter(&$items) {
  unset($items['drutexml']);
}

Menu items that are part of a menu, including the ones defined with hook_menu(), are saved in the menu_links table. Those defined in hook_menu() are saved setting the "module" field to "system" to distinguish them from other links directly added from a module.


Drupal views to display content updated today

For the filters all you should need is:

Content: Updated day [With default value to be Current Date]

Because you have the created date filter you are currently only getting nodes created today.


How can I collapse the *sidebar first* region when the browser width is less than 900 pixels wide?

A media query, just like the one you list, is indeed the proper way to do this.

Obviously you would first need to adjust the width from 480 to 900, but also, you may want to choose "max-width", instead of "max-device-width", as the former will work in a small browser window on a large screen as well. That's really up to you though.
You say that you want to collapse the sidebar, which means you may also want to "display: none;", instead of "float: none;".
Strictly speaking, the "screen and", is not necessary. If you want the rule to apply to all media types, such as print and handheld, you can just omit it.

Example 1, unfloat the sidebar, only on screen media:

@media screen and (max-width: 900px) {
  .sidebar-first {
    float: none;
  }
}

Example 2, hide the sidebar, all media:

@media (max-width: 900px) {
  .sidebar-first {
    display: none;
  }
}


How to show selected options only if item is selected in select?

You may use Reference field option limit module to accomplish this
task

  This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.


How do I use the Drupal 7 API to change ownership of a comment

This changes the comment author details using the core comment API:

$cid = 12; // e.g get from db_select
$comment = comment_load($cid);
$comment->uid = 1;
$comment->name = 'admin';
$comment->mail = 'admin@example.com';
comment_save($comment);

You could also do something similar with a Rules component for use with VBO.


If I've understood right you should implement next steps to achieve your goal:

Take a look at drupal_parse_info_file() function to get a value from .info file.
Alter your form and set appropriate value to #default_value property whithin your field.


Alter a panel page variant provided by another module (programmatically)

You might try creating a clone of this variant and then making your custom changes to it. You can then reorder this variant so it is above the original. This way your custom variant will always get executed and the original one ignored.

Once that is completed, you should then be able to export your variant using features.


Drupal commerce and multiple products sharing SKU

You can handle that with Commerce Product Bundle. Some details about it, from its project page:

  This module extends Drupal Commerce by allowing the site admin to
  collect a number of existing products together in a bundle, and offer
  them at a new bundle price, with a new bundle SKU.

  You can define products that consists of other products. They are all
  combined in one add to cart form which works like the core add to cart
  form. The bundle is then represented by one order line item. This
  allows the maximum compatibility with other modules such as shipping
  or payment modules.

As an alternative, there is also Commerce Bundle. Some details about it, from its project page:

  Implements product bundles for Drupal Commerce. For example, you want
  to offer products A, B, and C for a lower cost if purchased together
  rather than standalone. Notable features include setting the prices at
  the bundle group or product level, and product attribute support.

Note: if you wonder how those to modules compare to each other, then this might help (= quote from the Commerce Product Bundle project page):

  Commerce Bundle also allows creating product bundles. Customers add a bundle to their cart, but the component products show in checkout and order history. It therefore doesn't allow assigning an overall price to the bundle (but it has some neat ways to assign prices to component products). With Commerce Product Bundle, the bundle, not the component products, show in checkout and order history. Therefore an overall price can be assigned to the bundle


Styling the autocomplete dropdown to work with the up/down arrow keys

This should work:

#autocomplete li.selected {
  background-color:#428bca;
  color:green;
}

The items from the autocomplete list are having the .selected class added on hover/key navigation.


record of email notifications sent out (webform / postfix)

Webform doesn't provide default functionality for it.

you can use either of these modules to log outgoing mail:

Mail Log
Email Log


Where is the value in a form textfield stored?

The easiest way to debug form related issues I have found is with the devel module

drush dl devel && drush en devel -y

This module provides a whole host of helpful functions. E.g. in your case you could use this in your validation function:

dsm($form_state['values']);

This would print a lovely formatted array of every value in the form. From there you can drill down to the required value.

I believe you should be checking for:

if (empty(trim($form_state['values']['field_upload_file']))) {
  form_set_error('upload_file', "Please enter a file name: ");
}

Or alternatively, if you are just checking to see if the textfield simply has a value in it, then the better approach would be to use the FAPI and declare:

$form['upload_file'] = array(
  '#type' => 'textfield',
  '#title' => t('File to read'),
  '#required' => TRUE,
);


Limit Entity Reference to published nodes

Create a view with entity reference display. Click add and in the drop down you will see entity reference.

Now create a view and create a filters normally as you do. Now go to your content type services field settings and click views instead of simple selection

Select the views you created and your options will be limited to the result of the view.


Where 'target_id' of field_data_field... tables points?

If you look in the field_data_field_{field_name} table, you will see these columns:

entity_type: tells which type of object the target is.
entity_id: which one in the entity table

For entityforms, you can go to the URL /admin/structure/entityform_types/manage/{entity_type}/fields, and you can see what the {field_name} refers to by finding {name} in the list.

So if you know what type of object it is, hopefully you know how to find the list of fields.

If not, go to /admin/reports/fields and search the full list for your field.


You also might try the user readonly module. It allows to disable or hide certain form fields for certain users.


Menu Block - How to make a new menu automatically available?

I'm not very familiar with the Menu Block module, but this seems to be the proper way of setting the menu_block_menu_order variable when a new menu is created:

function mymodule_menu_insert($menu) {
  $menus = variable_get('menu_block_menu_order', array('main-menu' => '', 'user-menu' => ''));
  $menus[$menu['menu_name']] = '';
  variable_set('menu_block_menu_order', $menus);
}


apache solr result logged users node should appear on top and then other user's node

I strongly recommend using the Apache Solr View module, with this module installed it is only a matter of indexing the correct data and building the view with the correct sorting.


Establish whether a node is NEW in a custom #submit function

You could try this method:

if ($form_state->getFormObject()->getOperation() == 'edit') {
  // existing node
}

These are the operations defined for node:

 "form" = {
   "default" = "Drupal\node\NodeForm",
   "delete" = "Drupal\node\Form\NodeDeleteForm",
   "edit" = "Drupal\node\NodeForm"
 },


List all users whose "member for" and "last access" are the same

These won't be exact matches.  It uses a timestamp value that will vary, even if only a few seconds.

I would suggest doing this in some custom PHP

that module, or writing your own custom functions.  you'd convert the timestamp difference to a reasonable value (say, within 1 hour?) and then user_delete()

I would also add a captcha and/or email verification to help prevent this.


After looking at the source code of the blog module, it appears that the path /blog/<somestring> is sort of reserved for the blog module itself.

Problem:

The pattern based aliases created when creating a new blog node seem to take precedence over those internal paths so if your URL alias pattern is blog/[node:title], you are shown the expected blog node as long as it exists.

Once the blog node is deleted and the alias is deleted with it, /blog/<somestring> means "do whatever path <somestring> does in the blog module" which results in a 403 Forbidden error rather than the expected 404 Not Found error.

Solution:

The only solution I found is to use a different URL alias pattern such as blogs/[node:title] which avoids the problem.

Tip:

Use the Redirect module to let the Pathauto module create redirects when changing URL aliases. It also helps to keep track of those redirects so you can see which redirect URLs still receive traffic and which could be deleted.


how to add dropdown checkbox list in to the search api(facet api) display widget?

What you need to do is:

In your search api configuration (screen you attached), select "MultiSelect element".
Install an appropriate dropdown widget, the jQuery UI MultiSelect Widget is probably the best option for what you need.
Configure the jQuery UI MultiSelect Widget to target your Search API's MultiSelect element:

First, figure out what the id or class of that MultiSelect field is. You can use your browser's "Inspect Element" function to figure that out while viewing the standard Search API Facets on a search page.
Once you have the right class or id, go to the configuration page of the jQuery UI MultiSelect Widget (URL is sth like your.drupal.localhost/admin/config/user-interface/jquery_ui_multiselect_widget) and add it in the "JQuery subselector" text box.

That's it, now you should have a the jQuery MultiSelect Widget rendering your standard Search API Facets MultiSelect field.

Here is a screenshot of the end result (search api block facet rendered as a jQuery UI MultiSelect Widget):

Let me know how this goes!

Appendix A: jQuery UI MultiSelect Widget Configuration

Appendix B: jQuery Update Configuration


How can I allow users to specify image dimensions in CKEditor

Depending on how far you are in your project consider using Paragraphs instead, to have your content built modularly. Inline images are bad practice IMHO. They are difficult to preprocess and difficult to apply responsive image styles.

With Paragraphs (or in general with a fieldable approach instead like Kevin pointed out in the comments) you'd provide certain paragraph types, for example one for pure text and one for an image. Editor then places an image paragraph, followed by a text paragraph and the text simply floates around the image. You can have responsive image styles for the image, you can build the image field according your logic to provide certain crop types etc.

I know this is not the answer you might look for, but honestly for the sake of maintainability think about it if putting everything into the body field will still work in the long run. In my experience this can lead to a very big mess. Hard to disassemble, hard to migrate, hard to maintain.


Try this

 <?php if ($page['triptych_first'] || $page['triptych_middle'] || $page['triptych_last']): ?>

            <?php print render($page['triptych_first']); ?>

            <?php print render($page['triptych_middle']); ?>

            <?php print render($page['triptych_last']); ?>


How can I print current user role in Twig?

You can use below without any function. Because the User module provides the variable in preprocess for all templates: :

{% set roles = user.getroles(TRUE) %}
{{ dump(roles) }}

If you want to do anything only for the particular role then do this:

{% if 'ROLENAME' in user.getroles(TRUE)  %}

The user has the role "ABC".

{% endif %}


Populate a hierarchical select field programmatically

I have saved user with custom hirerarical select field named "field_register_state" like below: it's working very well.

$account = new stdClass;
$account->is_new = TRUE;
$account->name = $username;
$account->pass = user_hash_password($form_state['values']['pass']);
$account->mail = $form_state['values']['mail'];
$account->init = $form_state['values']['mail'];
$account->status = TRUE;

$account->field_user_code = array(LANGUAGE_NONE => array(array('value'=>$userCode)));
$account->field_full_name = array(LANGUAGE_NONE => array(array('value'=>$form_state['values']['field_full_name']['und'][0]['value'])));
$account->roles = array(DRUPAL_AUTHENTICATED_RID => 'authenticated user',$form_state['values']['roles']=>getRoleNameById($form_state['values']['roles'],$form));

$account->field_user_area_name = array(LANGUAGE_NONE => array(array('value'=>$areaName)));
$account->field_created_by = array(LANGUAGE_NONE => array(array('value'=>0)));
$account->field_register_state = array(LANGUAGE_NONE => array(array('tid'=>$statecode)));
$account->timezone = variable_get('date_default_timezone');
user_save($account);
drupal_set_message(t('User Created Successfully'), 'status');

Hope this help's you..


Installed Boost module. How do you tell it is working on your site?

View the source code of the page as you're browsing as an anonymous user. Boost inserts some metadata about the cached page ("Page cached by...") as an HTML comment:

  // Add note to bottom of content if possible.
  if ($_boost['matched_header_info']['comment_start'] && $_boost['matched_header_info']['comment_end']) {
    $expire = $_boost['matched_header_info']['lifetime_max'];
    $cached_at = date('Y-m-d H:i:s', REQUEST_TIME);
    $expires_at = date('Y-m-d H:i:s', REQUEST_TIME + $expire);
    $note = "\n" . $_boost['matched_header_info']['comment_start'] . 'Page cached by Boost @ ' . $cached_at . ', expires @ ' . $expires_at . ', lifetime ' . format_interval($expire) . $_boost['matched_header_info']['comment_end'];
    $data .= $note;
  }


How to restrict access to content based on roles (multiple levels) and show a public preview?

I would use Panels.

Basically, for all of your Panel Pages, you would have two variants.

Each variant would have a Selection Rule based on the user role, one for the role and one for not the role.

Then on each, build up the content the way you need.  Personally, I would make a custom node view for the restricted view, so you can use the Node Being Viewed content piece and just configure it to use the view mode you made.

The reason I recommend Panels is that it makes it easier to change things in the future without needing to get special-function modules to cooperate with each other.


The first error you were getting was because $ isn't defined as jQuery in Drupal 7, to avoid conflicts with other libraries. Adding the closure fixed that, as in your second code example.

As long as the mobilyslider library is definitely loaded into the page, the problem is probably that you're attaching the event before the DOM is ready...so the elements you're trying to attach to don't exist yet.

You could use the standard $(document).ready() method to solve this if you want to, or else use Drupal JS behaviours. For Drupal 7 that code would look like this:

(function($){
  Drupal.behaviors.mymodule = {
    attach: function(context, settings) {
      $('.slider', context).mobilyslider({
        content: '.sliderContent',
        children: 'div',
        transition: 'horizontal',
        animationSpeed: 500,
        autoplay: true,
        autoplaySpeed: 9000,
        pauseOnHover: true,
        bullets: true,
        arrows: true,
        arrowsHide: true,
        prev: 'prev',
        next: 'next',
        animationStart: function(){},
        animationComplete: function(){}
      });
    }
  };
})(jQuery);

Be sure to pass in context to your jQuery selector for reusability.

See Managing JavaScript in Drupal 7 for more info.


How can I enable unauthenticated user to activate himself?

Provided we're talking about Drupal 7:

Navigate to: Administration » Configuration » People »  Account settings.
Under: "Registration and cancellation. Who can register accounts?", check the radio button for "Visitors".
Click "Save configuration" at the bottom of the page.


Contact email flood limit is per whole system(application) or user/ip based?

As you can see its number of emails a user  can send in an hour

https://www.drupal.org/docs/8/core/modules/contact/overview#controlling-repeat-submission-blocking-flood-control

You can specify the text to display on your site-wide contact page and you can optionally limit how many times a user can submit a contact form in an hour.

btw, its defaults that you can override per any contact form . for example :
contact.settings.yml

default_form: feedback
flood:
  limit: 5
  interval: 3600
user_default_enabled: true


Is it possible (and within convention) to insert a hidden field in an views exposed filter to control form content (e.g for re-submit search)?

Though I am providing the solution for the question which you have asked but as per your description I understand you are looking to achieve content boosting with views.

It's a nice idea which has been implemented on some websites like meetup.com, where they boost the local event at top when you visit & these works for anonymous users too as well as authenticated.

You will need 3 modules to achieve this - Location, Smart IP & Views.

I have written a blog post about configuring them to achieve this, which you can find at - http://drupalconnect.in/content-boosting-views

I will recommend you to try this if you trying something like this :)


You will have no problem if you have the same field types installed on the localhost. For example If you are using the email field in your production site, it should be installed also in the localhost.

Assuming your are using Drupal 7, you have three choices:

Features
Bundle copy

  Bundle copy is a replacement for the Content copy module which lives
  in the CCK project for Drupal 6.

Field tools(currently alpha)


How to get block id on block add & edit form?

Have a lookt at Extend Block Class and my answer there about the block_class module.

It does exactly the same to add configurable CSS classes to blocks.


Endless redirect on paths containing question marks

You can try to manually add the query parameters to the redirect URL.

Add this code:

$query = [];
parse_str($current_uri, $query);

just below this code:

$current_uri = \Drupal::request()->getRequestUri();

And then change this line:

$url = Url::fromRoute('entity.node.canonical', ['node' => $nid]);

To this:

$url = Url::fromRoute('entity.node.canonical', ['node' => $nid], ['query' => $query]);


Sub-theme adding prefix to all block machine names

You can't.

This behavior is core functionality from the Block module that's enforcing its data model. Each time you place a block, you're creating a unique Block entity that has a theme property tied to it. Thus, the mainnavigation block entity can't simultaneously be used on the default theme as well as theme3.

This is why Drupal defaults to generating ${theme_machine_name}_${block_machine_name} so the user doesn't have to think about it.


How do I change the base URL to use a more user-friendly domain?

You could create a Drupal alias as follows:

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

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

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

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

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


You can use jQuery Multi module which provide functionality to load multiple jquery in Drupal site.

  jQuery Multi allows you to load an extra version of the jQuery library in parallel to Drupal's version, without conflicting with Drupal's version. You can then choose any
  JavaScript library or files to use the new version of jQuery. No
  need to alter packaged jQuery plugins!

  run a newer version of jQuery in parallel to Drupal's without    interfering with things that use the default jQuery version, using
  jQuery's built in noConflict mode
  use the newer version of jQuery in custom scripts using the provided    alias
  configure specific libraries to use the newer jQuery
  configure any JS file in the system to load using the newer jQuery


For "parent" node, how do I show list of child nodes related by child field of type "Entity Reference"?

Thanks in part to @Niall Murphy's response, I was able to find a Drupal Community Doc that got me further along, though I had to do some translation from Drupal-7 terminology to Drupal-8 terminology before I reached a solution/answer. I've updated the Doc accordingly so you can read it for the solution/answer details.

Note: No additional modules were needed. I was able to do everything with freshly-installed out-of-the-box Drupal 8.0.2 functionality.


I have no idea why the maintainers haven't fixed this glaring oversight, but after hours searching and testing I figured his out and want to share.

Total results for views with multiple displays and pager

Inline with the view, drop this in view header:

<?php
print $view->query->pager->total_items;
?>

Outside the view:

<?php
$view = views_get_view('MY_VIEW_NAME');
$view->set_display('MY_DISPLAY'); // like 'block_1'
$view->execute();
print $view->query->pager->total_items;
?>

That freakin' easy...


Global search/replace on special characters accidentally taken in on an import ( â€™ )

You can try the scanner module to do these sitewide text search and replace operations but it may be a little tricky because of the characters you're replacing (they look like MS smart quotes?)

Better solution might be to rollback your import, rexport your CSV with a UTF-8 character set and try your import again.


Commerce Product listing View with category contextual filter, How to show items of (selected term and its child terms)

There are two approaches to solving this problem:

Use the product_taxonomy_filter module to add the missing filter. Note that the performance impact of this module is unclear (it adds a subquery since it can't rely on the taxonomy_index table).
Build your product catalog the recommended way, using Search API. The official docs cover this use case (via adding the "Index hierarchy") processor.


Url aliases/global redirect not being used in Custom Blocks

Found the answer.  Sort of surprising since I don't think it's uncommon to run Drupal from a subdirectory (im my case, "drupal") and hide the fact through .htaccess rewrites.  Anyhow, doing exactly that breaks Global Redirect.

The fix is unfortunately hacking the module until it's addressed.  See here:
http://drupal.org/node/976214


The contextual filter needed to be linked to Content entity referenced from field_personstory_person_id) Content: Nid and then it worked.

This does not help me understand how to pass the argument from the panel, though ;)


Scrolling in chrome shears text and elements

Try to add -webkit-transform: translateZ(0); to your fixed elements.


how to empty the first select option with form api?

Add a empty value setting to the form array:

$form[$key] = array(
  ..
  '#empty_value' => '',
  ..
);

That will add a - Select - option to the list that will not pass a required validation if the user leaves it on - Select -.

Don't add an empty value to the #options array '' => t('Please select'). That will still pass a required validation if the user leaves that option selected.


naming convention for .tpl.php in drupal 7 for custom content type

Overriding node.tpl.php for a specific content type is very simple.  The naming convention is node--machinename.tpl.php. For machinename, use the machine name of the content type with underscores replaced by hyphens. You can inspect the machine name if you navigate to Administration → Structure → Content types.  If you just want the override to apply to a single node (as opposed to all nodes of this content type), add the path replacing all slashes in the path with a double hyphen.

Provided you want to override the node template for path test, your template should be named:

node--basepage--test.tpl.php

No extra actions are required. Just create it (usually by copying it from the theme's node.tpl.php to node--basepage.tpl.php), modify it and place it inside the themes templates/folder.

Provided you want to override page template page.tpl.php based on the content type being displayed, the naming convention is the same, but you need to do some extra legwork:

Open the template.php file in your theme for editing.
Look for a function called THEME_preprocess_page (replace THEME with the theme's name).
If this function already exists, you will need to add your code to it inside an if-statement that goes at the end of this function, just before the closing bracket  Otherwise, if it doesn't exist, you'll need to create a new function.

This is how the function should look like:

function THEME_preprocess_page(&$vars) {
  // If the function already exists, just leave the code here intact, and add
  // the three lines below to the end.
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

Now, copy the theme's page.tpl.php to a file named page--machinename.tpl.php and place it inside the themes templates/folder.

Provided you want to override the page template  for path test, your template should be named:

page--basepage--test.tpl.php

for Drupal 7.


Add class that surrounds all tables (or any other node,field etc...) using preprocess template?

you can override views-view-table.tpl.php template to achieve this.

Like :

<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>
   <?php if (!empty($title) || !empty($caption)) : ?>

<?php print $caption . $title; ?>

  <?php endif; ?>
  <?php if (!empty($header)) : ?>

        <?php foreach ($header as $field => $label): ?>
          <th <?php if ($header_classes[$field]) { print 'class="'. $header_classes[$field] . '" '; } ?>>
            <?php print $label; ?>

        <?php endforeach; ?>

  <?php endif; ?>

    <?php foreach ($rows as $row_count => $row): ?>
      <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
        <?php foreach ($row as $field => $content): ?>
          <td <?php if ($field_classes[$field][$row_count]) { print 'class="'. $field_classes[$field][$row_count] . '" '; } ?><?php print drupal_attributes($field_attributes[$field][$row_count]); ?>>
            <?php print $content; ?>

        <?php endforeach; ?>

    <?php endforeach; ?>

Get a look for override views template here

For other tables Override theme_table and change its return statement Like:

return '
'.$output.'
';


How to quickly create multiple Drupal 7 features?

You can use the Drush features add/export commands (add was removed in the latest version of Features (rc1)).  As there have been a lot of changes recently with features rc1 and drush 5.0, the exact commands will differ depending on your setup, but drush help will list the features commands and drush help fe will show you the details (in this case, how to export [e.g., create] a feature).

If you really needed to create a lot of features, you could script Drush (either extend Drush itself or run Drush via bash script, etc.)


Yes that is correct, the errors are saying entity_test_type and locales_source do not exists. Try searching for them with PHPMyAdmin or any other DB viewer and you will very likely not find them. So yes, somehow those tables got deleted or possibly renamed?

  Help! How can I fix this?

If they got deleted, you have the following options:

A) Disable and uninstall those modules, then enable them again and they should create the missing tables.

B) Revert back to a DB backup where those tables exist, then export the 2 tables only. Now revert back to your latest DB backup where they are missing and just import those 2 tables.

C) Manually re-create those tables with the proper column names


Open Id Connect SSO on cross platform sites

The OpenID Connect module is designed only to login your users when they use the login button(s).

The SSO module will propagate the logins to your Drupal sites, if you are using Drupal as authentication provider/clients.

If you are using a cross-platform setup, you will have to create your own auto-login propagation in a custom module. Depending on your authentication provider, you may (or not) be able to define post-login actions to use. Or you may yourself utilize post-login hooks of your Drupal site to trigger logins on the remaining sites.

Unfortunately, the solution you are asking for not only depends heavily on your authentication provider, but also is far out of the scope of Drupal Answers.


What variable is responsible for the default admin bar on top of every default Drupal theme?

It's stored in $page_bottom...you should also output $page_top to make sure you have a complete page:

</head>
<body>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>


D8 Views Template Suggestions Being Ignored

A template name suggestion has to start with the theme hook and two underscores. You find the theme hook in the twig debug output, in this case views-exposed-form:

$suggestions[] = 'views_exposed_form__' . $mycustomdata;


So Simple. just paste it

$user_fields = user_load($user->uid);
$user_fields->field_points['und'][0]['value'] = $points;
user_save($user_fields);


Callback to Drupal site after curl call to 3rd party site doesn't resume authenticated session if more than 120 seconds elapsed since authentication

A callback from a credit card processing site to your Drupal server should never have the same session as the paying customer. If it does, then you have a problem.
But I'm not sure that's what you're saying - you are vague when you talk about session ID. If you mean that the paying customer's session ID shouldn't change when your server sends the payment information to the credit card processing site then receives the response, then you are correct. But why even mention credit card processing and posting back in this case, as it's not very relevant? If the paying customer's session ID changes, then you need to investigate how the session ID is invalidated and what your session timeout is. Perhaps your callback is invalidating a cache tag that forces a new session to be generated for that user.


Try using renderer service instead as rendeer and drupal_render() is deprecated, e.g.

\Drupal::service('renderer')->renderRoot($content);

  Renders final HTML given a structured array tree.


Have To Recreate Feature After Rollback - Features Module

It turns out the feature is in 'overridden' state

drush fl name_on_feature

If I did revert

drush fr name_on_feature

Then that solved my problem but i am still puzzled. If I drop tables, then how is it detecting 'overridden' state. Does Features module has some local file cache used for handling states?..just thinking loud. To my understanding revert updates database according to the code of the feature.


Implementing hook_form_alter() alone is not enough. The View query will check the taxonomy by term id. Now you just altered it to title in the dropdown values.

You would then need to implement hook_views_query_alter() and alter the query condition as your need. Assuming you have a taxonomy term field field_cat, your view query will have the following similar condition - field_data_field_cat.field_cat_tid = {the_selected_value}

Now, you need to check it against taxonomy_term_data.name:

function MYMODULE_views_query_alter(&$view, &$query){
    if($view->name == 'your_view_name'){
        $conditions = $query->where[1]['conditions'];
        $k = 0;
        foreach($conditions as $cnd){
            if($cnd['field'] == 'field_data_field_cat.field_cat_tid'){
                $replaced_condition = array(
                    'field' => 'taxonomy_term_data_field_data_field_cat.name',
                    'value' => $cnd['value'],
                    'operator' => $cnd['operator']
                );
                $query->where[1]['conditions'][$k] = $replaced_condition;
                break;
            }
            $k++;
        }
    }
}

Hope this helps.


How do I get the translated title of a node?

You should load the translated entity, and get the title from that.

$translated_entity = $entity->getTranslation('en');
$translated_title = $translated_entity->getTitle();

You can get the current entity language using $entity->get('langcode')->value;, and as @4k4 says, you should check that a translation exists using $entity->hasTranslation($langcode);.


Is there a way to display SCALD image and have it link to outside website: Drupal 7

I gave the module Image Link Formatter a try, but I could not get it to work and I filed this bug report: https://www.drupal.org/project/image_link_formatter/issues/2970937

Instead I used the Linked Field module:https://www.drupal.org/project/linked_field plus Token: https://www.drupal.org/project/token.

To make this work, I have a content type that uses a SCALD Atom for the image field and I have a separate field to add a URL.  Under the Manage Display tab for your content type, go to the Link to Content section (click on the gear wheel) and opt to Link this Field. You will be presented with a Destination field.

You'll need to browse the available tokens to find the destination field that pertains to your content type.  Make sure to use the one with dashes instead of underscores and in the case of a URL, you'll need to append the token with :url.  Mine looked like this:

[node:field-default-content-link-url:url]

If the field on my content type is populated, it links to the website.  If it is empty, the image is not formatted as a link.


CAS module - disabling auto login / want nonpersistent cookies - deleted when browser closes

Not sure if this would meet your requirements but look at the require_login module.  I'v done CAS and Shib authenticated sites using this module.

My solution was to have an excluded custom login page that was set up as the user login path in this module.  This page generally had the welcome / security blurb and a button that linked to the Authentication agent (CAS / Shib).  I seem to remember having to custom craft this to include the page to return to after login.

The part that might not work for you is that if a user had authenticated via CAS on another site and then came to this site, they did not see this page but where autologged into Drupal.. after all CAS, Shib, and the like are Single Sign On solution.. ;)

This might work for you with the Gateway option off.

Otherwise you might have to look at creating a custom event subscriber that handles the CAS authentication.  E.g., if a user logs in and they are a CAS user, send them to the login page.  Set some flag on the login page and then allow them to "login".


how to create expire flagged node after custom time

You need the rules module along with its Rules Scheduler module. The flags module is well integrated with rules and you can do a lot of stuff with this combination.

A simplified instruction how to achieve your desired functionality:

Enable rules, rules scheduler.
In admin/config/workflow/rules/components crete an actions component which, when triggered by the scheduler, will unflag your node. You will have to set its inbound variable to 'content' (usage: parameter). Action will be unflagging your node.
In admin/config/workflow/rules create a rule which will start the scheduler (the triggering event should be 'node has been flagged' and the action should be 'schedule component evaluation' which passes the node id (content) to your component.

This way whenever a certain node is flagged with a certain flag, a new scheduler entry is added and when its expired, your node gets unflagged. Bear in mind the entry is only evaluated on cron run, so you will be hitting that cron button many times during debugging.

You can find rules tutorials all over the place, but not so much scheduler tutorials.
This comment is a good starter.