Migrate creating custom fields I have 2 server rather than the localhost ex: staging & development.
And I am creating custom fields on the local machine and those fields from
different types [entity reference - user reference - image - ...etc]
so how to migrate creating these fields on the other servers[staging & development] and even [production server] from inside the code, instead of repeating the same process from the Admin of Drupal-7 every time on different server!?

You might want to have a look to the Features module.

By creating a feature, you can export entities, fields and many other settings created using the admin UI to a module, that then can be installed to your target site.

You may also consider creating a dedicated custom module that holds all your database-stored settings and pre-populated entities/content (e.g. basic taxonomy vocabularies, user roles, permission assignments, ...) set by code instead of the admin UI.

Every setting you can do within the admin UI can be done by code as well, using according hooks, function calls or database queries. And each time you extend your site and settings, you will add an according update hook to keep sites up-to-date that have your module running already. (Staging / Production)

This approach is considerably difficult for beginners to work with, but once you know how to do it, it's worth the efforts. (Speaking from experience.)

Last but not least, you can always synchronize entire databases. For example using the Backup & Migrate module or manual database exports/imports. You just need to make sure to do your settings on a clean version without test data. This approach starts becoming messy once your site is live, but may suit your needs while you still create it.

In Drupal 8, I'd suggest configuration export/import instead, which makes the entire process of configuration management a whole lot easier.


Views relationship using taxonomy I have two content types (document and employee) and both have a reference to a taxonomy (language). I would like to build a view showing all documents that a employee could read. In other words, both of them have the same language.

I've try to relate the employee and the taxonomy; however, I can't see a way to relate the taxonomy to the document. I've also tried to relate directly the employee language ID to the document language ID, with no success.

Do you have any idea to solve this problem?

I thing you need to sort the node using the taxonomy fields. Is it so then use the steps:

Add realtionship in views

Then add 'taxonomy terms on node'

Then go to filter then you can find all the terms there


How to display a custom block in a view? I created a custom block "Share". This one is not displayed on any page.

I installed the "Twig Tweak" module.

How to display a custom block in a view ?

If you want to add it to the header or the footer, edit your view, and in the middle column next to header or footer click add and then select Rendered entity - Custom block

When adding the block, just use the block ID (that can be found in the block's URL - in the image you uploaded your block ID would be 103)

Make sure these options are checked / filled in.


Redirect with POST and parameters in a controller I want to redirect to a url (Sermepa/Redsys) with POST and some form parameters in a Controller. The process is I submit a form that collect some data, and when the user submit this form, it redirect to my controller. In this controller I prepare the post data and then I want to redirect to bank gateway with POST.
<?php

namespace Drupal\mymodule_sermepa_redsys\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\mymodule_sermepa_redsys\RedsysAPI;
use Drupal\node\NodeInterface;

/**
 * Class DoPaymentController.
 */
class DoPaymentController extends ControllerBase {

  public function doPayment(NodeInterface $node = null) {

    if ($node!==null) {

      $redsys = new RedsysAPI();
      $config = \Drupal::config('sermepa_redsys.settings');

      // Completamos los datos para la petición
      $redsys->setParameter("DS_MERCHANT_AMOUNT", $config->get('ammount'));
      $redsys->setParameter("DS_MERCHANT_ORDER", $node->id());
      $redsys->setParameter("DS_MERCHANT_MERCHANTCODE", $config->get('merchant_code'));
      $redsys->setParameter("DS_MERCHANT_CURRENCY", $config->get('currency'));
      $redsys->setParameter("DS_MERCHANT_TRANSACTIONTYPE", $config->get('transaction_type'));
      $redsys->setParameter("DS_MERCHANT_TERMINAL", $config->get('terminal'));
      $redsys->setParameter("DS_MERCHANT_MERCHANTURL", $config->get('url'));
      $redsys->setParameter("DS_MERCHANT_URLOK", $config->get('merchant_url_ok'));
      $redsys->setParameter("DS_MERCHANT_URLKO", $config->get('merchant_url_ko'));

      $version= $config->get('version');
      $kc = $config->get('merchant_password');

      $params = $redsys->createMerchantParameters();
      $signature = $redsys->createMerchantSignature($kc);

      $post_data['Ds_SignatureVersion'] = $version;
      $post_data['Ds_MerchantParameters'] = $params;
      $post_data['Ds_Signature'] = $signature;

      $client = \Drupal::httpClient();
      $response = $client->request('POST', $config->get('url_webservice'), ['form_params' => $post_data]);
      return $response;

    }
    else {
      return [
        '#markup' => t('Error. No nid'),
      ];
    }
  }
}

What I expected is after sumbit the form, controller was called, and then the user was redirected to bank payment page.
The form is a "create node" of a custom content type. In my .module file I have added a custom submit:
function mymodule_form_node_mycustomtype_form_alter(&$form, FormStateInterface &$form_state) {
...
$form['actions']['submit']['#submit'][]  = '_mycustom_form_submit';
}

function _mycustom_form_submit(array &$form, FormStateInterface $form_state) {
    $url = Url::fromRoute('mymodule_sermepa_redsys.payment_controller_doPayment');
    $url->setRouteParameters(array('node' => $form_state->getValue('nid')));
    $form_state->setRedirectUrl($url);
}

My routing file:
mymodule_sermepa_redsys.payment_controller_doPayment:
  path: '/doPayment/{node}'
  defaults:
    _controller: '\Drupal\mymodule_sermepa_redsys\Controller\DoPaymentController::doPayment'
    _title: 'Do Payment'
  requirements:
    _permission: 'access content'

Note: The class RedsysAPI is a helper class to prepare the data to POST, but It's irrelevant in the context of this question.

You can't redirect with Post properties. You can only do a request, which you've done. The $response you've created in the controller will contain the results of your HTTP request to the remote service. You'll have to retrieve the the relevant data from that object, and do something with it. You are currently returning that from your function. $response is a Psr\Http\Message\ResponseInterface object. If you just return this, your controller will not know what to do with it.


Accidentally deleted uploaded files, now I can't remove missing files from node So I made a bit of an mistake and accidentally deleted some uploaded files via FTP. In the backend, when I try to remove the missing files from the node itself, it presents an error "The website encountered an unexpected error. Please try again later." Upon checking the error logs it says:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] => 1384489746 ) in drupal_write_record() (line 7166 of /Applications/MAMP/htdocs/fung/includes/common.inc).

Any ideas how to fix this?

You should upload via FTP a file with the same filename and path as the deleted file. The file content doesn't matter.

Then edit the node and delete the file from the node editor.


Temporarily disable all modules for troubleshooting I have a bizarre error going on in the Drupal admin and I want to disable all modules to test if any of them are causing the problem. I have dozens of enabled and dozens of disabled modules. I can go through the process of writing down each module and its status, then manually disabling and re-enabling. However, that seems pretty tedious. Is there a better way to temporarily disable all modules without having to manually remember and tick them on/off?

You can collect the machine names of all the enabled modules with the drush pm-list --type=Module --status=enabled --pipe > enabled.txt command.

And then iterate through the list do disable:

drush -y dis $(<enabled.txt)

or enable

drush -y en $(<enabled.txt)

them.


Change product price before putting it on a cart Overview:

I have a website that only sells one product. It has a $0.00 Price.

I have this custom form when sent, it will give the product id (e.g.) to the uc_cart_add_item

uc_cart_add_item($nid, $qty = 1, $data = NULL, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE);

Well, technically it goes to the cart with a price of $0.00.

So the question here is, how can I alter the product price before sending it to the cart?

I saw this function from other website that this one alters the product price

hook_uc_product_alter(&$node)

Unfortunately, it doesn't seem to work or something.

I've searched for some questions

Ubercart alter product price when product added to cart

Even this one, but it's on Drupal Commerce not on Ubercart

programmically change price of product

Any help would be appreciated.

You want to alter the cart item, not the product node. hook_uc_cart_alter is what you're looking for.

function MYMODULE_uc_cart_alter(&$items) {
  foreach($items as $key => $item) { //Set all items to $3.50
    $item->price = 3.50;
  }
}


leaflet get direction Hi is it possible to make/install "a get direction button" which will use the [widget - Geocode from another field] and then show the route?

Maybe this link helps you: http://drupalminion.blogspot.com.au/2013/05/how-to-add-driving-directions-link-to.html

I am looking for the same answer


Site won't display after logging in OK, so I have a weird one that I have never seen before. I have about 15 Drupal sites setup locally that are all running fine. I am attempting to setup a new one that I am setting up from a Drush archive dump that was given to me. I have used this method plenty of times in the past.

I am on a Windows 7 box and am running WAMP server v2.5. Apache v2.4.9, PHP5.5.12 and MySQl 5.6.17. So, I create the database, create the entry in my HOSTS file and create the entry in my Apache httpd-vhosts.conf file. I tweak my settings.php file with the correct dB connection info and attempt to go to the site and the site comes up just fine.

I can view the homepage. If I attempt to go to something like local.mysite.com/admin, I get "Access Denied" as expected. However, if I go to local.mysite.com/user and then login with user 1, I get "This site can’t be reached - ERR_CONNECTION_RESET" in Chrome and then I continue to get that even if I attempt to go to the homepage again. If I go to local.mysite.com/user/logout, it will successfully log me out and then the home page comes up again just fine. It only won't display when I login.

I thought maybe it was the temp directory, but I used Drush to check what that was set at and made sure I had that on my local box. I checked the PHP logs, the Apache logs and the MySQl logs and nothing jumped out at me as out of the ordinary. I also checked to make sure the .htaccess files were in place. I also checked this in multiple browsers and got the same result. I also tried changing the name of the site from local.mysite.com to "foo" in my HOSTS file and in Apache and restarted Apache and the site comes up, but it does the same exact thing. The site cant be reached as soon as I login. I'm at a total loss here.

Couple things you can try.

Clear the session table, as it sounds like there may be some preexisting sessions left over from the archive.
Clear the cache tables as well
Make sure the folders/files are owned by the Apache user


Tracking user contact form submissions How can I track user contact form submissions on Drupal 6?

I'm thinking of something similar to the webform results table but for user contact forms.

If not something that complex, then just simple statistics on contact form use, e.g. "UserX received 10 emails this month."

I'm pretty sure I'll have to create my own module which is fine, I just need to know how to go about this.

Do you have any ideas?

What you could try is:

use hook_mail_alter() to check when mails have been send and store the information you need in a special table of your own module. Maybe the information in the $message is enough for you. If not you could try:

hook_fom_alter() to add an extra submit-handler to the contact form like this:

$form['#submit'][] = 'my_custom_submit_handler';

Inside my_custom_submit_handler($form, &$form_state) you should have full access to the form fields and store everything you need like you want to.


Custom Token + foreach not functionnal I want create a custom token to retrieve all parents with a specific type of a menu item.

I have created a custom module with that :

function mytoken_token_info() {
    $info['tokens']['node']['team_url'] = array(
        'name' => t('Team URL'),
        'description' => t('Returns a custom url for team and team pages'),
    );
    return $info;
}
function mytoken_tokens($type, $tokens, array $data = array(), array $options = array()) {
    $replacements = array();
    if ($type == 'node' && !empty($data['node'])) {
        $node = $data['node'];
        $path = 'node/'.$node->nid;
        $mlid = db_select('menu_links' , 'ml')
        ->condition('ml.link_path' , $path)
        ->fields('ml' , array('mlid'))
        ->execute()
        ->fetchField();
        $menuParents = token_menu_link_load_all_parents($mlid);
        foreach ($menuParents as $itemParent_mlid => $original) {
                $item = menu_link_load($itemParent_mlid);
                $item_path = $item['link_path'];
                $item_path_args = explode('/', $item_path);
                $item_id = $item_path_args[1];
                $item_entity = entity_load('node', array($item_id));
                $item_type = $item_entity[$item_id]->type;
                $item_title = pathauto_cleanstring($item_entity[$item_id]->title);
                if ($item_type == 'type1' or $item_type =='type2') {
                    $replacements[$tokens['team_url'] = $item_title;
                    break;
                }
        }

}
return $replacements;

}

With this code I get only one parent. The foreach seems not functionnal.

if I use $replacements[$original] = $item_title I get no parent.

Can you help me ?

Thanks.

P.S. If i use a similar code in my node template I get all parent items. It's ok in my node.

I have rewrited my code from an example of a custom token:

$replacements = array();

if ($type == 'node' && !empty($data['node'])) {

    $node = $data['node'];

    foreach ($tokens as $name => $original) {

        switch ($name) {

            case 'team_url':

            $path = 'node/'.$node->nid;

            $mlid = db_select('menu_links' , 'ml')
            ->condition('ml.link_path' , $path)
            ->fields('ml' , array('mlid'))
            ->execute()
            ->fetchField();

            $menuParents = token_menu_link_load_all_parents($mlid);

            foreach ($menuParents as $itemParent_mlid => $itemParent_title) {
                $item = menu_link_load($itemParent_mlid);
                $item_path = $item['link_path'];
                $item_path_args = explode('/', $item_path);
                $item_id = $item_path_args[1];
                $item_entity = entity_load('node', array($item_id));
                $item_type = $item_entity[$item_id]->type;
                if ($item_type == 'team' or $item_type == 'page_team') {
                    $itemParent[]= pathauto_cleanstring($itemParent_title);
                }
            }

            $itemsParents = implode("/", $itemParent);
            $replacements[$original] = $itemsParents;

        }
    }

}

return $replacements;

It's functionnal. Perhaps we can simplify this code and get a cleanly syntax.


Change sort order of commerce orders In admin of the Commerce module, Orders (Store > Store Orders) are currently being sorted by 'order number' and I think "alphabetically" because they have a strange order like so:
842, 754...287, 146, 1370

How would I go about changing the default view to sort by 'Created' date to ensure that the latest orders are always at the top of the list?

Visit next: Administration » Structure » Views » Orders (admin/structure/views/view/commerce_orders/edit/admin_page)

FORMAT > Format:Table | Settings
Click Settings. In radios buttons select own default order field.


Exposing sort breaks order In my view I am exposing two sort options in the following order:
Date > Newest First
Title > A-Z

When both sort options are exposed it will correctly display the nodes sorted by date but will randomly sort the nodes by title. So for example titles starting with a R will appear for nodes which have titles starting with a D. When I turn off exposing the Title sort it will display correctly. First sorted by date and correctly sorted from A to Z. But I do need to expose the Title sort. So what am I missing? Or is it just a bug?

My Views settings

Sort settings date field

Sort settings title field

It's not a bug. Node creation date is stored with hours, minutes and seconds. If you are sorting by creation time, only nodes created in the very same second will ever use secondary sort criteria - Unless you will set granularity:


Template hierarchy like Wordpress I am new to Drupal. Is there any template hierarchy structure to output different section of durpla like node, page, vocabulary, block etc. If so how can we use that.

E.g. In WordPress we have a template hierarchy to output page, posts, category, custom post etc.

Yes, Drupal has a modular, hierarchical template system. Each of the components you mentioned can be themed individually. The main html template includes the page template, which includes other templates, that include other templates, and on it goes.

See About overriding themable output for the how/what/why.


Common Custom PHP Library: Drupal 8 and Stand-alone Shell Scripts I have a Drupal 8 custom module that contains 5K of php in 10 classes.  This code is production ready for the launch of a new website.

I also have code that runs from non-drush shell scripts.  One example is the creation and distribution of a newsletter that runs from crontab.  This pulls data from Drupal and creates a multi-part (html & plain text) email in multiple languages.

There is overlap between these two sets of code that would like to eliminate.  How can I create a single php code library that can be shared between Drupal 8 and also used in standalone shell scripts?

There seems to be two approaches here:

(1) place all code in the custom module and Include it in shell scripts

I understand how to accomplish the custom module part of this.  I don't know how to do the include into a stand-alone shell script from the Drupal directory.

(2) place all code in an external library and Include it in the custom module, the shell scripts and anywhere else I need it

This approach seems to have more flexibility.  It addresses my original issue of sharing code between Drupal custom modules and stand-along scripts.  It also allows the same code to be used in multiple projects -- separate Drupal 8 installs perhaps for difference clients.

How can I pull a custom php library (not on packalist.org) into my Drupal custom module?  If this is possible, I will likely move most/all of my Drupal and Shell Script PHP code to a common external library that is under github change control.

It's possible to pull custom php libraries into your project with composer. You'll need to define the repository in the repositories section. Checkout handling private packages and repositories in composer's documentation. It's really fairly easy. If you have a single github repo you can include the repository info like below:

"repositories": [
    {"type": "composer", "url": "https://packages.drupal.org/8"},
    {"type": "vcs", "url": "https://github.com/myorg/mypackage"}
]

You should include a composer.json file in your repo as you'd probably expect. Here is a simple one to get you started:

    "name": "myorg/mypackage",
    "description": "My Package is the greatest!",
    "license": "proprietary",

    "autoload": {
        "psr-4": {"Myorg\\Mypackage\\": "src/"}
    }

Now your code can by placed in scr/Myclass.php with a

namespace Myorg\Mypackage;

Class Myclass {}

Choosing which version to pull in is a little but confusing. When you include a branch you need to prefix the branch nave with dev-, e.g. dev-master for the master branch. Otherwise, you can create tags and pull them in by their name, e.g. 1.0.0, etc. I've used this technique successfully with bitbucket.

Some inclusion examples where your composer.json in your repo defines your package name as myorg/mypackage:

// This will pull whichever branch is marked as the "default" branch in your repo
composer require myorg/mypackage

// This will pull the "develop" branch
composer require myorg/mypackage:dev-develop

// This will pull in the "2.1.3" tag
composer require myorg/mypackage:2.1.3

// You can also use "^" and "~" with tags
composer require myorg/mypackage:^2.1.0

You can tell composer where to put your package by adding a new item to the extra.installer-paths section of composer.json. For example, if you want to install your package to web/modules/custom add a line like:

"extra": {
    "installer-paths": {
        "web/modules/custom/{$name}": ["vendor:myorg"],
        ...
        "web/core": ["type:drupal-core"],
        ...
    }
}

If your repos are private, you may have some issues pulling your repo as a package. I've worked around this issue by using my ssh key for access to the repos and making sure anyone who runs composer require myorg/mypackage also uses the ssh key method.

An alternate technique is to create a zip release of your package and include it as a repository as the chosen module's README explains.


Is it possible to divide two columns using the the query builder? Is it possible to divide two columns using the the query builder?

Like: $query -> fields('A', array('valsA') / 'B', array('valsB'));

For complex expressions you can use the addExpression() method, e.g.

$query->addExpression('A.valsA / B.valsB', 'alias');


Change workbench moderation state with VBO does not work properly I have two workbench moderation states draft and publihsed
When I try to change the state of a node from draft to published using VBO's set moderation state action, It actually republish the published revision. While it should publish the draft revision.

In the screenshot, it move the draft to published with revision 4 and that should be the published revision. But it is pointing to the revision 3 that this is the published revision.
Is there any workaround for this issue?
Any hint where to look?

The patch in https://www.drupal.org/project/workbench_moderation/issues/3160301#comment-13758806 fixes the issue.


Custom views filter to select roles I have scoured the internet trying to find information on how to achieve this functionality to no avail. I am hoping I can get an answer here.

I have a content type called 'Server' on my website. One of the fields on 'Server' is an 'Access Role' field, which is an entity reference of user roles.

When a new piece of content is made, the author selects one (or multiple roles) that have access to this piece of content (The author can't be granted the 'manage roles' permission, so they can't use the standard 'permissions' options available when creating content).

I have a view setup (that is a REST EXPORT of type key_auth. When a user accesses the endpoint using their auth key, the view should return a list of server content that matches ONLY if one of the users roles is in the access roles field for the piece of content. I can't seem to find out how to achieve this using views and filters.

As an example;

Server 1
Access Roles: Developer, Testing

Server 2
Access Roles: Administrator

The user accessing the endpoint does not have the administrator role, but does have the Testing role. When the user accesses the endpoint, only 'Server 1' should return for them, since that's the only server that matches one of their roles. If more servers matched, those servers would be displayed, too.

I have the access roles setup, and the view setup to connect the api key to the correct user, but can't figure out how to set the filter up to match user roles to one of the possible access roles on the server content.

Is there somebody that could offer me some assistance?

EDIT: I think this is actually wrong: Views doesn't evaluate hook_node_access() for performance reasons. How to filter a view according to nodes permissions

It's going to be difficult for Views to model the relationships needed for this correctly, because Roles are configuration entities in Drupal 8 (as opposed to content entities).

You may be going about this the wrong way, though. Views already respects entity access control, preventing entities from showing in results if the current user doesn't have permission to access those entities. You haven't made those access control rules explicit to Drupal yet, which is why they don't get automatically filtered out in Views. But you could implement hook_node_access() to formally describe those access permission rules to Drupal.

Here's the API documentation example: https://api.drupal.org/api/drupal/core!modules!node!node.api.php/function/hook_node_access/8.8.x

Your implementation would look something like this:

<?php

function MYMODULE_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  if ($op == 'view' && $node->hasField('field_roles')) {
    $node_roles = array_column($node->field_roles->getValue(), 'target_id');
    $user_roles = $account->getRoles();
    if (array_intersect($node_roles, $user_roles)) {
      return \Drupal\Core\Access\AccessResult::allowed();
    }
    else {
      return \Drupal\Core\Access\AccessResult::forbidden();
    }
  }
  return \Drupal\Core\Access\AccessResult::neutral();
}


How can I purge a specific URL from varnish cache without making a curl request? I'm programmatically updating images and keeping the same file name. I flush the image styles for the image when I do this, but I'm running into an issue where my image styles aren't being regenerated because the old image style is being loaded from varnish when the attempt to regenerate them is made. I've read (in a couple places, including this related Drupal answer How can I clear the Varnish cache?) that I can clear the cache with a curl request:

curl -X PURGE -H "Host: domain.com" http://127.0.0.1/test.html

How can I use an existing method in the Purge or Acquia Purge modules to clear the cache for a given url, specifically an image style url?

Note: I've seen the purge_queuer_url module, but that is not a viable solution for me.

Update: I don't even think this was happening. I can't reproduce the varnish cache hits at all so I must've been wrong about that. I found a bug elsewhere with the focal_point module that was causing my image styles to not be recreated properly.

Here's some code that I use to clear Acquia varish via the Purge / Acquia purge modules when a pdf with the same name is uploaded.  You could expand on this to clear the styles cache as well.

/**
 * Implements hook_entity_update().
 */
function my_module_entity_update(EntityInterface $entity) {
  $type = $entity->getEntityTypeId();
  if ($type != 'file') {
    return;
  }
  // \Drupal::logger('my_module')->debug("File entity found");
  $purgeInvalidationFactory = \Drupal::service('purge.invalidation.factory');
  $purgeQueuers = \Drupal::service('purge.queuers');
  $purgeQueue = \Drupal::service('purge.queue');

  $queuer = $purgeQueuers->get('coretags');
  // Invalidate cache tags so all pages that have the file get banned from varnish
  // Also invalidate the file's url.
  $invalidations = [
      $purgeInvalidationFactory->get('tag', 'file:' . $entity->id()),
      $purgeInvalidationFactory->get('url', file_create_url($entity->getFileUri())),
  ];

  $purgeQueue->add($queuer, $invalidations);
}


Views contextual filters for NULL value How do I use a contextual filter to find all nodes with field_abc that has a null value?

1) Views PHP Filter is good to go when you have 'not that many' query results in total. The thing is that it loads node's object and it's not the best choice if you opt for better performance, but still it's okay for quick views filters creation.

2) Create new Computed field and store any flag (1/0 is quite enough) as its value. The flag itself will indicate if the field X has any content and then it can be used by Views for filtering.


PathProcessorEntityResourceBC Class not found error after updating to Drupal 8.4 After updating to Drupal 8.4 I now have an error in my browser when trying to load my Drupal site:

Error: Class '\Drupal\rest\PathProcessor\PathProcessorEntityResourceBC' not found in Drupal\Component\DependencyInjection\Container->createService() (line 262 of core/lib/Drupal/Component/DependencyInjection/Container.php)

If I execute a drush or drupal console command the error is the same but with more of a stacktrace.

I upgraded to Drush 9 which simplifies the error a bit more:

Service 'rest.path_processor_entity_resource_bc' for consumer 'path_processor_manager' does not implement Drupal\Core\PathProcessor\InboundPathProcessorInterface.

It looks like I have some dependency missing somewhere. I'm not sure how to track it down.

I have tried "composer install", "composer update", and removing the vendor directory and re-installing the composer packages but nothing has worked yet.

Has anyone had this error or know how to get the missing PathProcessorEntityResourceBC class?

I have fixed the error by replacing the 'core' directory with the latest 8.4.0 version. I then checked the git log and differences which were found in these files:

modified:   core/scripts/drupal.sh
modified:   core/scripts/password-hash.sh
modified:   core/scripts/rebuild_token_calculator.sh
modified:   core/scripts/run-tests.sh
modified:   core/scripts/update-countries.sh

The differences were similar for each file, for example:

--git a/core/scripts/update-countries.sh b/core/scripts/update-countries.sh

I'm not sure exactly how and why this fixed the missing class, but it seems like I have some differences between the 2 versions of the site.

I then added the changes into git on a new branch and after switching between the 2 branches I don't get the fatal error any more (with or without the updated files).

It's possible that something was cached and as my site and drush was broken I was unable to clear the cache, refreshing the core files must have fixed it.


JavaScript files not loading The JavaScript files for my theme aren't loading. What am I missing?

My theme.info.yml:

name: theme
type: theme
description: Custom theme.
core: 8.x
base theme: classy
version: 8.x-1.0
libraries:
  - theme/global-styling
#stylesheets-remove:
#  - '@classy/css/components/tabs.css'
#  - core/assets/vendor/normalize-css/normalize.css
regions:
  logo: 'Logo'
  navigation: 'Navigation'
  slider: 'Slider'
  content: Content  # the content region is required
  contact: 'Contact (Content Top)'
  testimonials: 'Testimonials'
  call-to-action: 'Call To Action'
  footer_logo: 'Footer logo'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'
  footer_copyright: 'Footer Copyright'
regions_hidden:
  - sidebar_first

My theme.libraries.yml:

global-styling:
  version: 1.x
  css:
    theme:
      css/animate.css: {}
      css/bootstrap.css: {}
      css/et-line-icons.css: {}
      css/font-awesome.min.css: {}
      css/extralayers.css: {}
      css/settings.css: {}
      css/magnific-popup.css: {}
      css/owl.carousel.css: {}
      css/owl.transitions.css: {}
      css/full-slider.css: {}
      css/text-effect.css: {}
      css/menu-hamburger.css: {}
      css/style.css: {}
      css/responsive.css: {}
      css/custom.css: {}
      //vjs.zencdn.net/5.8.8/video-js.css: { type: external }
  js:
    //vjs.zencdn.net/ie8/1.1.2/videojs-ie8.min.js: { type: external, minified: true }
    js/modernizr.js: {}
    js/bootstrap.js: {}
    js/bootstrap-hover-dropdown.js: {}
    js/jquery.easing.1.3.js: {}
    js/skrollr.min.js: {}
    js/smooth-scroll.js: {}
    js/jquery.appear.js: {}
    js/wow.min.js: {}
    js/page-scroll.js: {}
    js/jquery.easypiechart.js: {}
    js/jquery.parallax-1.1.3.js: {}
    js/jquery.isotope.min.js: {}
    js/owl.carousel.min.js: {}
    js/jquery.magnific-popup.min.js: {}
    js/popup-gallery.js: {}
    js/text-effect.js: {}
    js/jquery.tools.min.js: {}
    js/jquery.revolution.js: {}
    js/counter.js: {}
    js/jquery.countTo.js: {}
    js/jquery.fitvids.js: {}
    js/imagesloaded.pkgd.min.js: {}
    js/classie.js: {}
    js/hamburger-menu.js: {}
    js/main.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

Try this : Add this code in .info.yml

libraries:
        - 'theme/global-styling'
        - 'theme/global-scripting'

And include the CSS and JS the libraries.yml file like below.Include styles and scripts seprately.

 global-styling:
    css:
      theme:
       css/style.css: {}

 global-scripting:
    css:
      theme:
         js/script.js: {}


Customise Recent Content block to show only 1 content type I need to customise the 'Recent Content' block to show only 1 content type (i.e pages or articles).

This doesn't seem to be possible with the block settings so I presume that I need to clone and/or edit this block to restrict the content it shows?

A custom View (as a block) would solve your problem.

You can make it replicate the functionality of the 'Recent Content' block but minus the the Content Type that you wish not to include.


hook_theme, custom data, passing to custom TPL file I am having trouble passing custom data through theme() to a custom callback and passing the data through to a tpl file. Here is my code:

hook_theme:

function satb_schedule_theme() {
  return array(
    'satb_schedule_brackets' => array(
      'render element' => 'bracket',
      'variables' => array('bracket' => array()),
      'template' => 'satb_schedule_brackets',
      'path' => drupal_get_path('module', 'satb_schedule') . '/templates',
    )
  );
}

hook_menu item:

$items['tournaments/%/%/schedule/winner-bracket'] = array(
    'title' => 'Winner Bracket',
    'description' => 'View the winner brackets for this tournament.',
    'page callback' => 'satb_schedule_generate_bracket',
    'page arguments' => array(1, 2, '0'),
    'weight' => -16,
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('view tournament brackets'),
  );

hook_menu item callback (satb_schedule_generate_bracket):

function satb_schedule_generate_bracket($nid, $product_id, $bracket_type) {
  $schedule = new SATBScheduleDisplay(array('nid' => $nid, 'product_id' => $product_id));
  return $schedule->getTournamentBracket($bracket_type);
}

This function generates an array of data. Inside of the method, data is gathered and returned through theme(), like so:

$output = theme('satb_schedule_brackets', array('bracket' => $brackets));
return $output;

In the template.php, I have this to modify and add variables for the template:

function satb_preprocess_satb_schedule_brackets($variables) {
  $brackets = $variables['bracket'];

  foreach($brackets as $key => $round) {
    switch ($key) {
      case 3:
        $classes = array('round', 'quarterfinal');
        $round_title = t('Quarter Finals');
        break;
      case 2:
        $classes = array('round', 'semifinal');
        $round_title = t('Semi-Finals');
        break;
      case 1:
        $classes = array('round', 'final');
        $round_title = t('Final');
        break;
      default:
        $classes = array('round');
        $round_title = t('Round @round_number', array('@round_number' => $key));
        break;
    }

    $variables['bracket'][$key]['data'] = array('classes' => implode(' ', $classes), 'round-title' => $round_title);
  }

  $vars['bracket'] = $variables['bracket'];
  $vars['tournament_title'] = 'Just a test';
  return $vars;
}

My custom tpl is loaded (I can see the static HTML in there as a test and print static vars) however, my modifications don't seem to get passed to the template.

For example, if I do print $tournament_name;, its null. If I do print $bracket['tournament_title']- it appears, but I don't want to access variables like that because that's messy, and, it should respect the vars I am adding to the vars array.

What am I missing here? The classes and titles I am adding in the preprocess are also missing in the $bracket element in the TPL. The $vars has them, but the TPL does not.

Doh. $variables is passed by reference. I always forget this in template.php:

function satb_preprocess_satb_schedule_brackets(&$variables) {


How do I override clone block? I cloned the Block property view and renamed it Block portfolio.

When I change the content type, the Block property and Block portfolio still use the same content type.

How do I override it?

When you're configuring the filter, at the top, select For This block (override) or This Page (override)

Example:


Drupal Form Checkbox having different name and id (of my choice) As drupal assigns title as both id and name to a form element.

$form['wrapper'][$unitClean.'_container'][$unitClean.'_cb'] = array(
                '#type' =>'checkbox',
                '#title' => t($unit),
                );

I need name and id to be different for checkboxes, textboxes and select lists. Anybody with any idea?

I want to do this because I am populating multiple form elements in a loop, need to manipulate them using JS (in form of groups) and then process them on next page.

Found answer,
done like this:

$form['wrapper'][$unitClean.'_container'][$unitClean.'_cb'] = array(
                '#type' =>'checkbox',
                '#title' => t($unit),
                '#attributes' => array(
                  'name' => $unitClean.'_name',
                  'id' => $unitClean.'_id',
                  'onclick' => 'checkall();'
                    )
                );


Monthly sales reports I need to create a monthly sales report in Drupal. The report should contain products/services sold during last month, quantity and the price. Sales persons have to enter monthly the information in the report. I am thinking to create the products as a content type Product with the field Month, Name, Quantity, Price, Sales person (Author).

If I display in Views the Content Type - Product, how can Users (Sales role) enter the Quantities? How to control that the quantities for all products are set? How to limit it to 1 Report per month? How to identify which users have entered the report and which users didn't do it?

I would appreciate very much if you can guide me how to better achieve this monthly reporting objective!

This seems like a perfect usecase for the Forena module. Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports (and/or charts). Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS ... And there are quite some reasons for considering Forena.

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links, and experiment a bit with some of its demo samples.

Some of its features that I think will help to answer this question (and which only is a matter of minutes to deliver the features you're looking for):

Create a report about "products/services sold during last month, quantity and the price." Have a look at the "Northwind database" demo videos, which I tink are pretty close to what you're looking for. Such as these videos:

How to create a report/graph about Shipping summary (fast forward to about 4:15 if you're not interested in the SQL query prototyping part of it).
How to create Crosstab Tables and (related) charts (fast forward to about 2:15 if you're not interested in the SQL query prototyping part of it).
Various other Video demos and tutorials created in an earlier (7.x-3.x) release of Forena (which are mostly still accurate, but only using outdated Forena screens that have been enhanced in the 7.x-4.x version).

If you don't want to implement some validation about "... that the quantities for all products are set?" ... (or cannot do so for whatever reason), then you could create a report to find all cases that violate (as an alternative).
To create a report about "identify which users have entered the report and which users didn't do it?"

Disclosure: I'm a co-maintainer of Forena.


Need rule: if Giftcard used to pay order, then skip PayPal, if Giftcard not used then goto PayPal My Drupal Commerce site allows customers to buy vouchers (each voucher is a product), which are paid for using PayPal and which gives them a code. The system then allows them to book classes, using a voucher rather than PayPal. Using commerce giftcard module, customers fill out the voucher (giftcard) code in the giftcard pane at checkout. Apply the voucher and the the total to pay goes to zero and the voucher value is reduced by the cost of the class. Checkout says no payment is required, all is well, class is booked.

However, when no voucher code is entered checkout still says no payment is required, even though the total is not zero. In this case I need a rule checking the total of the order, allowing no-pay-progress if total is zero (i.e. gift card has been applied) else require PayPal (i.e giftcard code has not been applied and total is > zero).And that is where I get stuck. Any help on how to formulate this rule much appreciated.

Payment methods are enabled via Rules. One of the Rules conditions is to check the balance of an order. Have you not tried adding this to your rule that enables PayPal as a payment method?


Render page with theme wrapper from custom controller? I've created a page layout using panels in the Drupal admin UI (page_machine_id). I'm trying to load that page into a custom controller like so and render one of the variants (Drupal 8):

public function profile() {
    $page = \Drupal\page_manager\Entity\Page::load('page_machine_id');
    $variants = $page->getVariants();
    $pageVariant = end($variants);
    $viewer = new \Drupal\page_manager\Entity\PageVariantViewBuilder();
    $pageArray = $viewer->view($pageVariant);
    return new Response(render($pageArray));
}

This renders the page content correctly, but does not include the theme wrapper around it and I can't figure out how to get the theme to show.

Thanks.

solution is

    return $pageArray;

Adding Response bypasses Drupals rendering.


How to add payment method field to the footer of an order summary view? I can add payment method field to fields in my view, but it is not available to add in footer.

Why is it? How could I add it this field in the footer view?

Note:  My view is an order summary view, showing all line items, I would like to display below of the lite items, what was the payment method used. I think the footer would be a nice place to put this information, but I don't see the token for it. I can see the token to add in fields but not in footer.

Why is it? Fields are meant to go in the fields section and not in the footer.

An easy workaround solution is to create an attachment view contenting only the field in question and attach it after your current view.

To do this, in your view, click on +Add and select attachment.

Then you should have a cloned copy of your original view. When you add or remove fields make sure you select at top This attachment (override). If you do not do this, your changes will affect all of your views.

In your first/original view: In footer click on Add and select Global: View area. Select your attachment view and check mark the inherit contextual filters box.

  Note: If your first/original view is a Master, when you add the attachment, you will not have the For:
  Display box,  such as in the last picture (on step 3).

  If that is the case, all your views will get an attachment, including the
  attachment. Therefore, you will have to switch to the attachment view and
  select "This attachment (override)" and remove the footer from the attachment.


hook_form_alter() on a view exposed filter form I am trying to add a disable attribute in a field using the hook_form_id_alter function.  I created a module and built the function

function disableIncentiveform_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-drive-clean-incentive-search-page-1'){
    $form['field_new_used']['#attributes']['disabled'] = 'disabled';
  }
}

However, this does not add an attribute to the form.

I know there used to be a hook_form_views_exposed_form_alter function in D7 but I can't find anything specific for D8.  Is there a correct way to do this?

This code should do it:

function MYMODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $view_ids = ['YOUR_VIEW_ID'];
  $view = $form_state->getStorage('view');
  if ($form_id == 'views_exposed_form' && in_array($view['view']->id(), $view_ids)) {
    $form['field_new_used']['#attributes']['disabled'] = 'disabled';
  }
}


How do I create a field template or template override for a specific display mode? Because in the Drupal 7 Commerce module, the fields, 'sku,' 'title,' and 'status' aren't editable by Display Suite field wrappers, I'm unable to edit the field wrapper via the Drupal front end, I need to use a template to update "commerce-product-title.tpl.php" with an H2 wrapper, but I only need this for the 'product_full' view mode on all products. Is there a way to target this field in this display mode only with a template or theme function?

Fields

You have to add the theme hook suggestion yourself, first. For fields it's just the same as for nodes. Simply place the following snippet in your theme's template.php or your module's *.module file and replace MYTHEME/MYMODULE with your theme's or module's machine name.

Now copy the /modules/field/theme/field.tpl.php file over to your theme's /templates directory and name it along one of the following patterns:

field--field-name--view-mode.tpl.php
field--field-name--bundle--view-mode.tpl.php

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_field(&$variables) {

  $view_mode = $variables['element']['#view_mode'];
  $field_name = $variables['element']['#field_name'];
  $bundle = $variables['element']['#bundle'];

  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $view_mode;
  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $bundle . '__' . $view_mode;
}

Commerce Product title

For Commerce' product titles though things are a little bit different, as you don't get the view mode or the referencing entity from within its preprocess hook. But you can simply use your own logic to add your template suggestions. For example a pattern in the URL alias or something like that.

Then copy the /sites/all/modules/contrib/commerce/modules/product/theme/commerce-product-title.tpl.php file over to you theme's /templates directory and rename it along your desired pattern.

commerce-product-title--foo.tpl.php

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_commerce_product_title(&$variables) {

  // The following suggestion only gets added when there's
  // a certain keyword at the third position in the URL alias
  // as in /myproducts/overview/foo/myproduct.
  if (arg(2, drupal_get_path_alias()) === 'foo') {
    $variables['theme_hook_suggestions'][] = $variables['theme_hook_original'] . '__' . 'foo';
  }
}


What path should I give so that contextual filter works I am creating on view page for which works like archive and I am doing it for the terms that are used in Blog(I am using blog module).

I have followed this tutorial.

But problem is when I give CONTEXTUAL FILTERS to year+month, and after that If I open my URL example.com/blog/201502 it is showing me 404 page.

Where am I lacking ?

NOTE: It is working fine in preview which are under view.

Some snap shot regarding this:

If I put path something like blog/% then It is showing me all the blog post and I want to have Terms.

If I click on January 2015 then It should give me following result :

Please help me.I have tried a lot.Let me know if more information is required.

Instead of creating a node view create a taxonomy view

In that provide two relationships

Taxonomy term: Content with term
Taxonomy term: Content using {Name of the taxonomy field in the content type}*
Add a contextual filter of the type Content : Title Use the first relationship for the contextual filter, Make necessary changes in the more option such as change to lover case turn space to dashes etc
Add the required fields from the content with the relationship set to 2)

You are good to go.

EDIT : As per the discussion There was another need to also show the nodes under a term and its sub terms.

Create a view of the type content.

Add the required fields

Add a contextual filter of the type Content: Has taxonomy term ID (with depth) and select the depth a value as deep as the hierarchy you have in the taxonomy.

Now when you pass the term id as the input it would show all the nodes under that taxonomy term including the child nodes

If you wish to change the url to have the term name instead of the term ID Do the following.

In view give the path as taxonomy/term/% this will override the default taxonomy path.

Install Pathauto Module this depends on Tokens module so have to install that as well.

In Configuration -> URL aliases you have a tab called Patters

Set the pattern of the "TAXONOMY TERM PATHS" to what you would like it to be. Make sure that the last value is [term:name] so if you want the path to be category/carrot you should give it as category/[term:name]

If you have already added the taxonomy terms then you would need to do the "BULK UPDATE" which is again a tab on the URL Alias page.

Now when you visit the page category/termname you will see all the nodes under the term including the child terms


How to add a hierarchical taxonomy to a content type I have a hierarchical taxonomy like below

In Drupal 7 there was a module name hierarchical select to achieve this. But it is no longer support for Drupal 8. Is there another way to add this to a content type, so a user can select an element from this taxonomy. I need that to be hierarchical.

You can take a look on Simple hierarchical select and Client-side hierarchical select module.

Simple hierarchical select

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.

  This module has been inspired by Hierarchical select but is much
  simpler (hence the name ;) ).

Client-side hierarchical select

  A simple client-side hierarchical select widget for taxonomy terms.

  The widget provides three settings:

    Force selection of deepest level (If checked the user will be forced
    to select terms from the deepest level.)

    Parent (Allows to select a parent term to use only a subtree of a
    vocabulary for this field.)

    Labels per hierarchy-level


Create a view to list contents according to taxonomy & content type I have vocabulary with these terms

Countries

India
USA
UK
...

Sports

Soccer
Hockey
Cricket
....

And I have following content types

News
Events
Article
...

I need to create view that will show listing of content(s) as per the following path

for example:

/sports/soccer/news

/countries/india/news

or

/news/sports/soccer

/news/countries/india

Thanks for the help

You can create views pages with next pathes:

"taxonomy/term/%/news"

"taxonomy/term/%/events"

"taxonomy/term/%/articles"

Install Pathauto module and add "[term:parent]/[term:name]" pattern for URL alias for your vocabulary, and install Sub-pathauto module that will apply aliases for URL like this 'taxonomy/term/1/news'


Large Binlogs Generated When Reverting Features We're using features to manage content types and field groups, and every code update, when we perform a features-revert to push out the latest CTs and field group changes, we get a huge amount of data written to our binlogs -- a gig about every 10 mins:

-rw-rw----. 1 mysql mysql 1073759569 Aug  1 02:31 mysql-bin.000138
-rw-rw----. 1 mysql mysql 1073766800 Aug  1 02:42 mysql-bin.000139
-rw-rw----. 1 mysql mysql 1074139941 Aug  1 02:50 mysql-bin.000140
-rw-rw----. 1 mysql mysql 1073954804 Aug  1 02:59 mysql-bin.000141

which quickly locks up our MySQL servers.

What might be causing the large amount of data to be written? What can we be doing on the MySQL side and the Drupal side to keep this in check?

DISCLAIMER : Not a Drupal Expert, Just a MySQL DBA

There are really two classes of answers for this question

STANDALONE DB SERVER
MASTER/SLAVE REPLICATION

STANDALONE DB SERVER

If you know you are going to perform a feature-revert, the simplest thing to do is this

StandAlone Method #1 : Disable Binary Logs

STEP 01) Run SET GLOBAL SQL_LOG_BIN = 0;
STEP 02) Run your feature-revert
STEP 03) Run SET GLOBAL SQL_LOG_BIN = 1;

This will disable binary logging during the feature revert and reenable afterwards

StandAlone Method #2 : Erase All Binary Logs Except the Last One

You could crontab a job that runs this:

PURGE BINARY LOGS BEFORE NOW();

StandAlone Method #3 : Erase All Binary Logs

You could crontab a job that runs this:

RESET MASTER;

MASTER/SLAVE REPLICATION

In standard MySQL Master/Slave Replication, a Master Has Binary Logging Active and the Slave Does Not. You cannot just disable binary logging like you would for a StandAlone DB Server because you need to replicate the DB Changes of the feature-revert.

Here is what to do stem the rise of binary logs and relay logs

Replication Master (Manage Binary Logs)

At the completion of a feature-revert, which binary logs are safe to remove so that MySQL Replication can still work and remain intact?

Here is what you do:

STEP 01) Run SHOW SLAVE STATUS\G On the Slave.

For example:

mysql> show slave status\G
*************************** 1. row ***************************
             Slave_IO_State: Waiting for master to send event
                Master_Host: 10.64.97.249
                Master_User: replicant
                Master_Port: 3306
              Connect_Retry: 60
            Master_Log_File: mysql-bin.000658
        Read_Master_Log_Pos: 799061333
             Relay_Log_File: relay-bin.003861
              Relay_Log_Pos: 47059
      Relay_Master_Log_File: mysql-bin.000658
           Slave_IO_Running: Yes
          Slave_SQL_Running: Yes
            Replicate_Do_DB:
        Replicate_Ignore_DB:
         Replicate_Do_Table:
     Replicate_Ignore_Table:
    Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
                 Last_Errno: 0
                 Last_Error:
               Skip_Counter: 0
        Exec_Master_Log_Pos: 799061333
            Relay_Log_Space: 47059
            Until_Condition: None
             Until_Log_File:
              Until_Log_Pos: 0
         Master_SSL_Allowed: No
         Master_SSL_CA_File:
         Master_SSL_CA_Path:
            Master_SSL_Cert:
          Master_SSL_Cipher:
             Master_SSL_Key:
      Seconds_Behind_Master: 0
1 row in set (0.00 sec)

STEP 02) Get binary log from Relay_Master_Log_File

Field #10 of SHOW SLAVE STATUS\G
That would be mysql-bin.000658

STEP 03) On the Master, Run PURGE BINARY LOGS TO 'mysql-bin.000658';

Replication Slave (Manage Relay Logs)

To force a Slave to Throttle the amount of Relay Logs to Just 2GB, add this to the Slave's my.cnf

[mysqld]
relay_log_space_limit=2G

and restart mysql on the Slave. When a Relay Log is fully processed it is automatically deleted and makes room for the next Relay Log.

EPILOGUE

You should make sure you have this set in /etc/my.cnf on the StandAlone DB Server or Master

[mysqld]
expire_logs_days = 3;

and restart mysql. This will make sure all binary logs older that 3 days are automatically deleted.

If you are curious and want to know what runs in a feature-revert You could

Look through source code of the feature-revert module
take the binary logs and dump the contents in plain text SQL

Run the following:

mysqlbinlog mysql-bin.000138 mysql-bin.000139 mysql-bin.000140 mysql-bin.000141 > Revert.sql
less Revert.sql

UPDATE 2012-08-09 12:40 EDT

If you are concerned with point-in-time recovery, you must decide how many days worth of binary logs you are willing to keep.

Here is a scenario: Say you want to be able to revert back up to 7 days ago. You would have to setup the following:

STEP 01) Have the Slave maintain its set of Binary Logs with an expiration of 7 days

Add this to /etc/my.cnf on the Slave

[mysqld]
log-bin=mysql-bin
expire_logs_days=7

STEP 02) service mysql restart

STEP 03) Perform a midnight Backups on the Slave as follows

STOP SLAVE;
FLUSH LOGS;
mysqldump on the Slave
START SLAVE;

STEP 04) Delete backups older than 14 days

Once you have Steps 3 and 4 automated, you must let mysql rotate the binary logs on the Slave. You should not manually delete the binary logs on the Slave. Keep in mind that point-in-time recovery is not automatic. It is rigorous manual process.

Would you like a description of a point-in-time recovery ??? Here we go...

Let's say you have the following

It's August 9, 2012 12:11 PM
run mysqldumps on the Slave every night at midnight
each backup is named by date Backup_99999999.sql in /backups
and you have the following list of binary logs on the Slave

_

-rw-rw---- 1 mysql mysql 1073742269 Aug  2 11:22 mysql-bin.001789
-rw-rw---- 1 mysql mysql 1073762807 Aug  2 16:22 mysql-bin.001790
-rw-rw---- 1 mysql mysql 1073742048 Aug  2 21:28 mysql-bin.001791
-rw-rw---- 1 mysql mysql 1073741969 Aug  3 06:34 mysql-bin.001792
-rw-rw---- 1 mysql mysql 1073741954 Aug  3 11:20 mysql-bin.001793
-rw-rw---- 1 mysql mysql 1073742182 Aug  3 16:19 mysql-bin.001794
-rw-rw---- 1 mysql mysql 1073742228 Aug  3 21:37 mysql-bin.001795
-rw-rw---- 1 mysql mysql 1073753003 Aug  4 06:32 mysql-bin.001796
-rw-rw---- 1 mysql mysql 1073742100 Aug  4 13:18 mysql-bin.001797
-rw-rw---- 1 mysql mysql 1073741891 Aug  4 18:56 mysql-bin.001798
-rw-rw---- 1 mysql mysql 1073742424 Aug  5 06:12 mysql-bin.001799
-rw-rw---- 1 mysql mysql 1073742017 Aug  5 18:35 mysql-bin.001800
-rw-rw---- 1 mysql mysql 1073741952 Aug  6 05:27 mysql-bin.001801
-rw-rw---- 1 mysql mysql 1073757571 Aug  6 13:00 mysql-bin.001802
-rw-rw---- 1 mysql mysql 1073742172 Aug  6 17:35 mysql-bin.001803
-rw-rw---- 1 mysql mysql 1073742067 Aug  7 00:35 mysql-bin.001804
-rw-rw---- 1 mysql mysql 1073777487 Aug  7 10:45 mysql-bin.001805
-rw-rw---- 1 mysql mysql 1073791986 Aug  7 15:51 mysql-bin.001806
-rw-rw---- 1 mysql mysql 1073742035 Aug  7 20:37 mysql-bin.001807
-rw-rw---- 1 mysql mysql 1073741978 Aug  8 05:28 mysql-bin.001808
-rw-rw---- 1 mysql mysql 1073742217 Aug  8 10:30 mysql-bin.001809
-rw-rw---- 1 mysql mysql 1073742422 Aug  8 14:41 mysql-bin.001810
-rw-rw---- 1 mysql mysql 1073743447 Aug  8 18:47 mysql-bin.001811
-rw-rw---- 1 mysql mysql 1073742241 Aug  9 00:36 mysql-bin.001812
-rw-rw---- 1 mysql mysql 1073741985 Aug  9 08:45 mysql-bin.001813
-rw-rw---- 1 mysql mysql  743967477 Aug  9 12:10 mysql-bin.001814

You want to reload the Master going back to August 5, 2012 02:30 PM

Here are you steps

STEP 01) Take all binary logs that encompass August 5, 2012 from 12:00AM to 2:30PM. This would be binlogs mysql-bin.001799 and mysql-bin.001800. These are used because

PRINCIPLE : the first write of a binlog is also the last write of the previous binlog

the last write to mysql-bin.001798 is Aug 4 18:56 (6:56PM) 2012-08-04 18:56:00
the first write to mysql-bin.001799 is Aug 4 18:56 (6:56PM) 2012-08-04 18:56:00
the last write to mysql-bin.001799 is Aug 5 06:12 (6:12AM) 2012-08-05 06:12:00
the first write to mysql-bin.001800 is Aug 5 06:12 (6:12AM) 2012-08-05 06:12:00
the last write to mysql-bin.001800 is Aug 5 18:35 (6:35PM) 2012-08-05 18:35:00

The range 2012-08-04 18:56:00 to 2012-08-05 18:35:00 is the narrowest range that surround 2012-08-05 00:00:00 to 2012-08-05 14:30:00. This is why binlogs mysql-bin.001799 and mysql-bin.001800 are the correct choices

STEP 02) Generate all the SQL that ran August 5, 2012 from 12:00AM to 2:30PM

mysqlbinlog --start-datetime="2012-08-05 00:00:00" --stop-datetime="2012-08-05 14:30:00" mysql-bin.001799 mysql-bin.001800 > ForwardChanges.sql

STEP 03) Make a copy of the August 5, 2012 midnight backup to PITR.sql

cp /backups/Backup_20120805.sql PITR.sql

STEP 04) Append ForwardChanges.sql to PITR.sql

cat ForwardChanges.sql >> PITR.sql

STEP 05) Load PITR.sql into the Master

mysql -h IPAddressOfMaster -u ... -p... < PITR.sql

When the script is done, the database will be in the state it was as of August 5, 2012 2:30PM

Pretty easy, huh ???


Help with adding different stylesheet to one specific page in Drupal 7 using the template.php I am trying to apply a CSS style (games.css) to page--type--games.tpl.php. I am using Drupal 7, and I have created a new content type called "games."

So far, my code works for pulling up the page--type--games.tpl.php, but it has been unsuccessful in applying the CSS stylesheet. This is my current version of the code.

/**
 * Add javascript files for front-page jquery slideshow.
 */
if (drupal_is_front_page()) {
  drupal_add_js(drupal_get_path('theme', 'bluemasters') . '/js/bluemasters.js');
}

function bluemasters_preprocess_page(&$variables, $hook) {
  //some other stuff
  if (isset($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__type__'. $variables['node']->type;
    $variables['theme_hook_suggestions'][] = "page__node__" . $variables['node']->nid;
  }

  if (drupal_get_path_alias("node/{$variables['#node']->nid}") == 'games') {
    drupal_add_css(drupal_get_path('theme', 'bluemasters') . "/games.css");
  }
}

drupal_get_path_alias("node/{$variables['#node']->nid}") will be equal to "games" only in the case "games" is the path alias for the node being shown.

If you just want to verify the content type of the node being shown is "games," then you need to use code similar to the following one:

if ($variables['node']->type == 'games') {
  drupal_add_css(drupal_get_path('theme', 'bluemasters') . "/games.css");
}

To notice that a page preprocess function is called also for pages that are not associated to nodes; the function should first verify if it gets a node object, before to access it.
The complete code of the preprocess function should be like the following:

function bluemasters_preprocess_page(&$variables, $hook) {
  if (!empty($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__type__'. $variables['node']->type;
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->nid;

    if ($variables['node']->type == 'games') {
      drupal_add_css(drupal_get_path('theme', 'bluemasters') . "/games.css");
    }
  }
}


How to make dynamic google map in block? I want to make block with two links that lead to different gmaps position. Also gmaps is in that block.
So, block haves address text with two location and by clicking on that location i want that gmaps change the position of marker without reloading all page. So it is need to be dynamic block. Any help?

you could start by creating a custom module if you want , there's plenty of tutorials on the drupal website to help you get started then , in the block template add the js you need to create that map with the coordinates you want  . or using views , like in this post
 hope it helps


How can I add {% if %} for a field name? What would be the correct way to write an {% if %}  "field_name" "is", in Drupal 8 Twig files?
I would like to add a CSS style specifically to one field and I believe this will achieve that.

Here is my current code within Twig file:

{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}

  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

  {% else %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
  {% endif %}

{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}

    {% if multiple %}

    {% endif %}

{% endif %}

You copied field.html.twig to a new file, field--field-additional-text.html.twig. After clearing the cache, Drupal will only use this new file for that field only. Now you do not need logic in either template.

So you now can make changes, for example:

{% for item in items %}

{{ item.content }}

{% endfor %}

^ This means, for every item in this field (single or multiple values), print each value wrapped in this div, with this class. However, within a field template, you cannot output different fields as one, the sole purpose of a field template is to render the current field.

Read up on theming Drupal fields for more information.


/current/ date range contextual filter I have a view /widgets with a couple of optional contextual filters of type "Has taxonomy term converted to ID", so the url can look like this:

/widgets/blue
/widgets/big
/widgets/small/green

And so on.

But there should also be a "current" contextual filter on the date field defined as such:

Currently, we used exposed date filters as such:

But for "current" widgets, my urls look like this:

/widgets/blue/small?field_date_value_op=<%3D&field_date_value%5Bvalue%5D%5Bdate%5D=2013-05-17&field_date_value2_op=>%3D&field_date_value2%5Bvalue%5D%5Bdate%5D=2013-05-17

How to make:

/widgets/blue/small/current do a filtering like field_date_value<=today && field_date_value2>=today ?
/widgets/past do a filtering like field_date_value2<today
/widgets/future to field_date_value>today

I decided to create 3 sub-pages with normal filters, /widgets/all /widgets/past /widgets/current and /widgets/future.


Updating taxonomy vocabularies with Rules? I'm wondering if there's a way to add/edit/delete Taxonomy terms in a Rule with Drupal 7? I haven't found any way to define an action that will let me do that.

Usecase: I'm trying to use Rules to maintain a vocabulary of usernames of a certain role, so when a user's role is updated I add/remove their username.

Try the rules action "Set data value."  If the user includes a taxonomy reference field, you should be able to add or remove it this way.

Alternatives:
I'm not sure what you intend to use the vocabulary of usernames for, but it is straightforward to use the views module to generate a list of users by role.

Alternately, I have been using the flag module-- the latest Drupal 7 beta features rules integration-- to automatically flag users upon adding or removing roles.  You may be able to use flags instead of a vocabulary.


Multiple Custom Modules Using Same External JS Lib (e.g. Angular) I've been pulled onto a Drupal 8 project with multiple custom modules that need to use Angular.js. What is the best way to provide the Angular files to each module?

Right now, each module references the remote Angular files hosted by googleapis.com in my-module.libraries.yml.

my-module:
  version: 1.x
  js:
    https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js: { type: external, minified: true }
    https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-sanitize.min.js { type: external, minified: true }
    js/my-module.js: {preprocess: false}
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.ui.accordion

However, I would prefer to host the Angular files locally and list them as dependencies just like jQuery.

I know I could put the Angular files in the module itself, but then each module would need its own copy.

Whatever is the proper way to do it, my goal is to host the Angular files locally and reference them from each module that depends on Angular.

The simplest way to solve this is to add a /libraries folder at the root of the Drupal project. Then create a sub-directory for each external library you are using, and reference that from your module.libraires.yml file.

For example, I created /libraries/angular/js, placed the files in there, and then referenced them by starting with a / in the code below.

my-module:
  version: 1.x
  js:
    /libraries/angular/js/angular.min.js: {}
    /libraries/angular/js/angular-sanitize.min.js: {}
    js/my-module.js: {}
  dependencies:
    - core/jquery

Now any module within the project can reference the same files.


Hook into node operation from theme template.php? I have made a new content type in Drupal 7 in Drupal Admin (not via module). What I want to do is to add a Hook on the insert and update operation. How can this be done when my node type is not created by a module?

Can this be done at all?

You want to create a custom module. Note that nothing stops you from creating content types through the user interface, it is in fact the suggested way to do so nowadays with fields and stuff (instead of using hook_node_info())

Node API Hooks contains an overview of all hooks that can be used to interact with nodes at different events like create, view, delete..


Commit doesn't show up in profile on Drupal site I submitted my first, (and very small patch) here, by following the instructions here.

It looks like the patch worked, but when I look at the Commits tab of my profile, I don't see any entries.

When using Git, I created a new branch for the issue, made the changes, and then checked in. Should I have switched back to the dev branch and checked in?

Commits submitted in the issue queue are only counted when the maintainer accepts them and credits you with the patch.  Otherwise, people could just spam useless patches through drupal.org to increase their commit counts.


Taxonomy-term based block display I'm trying to display certain blocks in taxonomy term pages and the nodes associated based on the taxonomy term itself.

Let's say I have 3 taxonomy terms: Bologna, Milan and Rome.

When I'm in Bologna taxonomy-term page I would like to display a block that show the map of Bologna, when I'm in Milan taxonomy-term page the Milan map and so on.

Context module seems to work with node associated to a particular taxonomy term (for example, I'm able to display Milan map block in every node associated with Milan taxonomy term), but doesn't work for the taxonomy page itself.

I think the trick is in Panels.
I've enabled the taxonomy-term page override but I do not know how to display blocks based on arguments.

I've used views and panels many times before but never faced this particular problem: It's a bit different that filtering with arguments particular nodes or content types.

Kropot,

Have you tried views contextual filters?

Create a block view.
Add a Contextual filters with Content: Has taxonomy term ID.
defalt value: Taxonomy Term ID from URL
Add the fields to display.
Add the filters.

Deepak


Run PHP when node and/or profile is updated? I wanted to run an external script when a user profile(2) is updated, and/or when a node is updated. I've added the code to the themes template.php, but no go.

What have I missed?

<?php

$api_script_url = "http://www.aaa.com/test/test.php";
$msg = "File updated.";

// WHen a node is updated, be it new or old, update file.
function theme_node_update($node) {
    include($api_script_url."?q=".$node->nid);
    drupal_set_message($msg, 'status');
}

// WHen user profile2 profile is updated, be it new or old, file.
function theme_profile2_update($profile) {
    include($api_script_url."?q=".$profile->uid);
    drupal_set_message($msg, 'status');
}

?>

Theming functions are the wrong place for something like that. To run some PHP code after an node or profile (thus entity) is updated you should use the Rules module or use the following hooks, hook_entity_insert, hook_entity_update


When using a view in "Unformatted list" format with inline fields, how can I most cleanly add a break between the fields? I have a view like this:

Field A (Inline)
Field B (Inline)
Field C (Inline)
Field D

I would like it to display like this:

Field A label: value Field B label: value
Field C label: value
Field D

Obviously, I need to create a break after the value for Field B.  However, what is the best way to do this?  CSS in my stylesheet?  Rewrite the HTML  for the display of Field B?  Add a "Custom text" field within the view?  It seems like there must be a simpler way...

I hardly ever work with themes so I'm at a loss of how to best address even this basic formatting issue.

EDIT: I've realized that a solution that makes the view label inline but not the whole field would also work, but I don't know how to do this...

I would say CSS is the better route because it separates your content from your layout just as CSS does with respect to HTML.  Also, if you decide to change your layout later on, CSS will most probably be easier (and more obvious) to change than some fake data in a view forcing that is forcing/hardcoding your layout.


How to apply a custom class to a .field__item in an entity reference display? I have an entity reference field with multiple values, referencing various content using a custom view mode.

I need to apply the same custom class to each (delta) row.

By default Drupal (twig?) is applying a class of .field__items to each row, but this is not specific enough, as this is also used for other fields within the view mode.

What is the best way to achieve this?

You can add classes in the twig template directly, or through a preprocess function.

Preprocess

Docs provide some patterns to follow: https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_field/8.2.x

function HOOK_preprocess_field(&$variables) {
  $element = $variables['element'];

  switch ($element['#field_name']) {
    case 'MY_FIELD_NAME':
      $delta = 0;
      while(!empty($element[$delta])) {
        $variables['items'][$delta]['attributes']->setAttribute('class', 'custom-class-name');
        $delta++;
      }

      break;
  }
}

This applied the class to the entire entity, alongside field__item.

Template

If you have twig debugging enabled, you can see quickly what's a good template name. I tested with field--node--FIELD-NAME.html.twig. Using the field template from classy for example, just add the class at the end of the list.

{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    'custom-class-name',
  ]
%}

This applied the class just to the field, not the label. But you could modify the template to print the classes elsewhere.


How do I create custom 403/404/406/503 pages in Drupal 8? I am familiar with creating node and pointing to that specific node in basic site settings. How do i create this programmatically and package in features? Twig override?

To bundle and create programatically, you would need to create a custom module and inside that module: you could create a route for each specific page. That module could also update the config that is found in the system basic settings to use your custom pages.

Using this custom page you could call a custom page.html.twig and  override with the html you need.

Here are two resources:

https://www.drupal.org/node/2116767
How do I update the configuration of a module?


Why we need hook_cron if the cron job requires a path? In drupal we have a hook_cron() which runs on cron.

But in cron job we have to specify a path, the cron will access that path and will run the code in the page callback function of that path.

So my question is that why then we need hook_cron() if we can do this by creating path using hook_menu with a page callback and use that path in the cronjob?

Can someone explain this to me?

Using hook_cron() Drupal can run all the cron tasks using a single entry point (http://your.site/cron.php) and bootstrap code that is very specific for cron tasks, different from the normal bootstrap code used from Drupal.
This simplifies handling cron tasks since only a single URL is necessary to run them, and the code that runs them is faster compared to the normal code.

If I had the need to run groups of cron tasks at different times, then I could create different cron.php files to execute those specific groups. I would not implement different routes for executing cron tasks for the same reason Drupal 7 doesn't: The code that runs the routes is more complex than the code running the cron tasks and involves more hooks being invoked.
At least that was the reason for doing so when Drupal 7 was first released. With PHP 7, that is probably not a reason enough to prefer custom bootstrapping code to a route handler. As for Drupal 8, cron tasks are executed from a controller associated with a route.

In short, normally cron.php is enough, but it is also rare to even need a different route handler/controller for each cron task modules could.


user warning: INSERT command denied to user I am not able to insert rows into a table even though I have granted permissions to the corresponding database user.

I am able to insert rows into the same table with the same user from an individual php application. But if I try to insert a row from drupal, I get the error message as follows.

user warning: INSERT command denied to user 'username'@'localhost' for table 'table_name'

I even tried changing the password of the database user and changed the settings.php of drupal to reflect the new password, but still I get the same error message. I am able to run the SELECT queries successfully but not INSERT queries. What might be the problem here? Any help is appreciated. Thanks.

That doesn't really make sense. Drupal is just a PHP application; if you're using exactly the same connection details in Drupal as you are in your stand-alone PHP application, and that works, it's only logical that your Drupal connection will work too.

You've obviously checked that the username and password are correct, but have you checked the Drupal is connecting to the server from localhost? That would be the only other possible difference. If Drupal is connecting from a remote machine then you'll need to grant specific privileges to the user for that specific location.

The easiest way to see what you've already got is to run a SHOW GRANTS query on the database in question. That will show you something like this:

Grants for username@localhost
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER ON *.* TO 'username'@'localhost' IDENTIFIED BY PASSWORD '*xxxxxxxxxxxxx'

Plus a few more more rows more than likely.

Check through those rows to make doubly sure that there is a grant for INSERT for the database user AND the location that the Drupal website is connecting from.

EDIT

You could maybe get around the error using drupal_write_record():

$record = new stdClass;
$record->col1 = 'something';
$record->col2 = 'something';
$record->col3 = 'something';

drupal_write_record('table_name', $record);

But that really shouldn't make any difference


Can I make a content type for a single user's blog entries? I would like site announcements to appear in a block on the sidebar.

I can do that with a content type, but Admin has a blog and I was wondering if/how to automatically give all blog posts of Admin (and no other user) be of a content type

I think what you want is to create a view. Show all blog entries by 'user 1' only in your block.
Create a view: Under your display(on the left) select block from the drop down. Give it
a name, say Test1.
Under Fields add Node:Title and Node:Body.
In the filters add Node-type:Blog, Node:Published:Yes and User:Name=Admin

Then goto Site building->Blocks and you should see Test1:Viewname. Enable that block and configure it to show it on the page where you'd like.

Hope that helps.


How can I filter search results? I need to restrict certain search results from showing up for users and limit them to a specific content-type. This can be either the main search or some sort of custom search since it's the only type of post that will need to be searched on the site.

You have a few options. The quickest solution is to use views and take advantage of its quick and easy, powerful filtering capabilities. Views is a must in using drupal. If I was you and you are expecting to be heavily reliant on search then look into using search_api and views together to create some nice mashups.


Creating a filter programatically with views_get_view I have a lot of views and I want to add a filter to just one of them. This view is called soccer_news_feed and I want it to check out my custom field: field_data_field_is_score and display if it's not 1.

So in a hook_update_n I have this code:

$view = views_get_view("soccer_news_feed");

$view->add_item(
  $view->current_display,
  'filter',
  'field_data_field_is_score',
  'field_is_score_value',
  array('operator' => '<>','value' => array('value' => 1))
);

So I thought maybe this work but I get this error when I run updb:

PHP Fatal error:  Call to a member function get_option() on a non-object in /var/www/public/sites/all/modules/contrib/views/includes/view.inc on line 2450

I'm very lost on this.

The first key to enlightenment is to at error message.  It says the fatal error happened in views/includes/view.in, around line line 2450. I don't know your exact version, but in one of my Drupal 7 installs, here's what's close to line 2450:

  /**
   * Add an item with a handler to the view.
   *
   * These items may be fields, filters, sort criteria, or arguments.
   */
  function add_item($display_id, $type, $table, $field, $options = array(), $id = NULL) {
    $types = views_object_types();
    $this->set_display($display_id);

    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);

My line numbers don't match in my version, but notice the last line of the excerpt.  Best guess that $this->display[$display_id]->handler ($this is your view) is either NULL, or is not an object.

$this->display is an array of view_display objects; and $this->display($display_id) should either be a view_display, or perhaps, NULL or FALSE.

I'd recommend trying the following to debug this:

First, perhaps it's possible that $view->current_display is not initialized, or isn't what you think it is. Try substituting it with 'default', which usually works with Views.
If you look at your view's definition and know the machine ID of one of your displays for that view (say, 'page_1'), try substituting that and see if it works.
If you're using an IDE with a source debugger, this is a good time to learn to use it a bit. Views can be pretty opaque as to what it's doing under the hood, and sometimes, seeing what the data actually is in real time can save you a lot of time.

That's as much as I can suggest w/o knowing the exact version of Views you're using, but it may get you started.

Good luck, in any case.


Title showing 'Home' on Tabs I am creating a module for searching a library of books.  I have created a set of tabs on the module display page.

Search
Results
Item

The title when the Search page is selected (or default) is as I would expect "Search" however when I go to either of the other tabs (via link or a click) the title of the page is shown as "Home".  While not a major issue it doesnt look good.

I have set the 'title' attribute of the render array for each page to 'Results' and 'Item Details' respectively.  How do I force this title rather than 'Home'.

I have noticed the same behaviour for pages using 'MENU_CALLBACK'.

The page title is by default the title defined in hook_menu for the menu item. If you want to alter the title, you should use drupal_set_title.

Note: Drupal set title can't be used to late in the theming process (like template_preprocess_page), as the value for the title has already been populated at that point. Using it in the menu callback should work just fine.


Not able to alter field value/s using hook_views_pre_render or views api hook functions I have a search result page created using search api and views. My search result page is based on  this tutorial and it seems to work properly,however I need to tweak some field's output value and I used  hook_views_pre_render to try to alter the field values however I cant see my fields that I added from the views UI interface on the $view->result array  but  they are rendered on the page. All I see when I krumo($view->result) is (see attached image).
I seem to only get  entity and entity_properties array but not the fields in the array. I need to access the field to make the necessary tweaks like we have in the normal $view->result.

This is not a specific answer for your situation but I would like to advise you a better way of managing it.

Instead of rendering the views using Fields you can render each row by rendering as Content where you can choose a dedicated View mode which can be easily overridden using the standard template_preprocess_node.

This will bring a lot more flexibility in your Web application.


Views contextual filter on just ONE of the listed contenttypes I'm not sure how I can accomplish this but I hope you can tell me.
I have a view that lists 2 different contenttypes that has different filters.

Now, I want to use a contextual filter on just one of the contenttypes.

Is there any way I can accomplish this?

Best regards,

That really depends on your specific view configuration. Generally speaking, you can add validation (e.g. what content type to accept as contextual filter) and a fallback behavior (e.g. ignore argument vs. show 404), see screenshot. With these instruments you can achieve pretty much.


How to override specific row classes in a view preprocess function Have tried the following but it does not work

function THEMENAME_preprocess_views_view_unformatted(&$vars){
  $view = $vars['view'];
  if($view->name == "videos" && $view->current_display == "block_2"){
    $vars["rows"][0]["attributes"]["class"] = array_merge($vars["rows"][0]["attributes"]["class"],['testclass']);
  }
}

For Example:

function THEMENAME_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $view_name = $view->id();

  if ($view_name = 'frontpage') {
    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {
      if( in_array($id,[0]) ) { //first row only
        $attributes = $variables['rows'][$id]['attributes'];
        $attributes->removeClass('lol')->addClass('haha'); // changes "lol" to "haha"
        break;
      }
    }
  }

}


Clickable Images fields When creating new content types, I know I can have an image field, but how do I associate a URL with an image so that when you click on the image, it goes to that node or location? Is the only way to get into the code and surround the img tag with an href tag?

Welcome to stackexchange doug! :)

This is what I believe to be the most popular solution. It's good because it's fairly easy to set up, yet very flexible. You will need the Views module.

Add a textfield to the same bundle (content type) as the one holding your images.
Create a View
Add your link field to the field list, and check "Exclude from display".
Add your image field to the field list, scroll down to rewrite results, check "Output this field as a link", and add the link "token", in the "Link path" field. The list of available tokens are listed further down under "Replacement patterns". .
Save the View, and add it where you want. :)

If you want to know more about Views, you can see a video tutorial series here.


Drupal gives error to admin, anonymous users can browse pages Anonymous users can browse various pages, when logged in, it gives "The website encountered an unexpected error. Please try again later". I am using drupal 7 commerce. Before this error I installed drupal example modules and drupal commerce example modules.  THe image is attached which shows the errors.

The reason is that the error message only prints when an admin is logged in, you can disable that by going to Administer > Site configuration > Error reporting, anyway you can still fix the problem, by rebuilding your permissions, it mostly can cause by enabling permission dependent modules, like content access or something else.


Get main menu in to my search page I'm using the built in search in Drupal 7. My problem is that I need to customize the search page. Is it possible to get the search results into a panel so that I can output my main menu and a few other elements? Now My search result page is very bare.

You can customise your search-results.tpl.php by copying this file from the core search module and putting it into your theme directory. You can add your menu in where you like using code:

<div id="menu">
  <?php print theme('links__system_main_menu', array('links' => $main_menu)); ?>
</div>

Also remember to clear your cache after making changes!


Drupal 7. Custom pages for displaying data I'm juststarted with drupal and i want to create module for managing data in my custom database tables.
For example, i need to have three pages:
1) list of my subscribers
2) editing subscriber
3) adding subscriber

so, i need three pages for this:
/subscribers
/subscriber/edit/id
/subscribers/add

the question is:
do i need to create three Basic pages with such aliases in admin
and use specific templates files for each page to manage data?
or how to do it properly?

Using hook_menu() should get you the the ability to create those three pages.  Then you can use the page_callback to display the data you are looking to show. For the subscribers/id, you can use %id and then have pass the argument to the page_callback.  Using the db_query(), db_update(), db_select() functions in drupal, you'll be able to add the custom processing of the database.

If you are creating your own module you can use theme functions to decide how the page and that data will display.


drush site synchronization with aliases I configured the site aliases for the development, and staging sites. I have the <DRUPAL_HOME>/sites/default/aliases.drushrc.php aliases file with this content:

$aliases['dev'] = array(
  'root' => '/home/drupaltest',
  'uri' => 'localhost',
  'path-aliases' => array('%dump' => '/home/drupaltest/dump.sql')
);

$aliases['stage'] = array(
  'root' => '/home/drupaltest',
  'uri' => 'naftalin',
);

$aliases['all-scratch'] = array(
  'site-list' => array('@dev', '@stage'),
);

drush @dev status outputs:

  hubidubi@couscous:/home/drupaltest$ drush @dev status
       Drupal version         :  6.25
       Site URI               :  localhost
       Database driver        :  mysqli
       Database hostname      :  localhost
       Database username      :  root
       Database name          :  drupaltest
       Database               :  Connected
       Drupal bootstrap       :  Successful
       Drupal user            :  Anonymous
       Default theme          :  garland
       Administration theme   :  garland
       PHP configuration      :  /etc/php5/cli/php.ini
       Drush version          :  4.4
       Drush configuration    :
       Drush alias files      :  /home/drupaltest/sites/default/aliases.drushrc.php
       Drupal root            :  /home/drupaltest
       Site path              :  sites/default
       File directory path    :  sites/default/files

Then I tried to run drush rsync @dev @stage command to sync dev site to stage and I get:

  Could not evaluate source path @dev.

I can't figure out the problem; I think the alias file is correct.

Do you have any idea?

The drush rsync command does not bootstrap your site, so it cannot find your alias files.  Move your alias files to a global location (e.g. $HOME/.drush).

Also, since @dev and @stage are multisites with the same document root, it does not make any sense to rsync from one to the other, because they share the same files.  You might want to drush rsync @stage:%files @dev:%files.


How to translate "Sort by" region of the KickStart commerce into Russian? How to translate "Sort by" region of the KickStart commerce into Russian?

Need to completely translate KickStart commerce. Are there any ways except translating the core and searching for .po for an every single left module?

To translate "Sort by" region:

Go to the "Display products" view edit at path admin/structure/views/view/display_products/edit
In edit view page of the view you will find "Edit View Name/Description" dropdown menu on the right, from dropdown select "Translate View".

On the translate page, you will get fields to translate view stings.


Consuming RESTful web services Is there any existing Drupal 8 module (on drupal.org, GitHub or anywhere else) that would leverage Guzzle to consume JSON and/or HAL+JSON Web Services over REST?

Alternatively, is the recommended way to necessarily write a custom module leveraging the Guzzle HTTP Client that ships with Drupal core?

My end goal is to be able to create a 1:1 relationship to map fields (node, user...) with key/value pairs from RESTful web services. Then I need to be able to read, update or delete those values.

OH, just realized now, maybe I misunderstood the question 100%

This is the code which basically generates the output:

$serializer = \Drupal::service('serializer'):
$output = $serializer->serialize($entity, $format);

with $format for example being 'json'.

Luckily the serializer is symetric, so you can do the same the other way round.

$client = \Drupal::service('http_client');
$result = $client->get('http://example.com/entity/node/1', ['Accept' => 'application/json']);
$output = $result->getBody();

$serializer = \Drupal::service('serializer'):
$entity = $serializer->deserialize($output, 'Drupal\node\Entity\Node', $format);


How to load the node to print the node title, etc? I have a content type 'news' and created a seperate template for this which is node--news.html.twig. I want to load the node like Drupal 7 so I can print the node title, body and other fields as well. In Drupal 7 we load the node by node_load($nid) but is there any way to load the node in Drupal 8?

$node = \Drupal\node\Entity\Node::load($id)
$node->getTitle();

or
$nodes = \Drupal\node\Entity\Node::loadMultiple(array $ids = NULL)


Content change on hook I am working on a new content type. I created a hook that loops through a .csv file on its load, and makes a table from it.

What I want to do now is including this new table automatically in the CKEditor field, in the same form.

How can I do this? You don't have to tell me exactly what to do. Just some hints on which function to use would be appreciated.

In the hook YOUR_MODULE_form_CONTENT_TYPE_node_form_alter() fill the field (that outputs in the  ckeditor) with your HTML, like:

$form['field_body'][LANGUAGE_NONE][0]['value'] = $your_html;

You also need to make sure, that the  tags get saved, by adding these tags to allowed ones for your ckeditor!


How do you display a pane in an organic group? I'm trying to create a menu of subgroups for organic groups in d7.  I've copied the og list view and made a new view called og subgroups.  I made a pane display and configured the pane's argument to be Og group ID from context.  I also added the contextual filter: (group) OG group: Og group ID and the relationship: Group: Node group.

When I enter a group ID in the preview field of the view, it loads the appropriate menu items. When I go to the Group variant for the node template in panels, and add the pane as content in the appropriate region panels shows that the argument is group ID, but if I view the group it does not display the pane.

Am I doing something wrong?

This is what you need to do on the view content pane:

Relationships: "Group membership: Node group membership"
Contextual Filters: "(group membership) OG membership: Group gid"
Pane settings: Argument input: From context > Og group ID

On the panel contexts:

Contexts: OG group > Og group from context

Then you should add the view content pane to the panel pane and the argument should automaticaly be set to "OG membership: Group gid" > "OG group".

These are required for it to work, and I'm currently using them.


node_access check against array of node ids I am in middle of a problem where i have to check node access of current user against an array of node ids.

I have a two content types (A and B) and one contains the reference of other based on a taxonomy. A contains a user role reference fields to allow access to certain roles only. Now i want to show related contents from A on detail page of B. I have used a custom query to fetch all nodes from A somehow related to B. So code is looks like:

$related_nodes = <function_to_get_related_node>;
$result = node_load_multiple($related_nodes);

I have restricted couple of node from A content type to display only certain user roles but $result shows all node from A. Node access not worked.

In my function i have used db_select() with addTag('node_access') but it doesn't seems to be working.

So Basically i want some sort of code to check node_access on array of $related_nodes and filter before it passed to node_load_multiple function.
Could someone help me find a way? Thanks!

How about adding checking if the node has reference of current user while fetching related nodes.

So,

$related_nodes = <get_related_node>;

  // Might look Dumb
  function get_related_node($user=NULL) {
    if(is_null($user)) {
      global $user;
    }
    db_select('node','n')
     //Your existing joins
     // One more join for the user reference field, :O
     ->leftJoin('field_data_userreference','ur','ur.entity_id=n.nid')
     // your existing conditions for query.
     // One more condition for the current user as the value on the field.
     ->condition('ur.entity_id',$user->uid,'=')
    // And the execution continues.
  }

Fields mahcine names to be fixed as per the names provided. It should filter your reference nodes while fetching.