texts: Using a back reference inside a regex search string within replace filter

texts:
I’m trying to insert a programmatically generated id attribute into child elements of parsedown processed text. I'm aware that Craft’s twig replace filter incorporates preg_replace, so…

I have a regex search string that finds an HTML tag and its contents. It includes an inner back reference to make sure that the closing tag matches the opening tag (as opposed to some nested closing tag)…

(<([a-z][a-z0-9]*)\b[^>]*>(.*?)</\2>)\s+

I can use $1 inside |replace to refer to the entire tag found by the outer parentheses…

elems|replace('/(<([a-z][a-z0-9]*)\\b[^>]*>(.*?)</\\2>)\s/', '$1>,')

…and then work with the results, but the problem (I think) is the syntax for the back reference inside the search string itself.

I've tried the following without success…

elems|replace('/(<([a-z][a-z0-9]*)\\b[^>]*>(.*?)</$2>)\s/', '$1>,')
elems|replace('/(<([a-z][a-z0-9]*)\\b[^>]*>(.*?)</\\$2>)\s/', '$1>,')

Where am I going wrong? Is this even possible with preg_replace? Or is there a better way to go about injecting attributes into parsedown processed text?


texts: Set Up A Global Dashboard For A Specific User Group

texts: Is there a way to set the Dashboard up globally for a specific user group and lock it so that it can't be edited?


texts: SEOmatic not merging fields from a related entry

texts:
I have a pretty specific set up: posts get created via rss feeds and images are not attached to the specific posts, so instead in the entry template I use an image from a related entry. When I try to use the related entry's image as the SEO image and merge it with SEOmatic, it does not merge.

Has anyone ever tried doing this with SEOmatic? This is the code I'm using:

{% if craft.entries.section('episode') %}
   {% set relatedPodcastImage = craft.entries.section('podcastChannel').relatedTo(entry).albumCoverPicture.first().getUrl('large') %}
      {% set seomaticMeta = seomaticMeta | merge(
            { og:
                  {
                  title: entry.title,
          description: entry.podcastDescription,
                  image: relatedPodcastImage
                  }
            },
        { twitter:
                  {
                  title: entry.title,
                  description: entry.podcastDescription,
                  image: relatedPodcastImage
                  }
            }
      ) %}
{% endif %}


texts:
We have a problem related to the escaping of the & in the password reset URL not being escaped. This link:

http://yoursite/admin/actions/users/setpassword?code=abcd&id=1234

somehow, this arrives at our server as:

http://yoursite/admin/actions/users/setpassword?code=abcd&amp;id=1234

Then the code is abcd and a parameter called amp;id is 1234, and the error "Bad Request Param "id" doesn't exist." is thrown.

In our case, we have craft setup to send HTML emails, and have an email template like:

Click here to reset your password: {{link}}

and end up with the link http://yoursite/admin/actions/users/setpassword?code=abcd&id=1234 directly in the HTML - this is WRONG, since the & symbol has to be escaped as &amp;.

Now, we could compensate, and make our template:

Click here to reset: {{link|escape}}

Then we get correct HTML, but the plain-text version of the email is now broken.

Is there no way to have separate templates for text and html emails in craft?

How do other people solve this?


texts:
Good afternoon,

I'm new in Craft so I installed this step-by-step and I tried to install this theme: https://github.com/duezerouno/0-201

After I did everything, I can see a template error on my site that shows the next: Unexpected token "end of template" of value "" ("end of statement block" expected).

Looks like the error is on the _head.twig file and says that:

<head>
{% block head %}
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>{% if title is defined %}{{ title }} - {% endif %}{{ siteName }}     </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="home" href="{{ siteUrl }}">
<link rel="icon" href="images/favicon.png">

<link rel="stylesheet" href="/styles/app.css">

Anyone can help me with this?

Thanks in advance.


texts: How to set Home page menu as active when slug is not defined in admin panel?

texts: Is their is any way to set active class to a page when slug is not define?


texts: Set Password on Test User Account in Localhost

texts:
I'm trying to set the password for a 'test' user account on my localhost test site.  I don't have an email server to send the reset emails, so I've been using the copy URL method.
When I do go to the URL and change the password, I get a 'Page Not Found' page.  I went ahead and checked to see if the password was in fact changed, but upon successive login tests, they failed.
I was wondering what might be causing the 'Page Not Found' error?  Is there a way to set the password through a plugin, etc?

Thanks


texts: Selecting all parent users and their related children

texts:
Ok, I need a MySQL pro.

The setting:

Hundreds of users
User can be a child of other users, through relation field 'myParents'
I need a list of users, and their child(ren), related to an entry (through relation field belongsToGroups)

I don't want to use $criteria->find(), because it returns objects, which makes it terribly slow. So, I want to create a db query. What I have now, is this:

$parentsWithChildren = craft()->db->createCommand()
        ->select('u.id userId, u.firstName parentFirstName, u.lastName parentLastName, c.firstName childFirstName, c.lastName childLastName')
        ->from('users u')
        ->join('relations r', 'u.id = r.sourceId')
        ->join('relations uc', 'u.id = uc.targetId')
        ->join('usergroups_users g', 'u.id = g.userId')
        ->join('users c', 'uc.sourceId = c.id')
        ->where('r.targetId = '.$elementId)
        ->andWhere('uc.fieldId = 92')
        ->andWhere('g.groupId != 5')
        ->order('u.id')
        ->queryAll();

This return a nice list of all users, children included, but only if a user has children. In short: I also need the users without children. Any SQL guru willing to help me out, it's been a long day ;)


texts:
Does anybody know of a collection or library of Yii Modules online?

I'm trying to understand how easy they can be moved from one application to another, are we going to see something similar to the plugin store for modules within Craft? :O


texts: How to do an ajax submission to Craft Contact Form with attachments using FormData?

texts:
JS

.on('submit', '#application-form', function(e) {
    e.preventDefault();

    var form = $(this),
        formData = new FormData(form[0]),
        msgBox = form.find('.msg-box'),
        submitBtn = form.find('.submit'),
        loader = submitBtn.find('.fa');

    submitBtn.prop('disabled', true);
    loader.css('display', 'inline-block');

    formData.append('attachment[]', form.find('#resume')[0].files[0]);
    formData.append('attachment[]', form.find('#portfolio')[0].files[0]);

    $.ajax({
        url: '/',
        type: 'post',
        data: formData,
        dataType: 'json',
        contentType: false,
        processData: false,
        success: function(data) {
            msgBox.fadeOut(function() {
                if(data.success) {
                    $(this).text( 'Your application has been submitted!').removeClass('error');
                    form[0].reset();
                } else {
                    $(this).text('An error occurred. Please try again.').addClass('error');
                }

                submitBtn.removeAttr('disabled');
                loader.removeAttr('style');

                msgBox.fadeIn();
            });
        }
    });
})

HTML

<form id="application-form" class="content-block-lg" method="post" action="" accept-charset="utf-8" enctype="multipart/form-data">

            {{ getCsrfInput() }}
            <input type="hidden" name="action" value="contactForm/sendMessage">
            <input type="hidden" name="fromEmail" value="no-reply@example.com">
            <input type="hidden" name="subject" value="Application Form">

            <input type="text" id="address" name="address">

                <input type="text" name="message[Name]" placeholder="Name">

                <input type="text" name="message[EmailOrPhone]" placeholder="Email or Phone">

                <textarea name="message[body]" rows="3" placeholder="Tell us about you"></textarea>

                <input type="text" name="message[LinkToOnlinePortfolio]" placeholder="link to online portfolio">

                Upload a pdf of...
                <input id="resume" type="file" placeholder="resume">
                <input id="portfolio" type="file" placeholder="portfolio">

                    resume
                    portfolio

                <button class="submit" type="submit">send </button>

</form>

The problem I am getting is that, with the code above, submitting the form, I get a response of the entire Homepage html.  I've tried using the url set in the action hidden input, but that just gives me a 404 response.  It's like it can't see the "Action" being passed in because it's in FormData?


texts:
Very new to Craft & Twig. So I get the following error: Impossible to invoke a method ("url") on a integer variable ("0") with the below code:
{% if module.type == "rotator" %}

        {% for row in module.contents %}
            {% set position = loop.index0 %}
            {% set previous = loop.index -1 %}
            {% set next = loop.index + 1 %}

                     ‹

                    {{ previous.slideTitle }}

{{row.slideTitle}}

                        {{row.slideCaption}}

                    {{ next.slideTitle }}

                     ›

        {% endfor %}

{% endif %}

So basically I need a 'previous' and 'next' variable that corresponds to the previous row and the next row in the Super Table. Essentially I need a way to call the current row in the Super Table I'm at, and the previous row and next row relative to the row I'm on.
Here's what my set up looks like:

I've tried loop.index0 + 1 and loop.index + 1. But neither work and I know I am calling them in the wrong way.


texts: I have an S3 volume with a row in the volumefolders table that uses camel case. This is not appropriate for our S3 configuration. Can I just update the row to downcase the name and path? Is it possible to require lowercase names when creating a new folder in the S3 volume?


texts: Variable "entrySlug" does not exist Routing

texts:
I currently have a routing set up as follows to enable an "Edit" entry page following on from this question but I'm getting the following error message when going to that page.

  Variable "entrySlug" does not exist

I have my routing set up as follows within my CP, which loads a URL like so mydomain.com/marketplace/authorname/entryname/edit

and within my listings/_edit

{# Find the entry by slug and author: #}
{% set listing = craft.entries({
    section: 'networks',
    slug: entrySlug,
    author: currentUser
}).one() %}

I'm really unsure why it can't find the slug of the entry.


texts: How can I add an option group to the select Macro from CraftCMS forms macros

texts:
I'm trying to list out a select element with option groups and options using the awesome for macro that Pixel and Tonic created.

I have imported the macros and am calling the select one like so:

{{ forms.select({
          id: 'ccs',
          label: "Collection store:",
          class: '',
          name: 'fulfilmentStore',
          hasOptgroups: true,
          options: [
            {'optgroup':'North Island', 'value': 'NI1',},
            {'optgroup':'South Island'}
          ],
        }) }}

I pretty sure I have to have another lot of options sitting under the optGroup but can't get the syntax right.

Thanks in advance.


texts: Detect if a language is translated or not

texts:
For entries where the content isn't translated yet I'd like to add a "Sorry not translated yet" message.

Since all the content is synced is there a way to check if the synced content is the same as in the other locales?


texts:
I'm trying to set up multi-environment configs.

I have specific db settings I want to change depending on environment. I am using localhost and my Digital Ocean server IP address in my db.php file.

<?php

return array(

'*' => array(
    'tablePrefix' => 'craft',
),
'localhost' => array(
        'server' => 'localhost',
        'user' => 'root',
        'password' => 'root',
        'database' => 'something',
),
'xxx.xxx.xxx.xxx' => array(
            'server' => 'localhost',
            'user' => 'some_user',
            'password' => 'some_password',
            'database' => 'somethingelse',
    ),
);

I've tried switching the order, that did not work.

Do I need to use a domain name rather than a IP address here?


texts:
Is there any way to have some entries exist as flat files? Considering moving my blog over from Statamic where I have a boatload of Markdown files that work as article entries.

It seems like Craft can do anything! I wonder if there's someway to do a combo thing where some entries exist in the database and others in a directory.

Is this possible?


texts: How can I join plugin data with entry data based on uri?

texts:
I have a plugin with a record (and model). The record have attributes uri and hits. The uri attribute in my record corresponds to an entry's uri, as stored in the craft_elements_i18n table.

What is the most efficient way to return entries with the uris I have stored, sorted on hits? Is there a way to join the uri attribute in my record with the uri in the craft_elements_i18n table, and return entry data and hits in one go?

Right now I have this, which does the job but isn't very efficient:

$results = $this->queryResultRecord->getQueryResultsBySetId($querySet->id);

if ($results) {
    foreach ($results as $result) {
        $criteria = craft()->elements->getCriteria(ElementType::Entry);
        $criteria->uri = $result->uri;
        $entries = $criteria->find();

        if ($entries) {
            $entry = $entries[0];
            $return[] = array('entry'=>$entry, 'hits'=>$result->hits);
        }
    }
}

The getQueryResultsBySetId method return the data from my record sorted by hits. The $return variable is returned back to my frontend templates where I can do:

{% for result in results %}
    {{ result.entry.title }} - {{ result.hits }}<br>
{% endfor %}


texts: Display notification if no entries exist for status criteria and logged in user

texts:
I'm aiming to display disabled entries for a logged in user and a message if no entries with this criteria exist. I've tried two different ways without success.

Version 1 gets all entries - live and disabled, gets those by the logged in user, and then tests for the entry status of disabled (which doesn't work).

{% set entries = craft.entries
    .section('profileEntry')
    .status(null)
    .all() %}

     {% for entry in entries %}

        {% if currentUser.id == entry.author.id %}

            {% if entry.status == entry.status('disabled') %}

{{ entry.title }}

                {% else %}

No entries exist

            {% endif %}

        {% endif %}

    {% endfor %}

Version 2 only gets the disabled status entries, then the entries by the logged in user. Which doesn't work either.

{% set entries = craft.entries
    .section('profileEntry')
    .status('disabled')
    .all() %}

{% for entry in entries %}

        {% if currentUser.id == entry.author.id %}

{{ entry.title }}

        {% else %}

No entries exist

        {% endif %}

{% endfor %}


texts: Adding `www` causing it to have index.php

texts:
I am trying to get pretty urls

In my general.php file I have

'omitScriptNameInUrls' => true,

which works fine and removes the index.php

BUT

When I try to force a www in the htaccess the index.php comes back and I can't seem to remove this.

This is what I have in my htaccess

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

Any thoughts?


texts: Issue with external JS when toggling between entry types

texts:
I'm working on a custom plugin / fieldtype, and it requires first an external JS library, and then it needs to be initialized in-page. I.e:

<script src="//remote.path.to/my_script.js"></script>
<script>
    my_script.init({selector: '#my_field'});
</script>

I have the fieldtype set up as a second Entry Type in a test channel.

When I go to post a new entry, I (obviously) have to change Entry Types to the one with the field I'm developing. The first time I do this, everything works fine and initializes, but if I change the Entry Type back to the original type and then back again to the one with the test field, the Javascript initialization no longer appears to work or get triggered. In the browser's inspector, I see that the initialization line is getting inserted at the bottom of the HTML each time I switch to that Entry Type, so there's definitely duplicate code being appended; not sure if that's the issue or not.

Here's the basic and abstracted fieldtype code:

<?php
namespace Craft;

class MyPlugin_MyFieldType extends BaseFieldType
{
    function init()
    {
        craft()->templates->includeJsFile('//remote.path.to/my_script.js');
    }

    public function getInputHtml($name, $value)
    {
        $id = craft()->templates->formatInputId($name);
        $namespacedId = craft()->templates->namespaceInputId($id);

        // Prepare init string
        $script_init = "my_script.init({selector: '#" . $namespacedId . "'});";

        // Include JS
        craft()->templates->includeJs($script_init);

        return craft()->templates->render('MyPlugin/field', array(
            'name'          => $name,
            'id'            => $id,
            'value'         => $value
        ));
    }
}

I'm including the call to the remote script in the init() function so it doesn't get duplicated along with everything else.

So what's going on - why does the initialization not survive toggling between Entry Types?

EDIT: Also, not sure if related, but the field doesn't seem to survive the Live Preview mode, either. The JS-modifications that the script makes to the HTML form element are there visually, but I can't focus the caret in there. Also, once I exit the Live Preview mode, the content that was in the field before Live Preview is gone. I suspect at least part of this stuff is the external script I'm working with, but I figured I'd best report it anyway.


texts: Craft 3 Upgrade having issues with rich text editor

texts:
I know that Craft3 now requires Redactor or CKEditor plugins to handle rich text editing, however after installing the Redactor plugin through the store, I am getting this error in the 'Body'.
The title and everything else works, just the body gets the error:

  Unable to find component class 'RedactorI'.

Simple.json

{
  "buttons": ["bold", "italic"]
}

Standard.json

{
  "formatting": ["h2","h3","h4","h5","p", "blockquote"],
  "buttons": ["html","formatting","alignment","bold","italic","unorderedlist","orderedlist","link","file","image","video","table"],
  "plugins": ["fullscreen","video","table"],
  "toolbarFixed": true
}

I've checked my craft/config/redactor simple and standard JSON files and they're properly formatted.

Any ideas?

Thanks


texts: Send e-mail only to users related to entry with Postmaster/Sprout

texts:
I would like to set up Postmaster or Sprout Email to send an e-mail notification when a new entry is added. I only want the email sent to users who are linked to the entry via a custom field (type:user).

I've having trouble solving this without writing a plugin to extend either plugin. If I have to write a plugin to do this, any tips? Otherwise, how can I do this with either plugin?

To reiterate:

How can I have notifications sent only to users who are linked to the new entry via a custom field (type:user)?


texts:
I have looked through previous questions and answers, but don't see the following clearly explained.
When my users visit /logout, they are successfully logged out and redirected to the website's homepage.
What is not clear to me is how I can detect that action, and display some HTML saying they have been successfully logged out.


texts: Retrieving an entry by ID in ALL locales

texts:
I've been looking at How can I build a language switcher? but I don't to hit the DB for each entry in the loop, just to get the entry's localised slug.

However I can't see a way to get an entry by ID with anything other than the current or a specific locale.

So assuming I'm on a template where we have an entry defined, this returns 1 entry in current locale:

craft.entries.id(entry.id);

And this returns 1 entry in a different locale:

craft.entries.id(entry.id).locale('es');

How can I get entries for ALL locales so I can do one DB query rather than one for every locale that's enabled on the site?


texts: Commerce Stripe Card Declined shows white screen with no error

texts:
I've got an issue when cards are declined and only a white screen is shown to the user without any feedback. The url has not changed at all either.

This is happening on the live Stripe account so I set up a dev site and used the test account and saw the same when using the
4000000000000002 card number, devMode is enabled but no errors were returned.

Here are the relevant bits of my JS code which handle the creating of the card token and showing any errors encountered:

function stripeResponseHandler(status, response) {
    // Grab the form:
    var $form = $('#payment-information');
    if (response.error) { // Problem!
        if ($('#stripeToken').length) {
            $('#stripeToken').remove();
        }
        // Show the errors on the form
        $('#payment-information').find('.payment-errors').show().find("p").text(response.error.message);
        return false;
    } else { // Token was created!
        // Get the token ID:
        var token = response.id;
        // Insert the token into the form so it gets submitted to the server:
        if ($('#stripeToken').length) {
            $('#stripeToken').val(token);
        } else {
            $('#payment-information').append($('<input type="hidden" id="stripeToken" />').val(token));
        }
        $('#payment-information').find('.payment-errors').hide();
        $("#payment-information").submit();
        return true;
    }
}

Stripe.card.createToken({
    name: $('input[name="firstName"]').val()+" "+$('input[name="lastName"]').val(),
    number: $('#payment-card-number').val(),
    cvc: $('#payment-cvt-code').val(),
    exp_month: $('select[name="month"]').val(),
    exp_year: $('select[name="year"]').val(),
    address_zip: $('#shippingAddress-zipCode').val()
}, stripeResponseHandler);

Payments are going through fine on the live site and errors such as invalid card numbers are being shown correctly. However, 4000000000000002 is a valid card number and therefore the token is being created successfully without any errors. This is what is happening on the live site when payments are being declined for customers.

When this is then submitted through the commerce/cartPayment/pay form, no errors are shown, just a white page. Has anyone else encountered this and found a way around it? Thanks.


texts: Should the timezone in general settings effect the output of $time = date("g:ia");?

texts:
I am using the following in a plugin which I would expect to simply output the time of the server.

// get current time
$time = date("g:i a");
// outputs 9:36am

In a straight .php file this is correct - however, from within the plugin the time is an hour out - 8:36am. I imagine this might be to do with British Summer Time. However, in Crafts general settings I have set Timezone to UTC+1 (BST) - Europe/London


texts: How Do You Add A Form on a Page to Gate the Content?

texts:
I am new to Craft, but one of my clients has a website built in Craft. They would like to "gate" the content on a page of their website.

A. Is it possible to gate content in the Craft CMS? Client wants to add the capability of requiring an email address before viewing the content on a certain page.

B. If it is possible, what are the steps to adding/implementing?

Thank you in advance.


texts:
I haven't seen any answers specifically addressing this. While I did find a workaround, there's a bit of a gap in knowledge or guidance on this one, it seems.

I'm developing a plugin as prescribed in the Craft Docs, where my plugins folder is outside of my Craft folder:

  "minimum-stability": "dev",
  "prefer-stable": true,
  "repositories": [
    {
      "type": "path",
      "url": "../dev/craft-campaignmonitor-transactional"
    }
  ]

This is working great! After seeing a bunch of code work I ran composer require in my plugin to add a required package there, and it installed in my vendor directory for my plugin.

No matter what I tried, though, I kept getting "Class not found" errors for that package's class when I tried to use it in my plugin code.

Only when I ran composer require on the package in my Craft directory did it work in my plugin.

I can understand why this is happening...but should I be able to work on a plugin outside the Craft directory and keep vendor packages out of the Craft directory until I'm ready to install it? Or is this a necessary workaround while in development?


texts:
I have simple loop:

{% for total in thing %}
  {{ total.seatsKids }} {{ total.seatsParents }}
{% endfor %}

This results in a string of numbers eg. 1 3 4. I want the sum of all numbers. So how do I get 7 at the end? I don't understand how to write math operations within loops.


texts: Nested IA Structure - What's the best way to get it set up?

texts:
I'm beginning to work on my first Craft CMS website. (I'm really excited!) I've read a ton of documentation and am getting my head around setting up a structure within the system.

The website will be fairly large, and the site structure a few levels deep.

For the IA, say I have:

/ (Home)
/about  (About Overview Page, contains information from all subpages)
/about/team (bios of team members)
/about/history (content page)
/about/contact (contact form)
/industries (overview of all industries, contains content from subpages)
/industries/medical (industry overview page, contains contact from about, featured documents, featured case study, etc)
/industries/medical/about (content)
/industries/medical/history (content)
/industries/medical/documents (content + documents)
/industries/medical/case-studies (content + case studies)
/industries/medical/portfolio
/industries/financial
/industries/financial/about
/industries/financial/history
/industries/financial/documents
/industries/financial/case-studies
/industries/financial/portfolio
...(etc)

You get the point.

So, I believe that for the majority of the data (documents, case studies, portfolio items) I will set up channels to house that data. (Is that the way it should be done? Set up channels and then have a "Industry" select field where the admin can choose what industry the entry belongs to?)

How do I get this structure set up? Is it just a matter of adding templates into the corresponding /templates/ folders in the system?

I've gone into Admin > Sections and created an "Industries" section, and then I created entry types for: Content, Documents, Case Studies, Portfolio Items, Forms, etc.  Will I basically use that index.html template in /templates/industries/index to route ALL of the requests across all subpages in that section? i.e. get the one part of the slug to determine the active industry, and then the second segment to determine what page and what template to show?

If so, then what role would the Entry Template have?

Am I going about this all wrong?

I think once I understand this piece of it, everything is going to click.

Thank you in advance for your help! Happy to clarify anything to help me get clarity ;)

UPDATE: Upon further reading, I think I'm getting it. The entries are really just containers for the data, the sections are a way of organizing that data. I just use routes to handle the site structure. Is that correct?


texts: Does the Craft config var "cache" exist?

texts:
I'm reviewing the code on a project that has the following defined in the main config.php as a boolean:

cache => true

Looking at the docs this doesn't seem to be referenced anywhere. Does the config option exist in Craft 2? I'm not seeing any documentation that states it does.

I know others like cacheMethod and cacheDuration do.


texts: Proper way to pass matrix fields to Javascript

texts:
I'm working on a semi-headless solution with Vue frontend.
The problem is the Matrix field. How to properly pass this from the Controller in PHP to Javascript/Vue frontend? With all its possible extra queries needed to get categories etc.
I cant find any dynamic way to do this.


texts:
I’m runnung a few Craft sites with Redis cache enabled. It works fine. Except that Craft only uses around 3mb of Redis memory, with peaks up to 5, while there’s 128mb available.

Is there a way to set the amount of memory Craft can use? I couldn’t find anything in the documentation.


texts: Delay Updating element slugs and URIs Job

texts: On a large website, after using feedme to import some content it immediatelly triggers the "Updating element slugs and URIs" process that takes very long time to complete. Is there a way to postpone or temporary disable this task and do the import first?


texts: How can I order a sections entries by their children entry postDate?

texts:
Is it possible to order a section of entries by their child entries post date?

{% for article in craft.entries({
    section: 'articles',
    type: 'videoArticle',
    limit: 6
}).getChildren().order('postDate asc') %}
    {{ article.title }}
{% endfor %}

Each article has 1 child under it. I want to filter the articles by the latest postDate of the children.


texts: Case sensitive craft.entries.search() in Craft

texts:
From Brad's answer to this question it's obvious that Craft doesn't have a case sensitive search from the start, but he mentions that it depends on MySQL database and table collation.

My question is however related to the way Craft saves keywords in craft_searchindex table. Here they are converted to lowercase. So my question is if there is a way to enable case sensitive search through MySQL collation changes?

My issue is that the client sees an issue when searching for a Persons name in an article content he also finds results which only include words starting the same. However fuzzy search on the right side is needed, so turning it off isn't an option.


texts:
I have a Structure section (galeriesPhotos) with two Entry Types:

Albums - the categories on the index.html page
Photos - the the actual gallery on the entry.html

I'm trying to display the images related to the "Albums" on entry.html like this:

{% set entries = craft.entries.section('galeriesPhotos').getEntryType('Photos') %}

{% for image in entries %}
  <img src="{{ image.getUrl }}">
{% endfor %}

Nothing happens. I get a blank page without any errors. What I am doing wrong?


texts: Using PHP 7.4 on Laravel Forge, the storage folder has a permissions issue

texts:
Standard Craft install on Laravel Forge with PHP 7.4 installed. The storage folder is marked as unwritable so the site won't load. Switching back to PHP 7.3 fixes instantly.
I think it's related to this, so would welcome any experiences anyone else has had.


texts: How do I display entries from multiple entry types?

texts:
I have a 'teacher' channel section on my site. That channel has three entry types, 'teacher', 'demoTeacher' and 'guestTeacher' - how do I display entries from teacher and demoTeach combined? At the moment I'm showing one type like this:

{% for teacher in craft.entries.find({section: 'teacher', type: 'demoTeacher'}) %}

Secondly, how can I use a conditional that checks for entry type? I need do something like the following (pseudocode):

{% if entrytype is demoTeacher %}
    display read more button
{% endif %}


texts:
In the logs, I have this error:

2021-02-01 18:00:04 [-][-][-][error][craft\commerce\services\Emails::sendEmail] Email template parse error for email “Order Submitted”. Order: “123456”. Template error: “An exception has been thrown during the rendering of a template ("Getting unknown property: craft\console\Request::csrfParam").” /home/project/templates/shop/_includes/order-review.twig:48

The code that it points to is this:
<form method="post">
     {{ csrfInput() }}
     {{ actionInput('commerce/cart/update-cart') }}
     {{ redirectInput('/shop/checkout/payment') }}

          <input type="text"name="couponCode" value="{{ cart.couponCode }}" placeholder="{{ "Coupon Code"|t }}">

               <button type="submit" class="btn btn-purple">Update Cart</button>

</form>


texts:
I currently have multi site config. One site have 2 locales.
My configuration like so:

'example.com' => array(
    'siteUrl' => array(
        'us_en' => 'https://www.example.com/',
        'br_sp' => 'https://www.example.com/sp'
    ),
'example.uk' => array(
    'siteUrl' => array(
        'uk_en' => 'https://www.example.uk/',
    ).

I'm using SEOmatic plugin.
Hreflang requires all site have to list on the head of page.
However, SEO list 2 locales which are us_en and br_sp on a site only.
How can I do it?


texts:
I'm writing a Craft CMS plugin with a widget. This widget needs to make calls to the Github-API trough javascript (Selectize is used in the widget). Now, the problem is that it's not allowed, made clear by this message in the console:

  Refused to connect to 'https://api.github.com/search/repositories/?q=i' because it violates the following Content Security Policy directive: "default-src 'self' data:". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

I can fix this by setting the Content-Security-Policy meta tag in the head:

<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://api.github.com/">

I've attempted to add this with the following code in the template for my widget:

{% set meta %}
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' https://api.github.com/">
{% endset %}
{% includeHeadHtml(meta) %}

Is this correct or is there a better way?


texts: Craft on digital ocean Ubuntu: Craft can’t connect to the database with the credentials in craft/config/db.php

texts:
I have been working locally on MAMP and now have deployed the site to Digital Ocean using this guide.
However I can't access the site. for page links I get the service unavailable error, and for the admin I get the 'Craft can’t connect to the database with the credentials in craft/config/db.php.' error.
i have checked my database credentials many times and they match.

return array(
    '*' => array(
        'tablePrefix' => 'craft'
    ),
    '000.00.000.00' => array(
        'server' => 'localhost',
        'user' => 'craftcms',
        'password' => '************',
        'database' => 'craft'
    ),
    'localhost' => array(
        'server' => 'localhost',
        'user' => 'root',
        'password' => '************',
        'database' => 'craftdev'
    ),
);

my general config settings are as follows:

return array(
    '*' => array(
        //'siteUrl' => "//projectname:8888/html/",
        'environmentVariables' => array(
            'basePath' => '/users/toddpadwick/Sites/projectname/html/',
            'siteUrl'  => '//projectname:8888/html/',
        ),
        'testToEmailAddress' => 'email@email.com',
        // Default Week Start Day (0 = Sunday, 1 = Monday...)
        'defaultWeekStartDay' => 0,
        // Enable CSRF Protection (recommended, will be enabled by default in Craft 3)
        'enableCsrfProtection' => true,
        // Whether "index.php" should be visible in URLs (true, false, "auto")
        'omitScriptNameInUrls' => 'auto',
        // Control Panel trigger word
        'cpTrigger' => 'admin',
        // Dev Mode (see https://craftcms.com/support/dev-mode)
        'devMode' => true,
    ),
    // Use IP address of your droplet below
    '000.00.000.00' => array(

        //'siteUrl' => 'http://000.00.000.00/',

        'environmentVariables' => array(
            'basePath' => '/var/www/html/',
            'siteUrl'  => 'http://000.00.000.00/',
        ),
        // Default Week Start Day (0 = Sunday, 1 = Monday...)
        'defaultWeekStartDay' => 0,
        // Enable CSRF Protection (recommended, will be enabled by default in Craft 3)
        'enableCsrfProtection' => true,
        // Whether "index.php" should be visible in URLs (true, false, "auto")
        'omitScriptNameInUrls' => 'auto',
        // Control Panel trigger word
        'cpTrigger' => 'admin',
        // Dev Mode (see https://craftcms.com/support/dev-mode)
        'devMode' => false,
    )
);

Any help would be greatly appreciated!


texts: What's the difference between ElementCriteriaModel and DbCommand?

texts:
Forgive me if this is a stupid or naive question...

I generally think of an ElementCriteriaModel as being a "search object". Specifically, it's a search object which revolves around a specific type of element. The model has attributes like order, offset and limit, which are obviously common terms when conducting an SQL query.

On the other hand, a DbCommand is an object which directly translates to an SQL query. This is far more flexible, allowing you to do things like perform complex joins.

So while I can certainly see some differences, it's hard for me to grasp the finer points of one vs. the other. (I'll admit that typing this has helped me to see it a little more clearly.)

What am I missing/misunderstanding?


texts: Grouping by select - keep order of options

texts:
I have a channel of entries that are being pulled into a single. I then  want to group the entries by a dropdown field called dealStatus.

This is working correctly, however the grouping is not outputting the order correctly. I expect the order of the groups to be in the same order that the dropdown field has them.

InMarket
postBid
closing
closed

Instead the groups are getting output in this order

postBid
inMarket
closing
closed

How do I get the groups ordered the same as the dropdown field option order?

My current code:

{% set allDeals = craft.entries.section('deals').relatedTo(entry) %}
{% set allDealsByStatus = allDeals|group('dealStatus') %}

{% for status, entriesInStatus in allDealsByStatus %}

      {{ status }}

          {% for entry in entriesInStatus %}

{{ entry.title }}

          {% endfor %}

{% endfor %}

This is on Craft 3.0.1


texts: Can I create a number with decimal point in number field?

texts: Could number for example 7.5 be created in number field?


texts: Craft constantly logging out from admin area

texts:
While working in the Craft admin area, on a fresh install, I get logged out every once in a while. It makes the CMS unusable.

I have tried:

Clearing cookies
Resetting the cache in the backend

Sometimes it logs out after 1 pageview, sometimes after 10.

I am using a Macbook Pro, 10.9.3 Mavericks. This happens in both Chrome and Safari (haven't tried Firefox).

I am running Vagrant with: PHP 5.5.12, Ubunutu 14.04, Nginx. Accessing the project locally via http://project.craft.dev

Has anyone experienced something similar? Are there any error logs for this kind of thing?

Update: in the craft.log I get a few errors:

2014/07/11 19:38:56 [trace] [system.db.CDbCommand] Querying SQL: SELECT count(`id`) FROM `craft_tasks` WHERE (level = 0) AND (status = :status). Bound with :status='error'
in /vagrant/dlfm/craft/craft/app/etc/db/DbCommand.php (79)
in /vagrant/dlfm/craft/craft/app/services/TasksService.php (420)
in /vagrant/dlfm/craft/craft/app/controllers/TasksController.php (57)

and

2014/07/11 19:38:55 [error] [php] session_write_close(): Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/vagrant/dlfm/craft/craft/storage/runtime/sessions/) (/vagrant/dlfm/craft/craft/app/services/HttpRequestService.php:852)
Stack trace:
#0 /vagrant/dlfm/craft/craft/app/framework/web/actions/CInlineAction.php(49): Craft\TasksController->actionRunPendingTasks()
#1 /vagrant/dlfm/craft/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams()
#2 /vagrant/dlfm/craft/craft/app/framework/web/CController.php(286): Craft\TasksController->runAction()
#3 /vagrant/dlfm/craft/craft/app/framework/web/CController.php(265): Craft\TasksController->runActionWithFilters()
#4 /vagrant/dlfm/craft/craft/app/framework/web/CWebApplication.php(282): Craft\TasksController->run()
#5 /vagrant/dlfm/craft/craft/app/etc/web/WebApp.php(863): Craft\WebApp->runController()
#6 /vagrant/dlfm/craft/craft/app/etc/web/WebApp.php(252): Craft\WebApp->_processActionRequest()
#7 /vagrant/dlfm/craft/craft/app/framework/base/CApplication.php(180): Craft\WebApp->processRequest()
#8 /vagrant/dlfm/craft/craft/app/index.php(196): Craft\WebApp->run()
#9 /vagrant/dlfm/craft/public/index.php(14): require_once()
REQUEST_URI=/index.php/admin/actions/tasks/runPendingTasks
in /vagrant/dlfm/craft/craft/app/services/HttpRequestService.php (852)
in /vagrant/dlfm/craft/craft/app/controllers/TasksController.php (37)
in /vagrant/dlfm/craft/craft/app/etc/web/WebApp.php (863)

but this one looks most suspect:

24. 2014/07/11 19:41:47 [error] [application] Tried to restore session from a cookie, but the given login name does not match the given uid. UID: 9d515b08-1073-4872-a0e2-155c389a2991 and loginName: Jason.

24. 2014/07/11 19:41:47 [error] [application] Tried to restore session from a cookie, but the given hashed database token value does not appear to belong to the given login name. Hashed db value: 37bb858b4b13b688c4034fe5eb127f75f4931387czozNjoiNDBlNTk0YWQtNGYxZS00NjAxLWEwY2UtZDJlY2NhNDkwMmQ1Ijs= and loginName: Jason.
in /vagrant/dlfm/craft/craft/app/services/UserSessionService.php (797)
in /vagrant/dlfm/craft/craft/app/services/UserSessionService.php (64)
in /vagrant/dlfm/craft/craft/app/etc/web/WebApp.php (592)


texts:
I recently installed Calendar (latest 1.9.3) on my Craft install (latest 2.6.2997)

Within the demo templates provided by Calendar (/calendar_demo/), the month view, I am getting the following error:

Fatal error: Call to a member function getTimestamp() on boolean in ../craft/app/helpers/DbHelper.php on line 597

I have seem to narrow it down to the targetDate variable being set to "today"

{% set targetDate = "today" %}

However, if i go to the following url: /calendar_demo/month/2017/11 the month view works but the test event I have doesn't show.

What am I missing here?

I am on a Pro license and only plugins I have installed are:

Contact Form (P&T)
Focus Point
Instagram Feed (currently disabled)
Minimee
Polls (currently disabled)
Relabel

Again now sure what I am missing here any point in the right direction is welcomed.


texts: Possible to merge and sum the values of an array?

texts:
I have a super table that has 4 columns. I'm trying to create an array based off one column (contentType) and merges to get only the unique values while taking the sum of a different column (points). Here is a screen shot:

Based off that screenshot I would have the following results:

Motivation-To-Achieve : 2
Emotional-Stability : 2
Openness : 4

I'm able to get the unique content types, however, I can't figure out how to take the sum of the points column. This is what I have so far:

{% set results = {} %}

{% for row in entry.surveyData %}
    {% set type = row.contentType %}
    {% set pts = row.points %}
    {% set results = results|merge({ (type) : {'name': type, 'points': pts } }) %}
{% endfor %}


texts:
I need to store Javascript/HTML code in some of our entries. I have tried to put the code in plaintext but cannot get the code to render through twig. I cannot store this stuff on the filesystem. It really needs to be attached to an entry if possible.

Any ideas?


texts:
I am making a plugin where I have about 10 tabs at the top.  Depending on the admin users privileges they may see a subset of 1-5 or 6-10 and super admins can see all 10.  The issue I am running into is I built the logic to show appropriate tabs for the user based on their privilege and it works fine.  What I now want to do is include that into an include file so I don't have the 60 lines of code on each of the 10 pages in the plugin.

I know I can put it into the main layout template in _layouts/cp but my logic is checking some variables that are set on each page of the plugin.  So if I put it in there none of my variables are set yet so the tabs don't show as nothing will match.  Example _layouts/cp template.

{% if user.superAdmin == "no" %}
  {% if color == "red" %}
    {% if usercolor != "red" %}
      {% redirect redirectUrl %}
    {% else %}
      {% set tabs = {
       red: {label: "red", url: url('admin/pluginname')},
       darkred: {label: "dark red", url: url('admin/pluginname/darkred')}
       } %}
    {% endif %}
 {% else %}
    {% if usercolor != "blue" %}
       {% redirect redirectUrl %}
    {% else %}
      {% set tabs = {
       blue: {label: "blue", url: url('admin/pluginname/blue')},
       darkblue: {label: "dark blue", url: url('admin/pluginname/darkblue')}
       } %}
    {% endif %}
 {% endif %}
{% else %}
      {% set tabs = {
       red: {label: "red", url: url('admin/pluginname')},
       darkred: {label: "dark red", url: url('admin/pluginname/darkred')},
       blue: {label: "blue", url: url('admin/pluginname/blue')},
       darkblue: {label: "dark blue", url: url('admin/pluginname/darkblue')
       } %}
{% endif %}

{% set block('content') %}

In each template file I will set what color the user is associated to and it should give a different set of tabs.  Example of template file.

{% set redirectUrl = "/admin/pluginname/darkblue" %}

{% set color = "darkred" %}

{% set usercolor = user.userColor %}

{% extends "_layouts/cp" %}

{% set selectedTab = "darkred" %}

{% set content %}

{% endset %}

If I move all my tab logic in the layout file and put it just below the extends _layout/cp the tabs work fine but not when it is in the layouts file.  I am sure there is an easy fix that I am just missing something but any help would be appreciated.  Not the end of the world if I have to have the tab logic within each template file but not ideal for any future changes.

Thanks


texts: How to get url from related entry in another site

texts:
I'm relating entries from another site in my installation, and I'm having issues getting the correct URL for the entry. This is an example of what I currently have:

{% set carouselEntries = entry.contentCarouselEntries.all() %}

{% for entry in carouselEntries %}

    {{ entry.title }}

{% endfor %}

This will get the correct title, however, it does not get the correct URL in that it does not include the site. Assume that the current site is mywebsite.com, and the URL for the site I'm retrieving the related entry is news.mywebsite.com. I'd expect the URL to be:

https://news.mywebsite.com/article/article-slug

Instead it's:

https://mywebsite.com/article/article-slug

The article/article-slug comes from Entry URI field in Settings > Sections > Site Settings > Entry URI Format

This is undoubtedly easy stuff, but I'm blanking on how to output this in my template?

I'm assuming that I need to query these entries in a different way? Whatever the solution, the entries need to output in the same order they were added to the entries field (contentCarouselEntries) on mywebsite.com.

Also, the solution needs to be dynamic in that I cannot just build the URL in my template like this:

https://news.mywebsite.com/article/{{ entry.slug }}

The related entries actually come from multiple sites in my installation including 'blog' and 'news', and from multiple environments like .local and .com. So, the link should include the site the entry is from and the environment you're in.


texts: Uploading a user picture on registration

texts:
I would like to make an image upload field so new members are required to upload a picture. I'm new to Craft (I've been a Drupal Front End developer). Other custom fields are working perfectly, and I've added enctype="multipart/form-data" to my form tag. This is how my input field looks like now, but I get a CException error.

Upload Foto

    <input type="file" name="userPhoto"
    {%- if account is defined %} value="{{ account.userPhoto }}"{% endif %}>
    {% if account is defined %}
    {{ errorList(account.getErrors('userPhoto')) }}
    {% endif %}

I've been searching for a while now but can't seem to find an answer on it.
So I hope someone can help me :-). Thanks a lot!


texts:
I have a channel section called Members. I have 2 category groups (categoriesMembres & cantons).

My goal: show entries only related to a specific category in categoriesMembres and loop through the cantons:

Canton1

entry 1
entry 2
etc.

Canton2

entry 3
entry 4
etc.

Right now the code below display it like that:

Canton1

entry 1
entry 2
entry 3
entry 4

Canton2

entry 1
entry 2
entry 3
entry 4

The code (I stripped out html for clarity)

{% set membersCat = craft.categories.group('categoriesMembres').title('Membre').first() %}
{% set entries = craft.entries.section('listeMembres').relatedTo(membersCat) %}
{% set cantonsCat = craft.categories.group('cantons').relatedTo(entries) %}

{% for canton in cantonsCat %}
   {{ canton.title }}
   {% for row in entries|batch(3) %}
    {% for entry in row %}
     {{ entry.title }}
    {% endfor %}
    {% endfor %}
    {% endfor %}

What am I overseeing or doing wrong?


texts: Issues loading files from within css files

texts:
i just started using craft on a local domain and i have some issues.
my stylesheet(a few files) are loaded using html<link rel="stylesheet" href="style/style.css">, and it works great for css and js files, but files requested from within the css aren't loading.
for example the Font Awesome @fontface.

Any ideas? and the is any issue using html instead of the {{ getHeadHtml() }} method?

Thanks Ahead!


texts: Programatically create a Neo block with children

texts:
I already discovered how to create a neo block programmatically from this post: How can I set a Neo field's values from my plugin/module?
However, I don't know how I can create a neo block with child blocks.
So the idea is I want something like this:
[
    'blocks' => [ // Neo field handle
        'new0' => [
            'modified' => 1,
            'type' => 'topLevel', // Top level neo block
            'enabled' => 1,
            'collapsed' => 0,
            'level' => 0,
            'fields' => [
                'someField' => true, // Neo block field
            ],
            'children' => [
                'new0' => [
                    'modified' => 1,
                    'type' => 'secondLevel', // child neo block
                    'enabled' => 1,
                    'collapsed' => 0,
                    'level' => 0,
                ]
            ]
        ]
    ]
]

The children array is just what I imagine the solution might be like. But this doesn't work.
Does anybody know how it should be done?
Thanks


texts: Unable to set error message in onBeforeDeleteUser

texts:
This is related to How to overrule Craft error messages with custom setError()? but I don't have enough rep to comment on it.

I have a plugin that needs to check if a user is ok to be deleted before doing so. Stopping the delete with $event->performAction = false; works fine, but I am unable to overwrite the Craft message with my own to tell them why.

The following code demonstrates the problem:

craft()->on('users.onBeforeDeleteUser', function(Event $event){
    craft()->userSession->setError("I don't want to delete " . $event->params['user']->username);
    $event->performAction = false;
});

If deleting from the edit user page the "Couldn't delete the user" message is shown. I can change setError() to setNotice() and it will be displayed alongside the Craft error as a potential workaround, but I'm reporting an error so would like to display it as such. (There is the other workaround of setting the error on a field of the user entry, but in my case the error has nothing to do with a field on the page so this would be misleading.)

If deleting from the users listing page setError() shows nothing, just the Craft notice "Deleted Users" is shown. This also cannot be overridden with setNotice().

Is there a way of overriding the Craft error message or showing my own error message alongside it?


texts: Using Craft CMS with Foundation 6 (for Sites)

texts:
So I finally am climbing on board the Craft CMS train, but I have a quick question about how some of you more seasoned Craft-users do things.

I do a lot of my work using the Foundation framework (by ZURB) for a lot of reasons, but I want to know if there is a "best way" to include the front-end framework with Craft. I've never really used a CMS before, so this isn't really a familiar territory for me at all. I haven't found any good guides online as of yet detailing how to do this with Foundation 6, so I figured this would be the next best place to turn! If someone who knows more than me could walk me through the process to mesh these two awesome elements together, that would be much appreciated!


texts: Fetch entries filtered by array within custom field

texts:
I'm using the multidate field plugin, which is excellent at presenting dates but I need to return entries based on testing the first date in there. I typically test with the entries loop, like so:

{% if product.dates.dates[0] | date('U') > now | date ('U') %}

but would prefer to only get entries fitting that criteria in the first place. Is there any way to fetch entries according to the first value in a an array like this?

{% set products = craft.commerce.products.dates(somehow only test the first value in the dates array here) %}

The field looks something like this:

dates [ // this is the custom field name
    dates [ // this is the dates array within the custom field
        [0] // this is the date object I want to test against
        [1]
        [2]
    ]
]


texts: How do I prevent Redactor from wrapping  with

texts:
I'm looking to have the <img> inserted without the wrapping <p />. I'm assuming I can tie in to one of the callback functions to do this? There is a fileUploadCallback function available but based on nomenclature, doesn't seem like that would help me if I added a path to a remote image versus uploading one.

Has anyone done this yet?


texts: Need no search engine tracking option in Craft websites

texts: Can you let me know what the process would be? I heard there was a no track tag we can put in the site header so the sites won't show up in search engines.


texts: Is there a way to define a global var within a twig block?

texts:
Something that would work like this:

{% block A %}
  {% set testVar = "foo" %}
{% endblock %}
...
{% block B %}
  {{ testVar }}
{% endblock %}

The scope of testVar seems limited to {% block A %}

I'm looking for a way around this, so that the child template can pass content to the parent to use in other blocks.

This is an issue since the child template that extends the parent cannot have content outside a defined block.


texts:
I have some matrix fields defined:

But when I use the matrix blocks inside of an entry - I don't get all blocks - just the richText ones.
I tested it out - just the richtText Matrix blocks will be loaded when I do:
  {% include "_private/partials/matrix" with {blocks: entry.bodyContent.all()} %}

Is there something I am missing, or is this a bug?
Would be great if someone could help.


texts: Getting Page Not Found error for my custom subdomain setup

texts:
I want to setup a new custom subdomain (va.domain.com) within the project of my existing domain (craft.domain.com) using homestead.

So I referred to this this answer on craftexchange and followed all the steps.

I now have a separate folder at the root level called public_va. Inside that I have my index.phpwith this define statement that is supposed to change the path:

define('CRAFT_TEMPLATES_PATH', realpath(dirname(__FILE__) . "/../templates_va").'/');

Inside of the craftfolder I have created a folder called templates_va that is a sibling of the existing templates folder. And I put in a simple index.html file in just for testing.

Now when I point my browser to va.domain.com, it just shows me:

Page Not Found

The requested URL was not found on this server.

I also tried creating a new (single) section called va_homepage in the CP backend but I get the same error.

What am I doing wrong? How do I fix this? My error logs inside my vagrant box show nothing. The domain itself has been setup correctly via homestead. I verified by routing request to a static file.


texts: Possible to re-use one field multiple times in a section?

texts:
This seems like it should be possible but I may be missing a trick.

Is it possible to use a single field multiple times in a section? So, for example, if you have a simple 'text' field and you want to include that twice in one section. The field layout designer only allows you to drag it once and then just move it to different tabs but not create another instance of it.


texts:
Our client has (sadly) presented a new site URL as www.foo.bar.com instead of foo.bar.com. I need to use .htaccess to remove the www. The site works correctly if www is not prepended to the URL.

This question comes close but implementing with a subdomain doesn't work.

Here's my .htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Redirect to non-www domain
    RewriteCond %{HTTP_HOST} !foo\.bar\.com$ [NC]
    RewriteRule ^(.*)$ http://foo.bar.com/$1 [R=301,L]

    # Send would-be 404 requests to Craft
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
    RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

To clarify, I would like to remove both www and index.php from all URLs. So:

http://www.foo.bar.com/yay -> http://foo.bar.com/yay

FWIW, this is hosted on Rackspace, which requires the Rewrite Base / directive.


texts: Using Shortlist plugin to create product wishlist

texts:
I'd like to use the Shortlist plugin to allow visitors to create product wishlists - using Craft Commerce.

Currently, I have setup the 'add to wishlist' function, but I am not sure how to then display the items that a user has add to their wishlist.

The code below, is the example given on the plugin docs for how to loop through the items a user has added, but this does not produce the required results for commerce products.

{% if shortlistLists is empty %}
You have no lists at the moment.
{% else %}
    {% for list in lists %}

{{ list.title }}

    {% if list.items is empty %}
    No items in this list
    {% else %}

        {% for item in list.items %}

{{ item.title }} (Remove)

        {% endfor %}

    {% endif %}
    {% endfor %}
{% endif %}

The docs for the plugin are available here - https://squarebit.co.uk/software/craft/shortlist/usage/quickstart

If anyone could point me in the right direction as to how to successfully use the plugin in conjunction with Craft Commerce, that would be much appreciated.


texts:
I have a Matrix field and I want to be able to filter by it.

For example I want to get all entries that has matrixField.field1Type.value = {some value}.

How can I do that?


texts: I have a date field, and I want it to be possible for this to be empty. How it works now is that if you don't enter a value, it takes today's date. Any suggestions?


texts: A more economical method of building an archive menu?

texts:
I seem to be having trouble with the performance of my site (on localhost) after including this object. Im using it to build a menu for an archive of the posts section which has about 2,500 entries inside of it.

{% set allEntries = craft.entries.section('posts').limit(null) %}

{% for year, entriesInYear in allEntries | group("postDate.year") %}
    {{ year }}
{% endfor %}

This fetch request spits out the following:

  2016 2015 2014 2013 2012 2011 2010 2009

When I make this fetch request, my page is reload time is ~11s. If I comment out this request my page reload time is ~3s.

Is there a more economical way to return the years associated with my posts?


texts:
I am new to Craft and have a decent handle on the basics, but I am struggling a little getting this to work.  Here is what I would like to do:

I have a banner with bxslider which will be looping through images in a matrix field.  This is for a church site and this template will be used for all their ministries.  Each ministry will have it's own photos, but right now assets is returning images for all entries.

Here is my code:

{% elseif craft.request.segment(2) == "crosstrainers" %}

        {% for entry in craft.entries
            .section('site_content')
            .find()
        %}

        {% for block in entry.slider %}

                    {% for image in block.sliderImage.limit(1) %}

                    {% endfor %}

{{ block.sliderHeader}}

{{ block.sliderText}}

{{ block.sliderButtonText}}

        {% endfor %}

        {% endfor %}

Any suggestions on how to limit the asset results to each ministry.


texts: Is it possible to include any tax values in the price on the products page (not just the cart)?


texts: How do I get a random entry's URL from a Entries field?

texts:
I have a Entries field and I'd like to return a URL for one randomly picked entry.

I could loop through all the entries, but I'd like to do something more efficient. Can I return an array of URLs? Or better yet, is it possible to randomly get one URL all at once?


texts:
I'm trying to make a archive page for a blog sorted by months. I tried to consult the solution from Linking and showing archive by month, but I can't get it to work like it should. The code I have now just displays all entries regardless of their post date.

{% set catch = year ~ '-' ~ month ~ '-01' %}
{% set firstDay = catch | date_modify('first day of ', month ~ year ~ ' 00:00:00') %}
{% set lastDay = catch | date_modify('last day of ', month ~ year ~ ' 23:59:59') %}
{% set archive  = craft.entries.section('blog').postDate('and', '>= ' ~ firstDay.date, '<= ' ~ lastDay.date) %}
{% for entry in archive %}

{{ entry.title }}

{% endfor %}

I had to add ".date" behind "firstDay" and "lastDay", or I get an error (Object of class DateTime could not be converted to string) If I remove the "and" from "archive" like this:

{% set archive  = craft.entries.section('blog').postDate('>= ' ~ firstDay.date, '<= ' ~ lastDay.date) %}

then it sorts my entries according to "firstDay", but completely ignores "lastDay". I tried to threw an and into the middle of the string, but that didn't to anything.

I also tried to use .after and .before, but then I just get what seems like a random set of entries...

{% set archive = craft.entries.section('blog').limit(null).after(firstDay).before(lastDay) %}


texts: Get the fields (fieldLayout) of the section. Not the entry

texts:
Can I get all the fields of a section? For example, I have channel events, I want the fields in that section, but not related to any specific event.

I want to know all the fields (not the values), before actually executing the query.


texts: Commerce & PayPal - What does "Solution Type" mean?

texts:
Our site is using the Craft Commerce plugin, and within that we've enabled the PayPal Express gateway. However, there is a very cryptic dropdown menu on the gateway settings page...

So my question is, what is the "Solution Type"?

What does that even mean? And what is the difference between the "Sole" and "Mark" options?


texts:
I've been doing some quite involved work on a site where we want to restrict user access to certain asset paths. Following the post at Assets Folder: Images don't show up I was directed to the excellent add-on, AssetSubfolderAccess

After hitting a few bugs think have resolved but this only works in the Assets tab/are of the Control Panel. It does not seem to work within the Assets modal (eg when prompted on entry creation/edit). Is there a separate hook available for asset modals or can anybody suggest an alternative way of targetting specific asset paths at specific users?


texts: Access array from the static translation file

texts:
This is the scenario: I need the translations strings in both Twig and JS (For React). Of course I'm covered in the Twig part., and I don't want to maintain two different files (php and json). So I've created a custom module, where I can read the files, like:

public function getTranslations($language, $translationsFileName = 'site')
{
    if (file_exists(CRAFT_BASE_PATH . '/translations/' . $language . '/' . $translationsFileName . '.php')) {
        return require_once(CRAFT_BASE_PATH . '/translations/' . $language . '/' . $translationsFileName . '.php');
    }
}

Usage:

{{ craft.translations.getTranslations(craft.locale) | json_encode | raw }}

It works, but, is this a good way? Is there a default Craft/Yii way?


texts:
I have been implementing my own PHP plugin code.

In that, I need to get an asset field in user info. If I can get if the asset is set on the field or not, it is enough.

I can get the values of text and radio button fields with $user->getFieldValue function.
However, it does not work for asset fields.
How should I do for asset?


texts: Sprout SEO Plugin - Title Tags Not Appearing Correctly

texts:
I have chosen to append all title tags with the site name on my site (see screenshot). However, none of my title tags are being updated when I click update. All title tags are appended with "- Site Name" and have appeared that way prior to adding the Sprout Plugin. I've tried changing the character, but nothing is updating the title tags.

Is there somewhere else in Craft that allows for management of title tags that I'm missing? Thanks for your help!


texts: Programmatically Setting Entry Type Via Javascript

texts:
At the moment I'm trying to create a script that is supposed to be run (by chrome extension) on page load (of the new entry page) that with automatically set the entry type. The name of the entry type is "Episodes" and the value (from the html) of the entry type is 5.

Here's the script I have so far.

var contenttype = document.getElementById('entryType');
contenttype.value = "5";

When run, this changes the Entry Type field on the side, but it doesn't actually set the entry type.

How should I go about doing this?


texts: Filtering entires via tag field and checkbox field using a form

texts:
*** Edited the question
I have a code that used to work fine on Craft 2 and I don't understand what I need to change to make it work on Craft 3.
I am using form to filter through a channel of entries based on two fields - checkbox field with handle blogcategory and tags field with handle blogTags.
Here is the code of the form I am using for the filtering (worked perfectly on craft 2):
{% set blogcategory =  craft.request.getQuery('blogcategory') %}
{% set tags =  craft.request.getQuery('tags') %}

<form action="" method="get">

            category
            <select name="blogcategory">
                <option value="">Any Category</option>
                {% for option in craft.fields.getFieldByHandle('blogcategory').settings.options %}
                    <option value="{{ option.value }}">{{ option.label }}</option>
                {% endfor %}
            </select>

            tags
            <select name="tags">
                <option value="">Any tags</option>
                {% for tag in craft.tags.group('blogTags') %}
                    <option value="{{ tag.title }}">{{ tag.title }}</option>
                {% endfor %}
            </select>

        <input type="submit" value="filter">

</form>

And here is the code for displaying the entries:

    {% set entries = craft.entries.section('blog') %}
    {% set search_terms = '' %}

    {% if blogcategory %}
        {% set search_terms = search_terms ~ ' blogcategory:' ~ blogcategory %}
    {% endif %}

    {% if tags %}
        {% set search_terms = search_terms ~ ' tags:' ~ tags %}
    {% endif %}

    {% if search_terms %}
        {% set entries = entries.search(search_terms) %}
    {% endif %}

    {% for entry in entries %}

            {{ entry.title }}

    {% endfor %}

The problem is that after submitting the form with the desired filtering, none of the entries are showing up at all. It seems like the .serach function is not working...
I am a bit lost how to start understanding what fails under Craft 3...


texts:
Is there a way to ignore part of a querystring if it contains the parameter "action"?
We have a 3rd party site which returns to one of our sites and they append "&action=something" to the querystring. The 3rd party site are not able to remove this parameter, so when the user gets returned to our site they're greeted with a 404 page - the Craft docs suggest 'action' is used to determin an action controller to use, which in this case there is not one set.
My 'hack' of an idea would be to detect the parameter in a template, remove that parameter, then go to the url without the 'action' parameter set. This would add more page requests, which would be annoying for a user I can imagine.


texts: Pulling in matrix fields from a Single onto a different page

texts:
Just wondering how to pull content from a matrix field on my homepage into another .html file. Basically taking the content from a single and placing it into a different template. This is what I have so far:

{% for event in entry.homepage %}
    {% for block in entry.aloneImages %}
        {% for asset in block.image %}

        {% endfor %}
        {{ block.source }}
        {{ block.credit }}
     {% endfor %}
{% endfor %}


texts: Adding entries to the top level scope of a variable in Twig

texts:
I have made a frontpage editing system where the user can desk a frontpage, adding news items and other blocks manually. One of the blocks is "Last n news items". I would like this to include the last added news posts, except the ones that are already added manually.
I create an array called shownNews and add items to it each time the "show news item" block is called. My problem is probably related to variable scoping, the array is updated locally, but not in the global page scope.
{% set shownNews = [] %}

    {% for block in entry.layout.all() %}
        {% include '_blocks/' ~  block.type %}
    {% endfor %}

And then inside the included block I call
{% set entry = block.article.one() %}
{% set shownNews = shownNews|merge([entry.id]) %}

If I output the shownNews variable at this point inside the block it has correcly added the id to the array, but it is not available to the next block that is called.
I believed that if I declared the array on the top level it would be available for the included blocks both for reading (which works) and writing (which doesn't). What am I doing wrong here?


texts: Front End Asset Upload to Custom Element Type not working

texts:
I have a custom Element Type to which I can add several custom fields.  I can create a front end form with most of those custom fields and the submitted data saves just fine.  However, I'm getting some odd behavior with the Assets field.

I can save Assets fields from the front end of Craft to Craft sections just fine.  And I can edit one of the Entries for my custom Element types on the backend and upload an Asset just fine there as well.

But when I submit an Asset from the front-end for a new Entry with this custom Element type, I don't get the right behavior.

What does happen (as far as I can tell):

The asset uploads and appears in the target upload folder
A new row in the craft_relations table is created correctly
identifying the asset and the element that it is related to.

What doesn't happen:

The uploaded asset doesn't appear in the Asset index.  Even if I reindex assets for this particular folder, it never shows up in the Assets file manager.
When I visit the individual entry page in the CP, the Asset never appears. (But if I upload the asset directly from this CP page, the asset then does appear on this same page)

I'm struggling to know where to look to troubleshoot this.  What would cause an Asset not to display properly when it's uploaded from the front end but to work fine when it's uploaded from the back end?  Could I be missing some data on the front end submission?  My form uses enctype="multipart/form-data" and the asset field is as simple as it gets (and I've tried several variations (<input type="file" name="fields[uploadfield]" >)


texts: Random posts displayed but exclude current entry ID

texts:
I am brand new to Craft and can't find much support on this problem online. I have my entry pages and at the bottom of them, I have a div with the code below in it which randomly links to any entry.

I now would like this to disallow the entry that I am on from that randomization. I assume from other threads it would be something to do with finding the ID of the entry the user is on and not allowing it in the randomize?

{% for image in randomEntry.projectFeaturedImage %}

    {{ randomEntry.title }}
    See Project

{% endfor %}


texts: I am developing a custom authentication plugin for Craft 3. But I can't route to my Controller via POST request with my login form. Request via GET work


texts: Is it possible to download an asset from an entries tab

texts: I was wondering if there was a plugin that would give my client the ability to download an asset – in this case a submitted resume – when viewing an entry in the backend.


texts: Can someone help me with my site structure? Sections/Category setup

texts:
Thank you for your time and patience I'm a newbie to the Craft world. I've been all over the Craft Documentation and this site trying to figure out the best approach for a site I am putting together. The prototype I did makes sense however when it came time to put it into Craft I'm hesitant or lacking confidence in the setup. I just need a sound board to bounce off my setup.

Current Section setup:

Home (Single)
Company (Single)
Products (Single and Structure with multiple entry types)

Product Category A

Type A

Size A
Size B

Type B
Type C

Product Category B

Product

Product Category C

Type D
Type E

Support (Single)
Contact (Single)

How would I best create a template structure for the products section? How can I setup categories to help create this structure?

URL would ideally be
site.com/products/product-category/product

or do I even need products? Just jump to the product-category?

I want to have a category page, comparison page (Size) and dedicated product page. The category page with the type category wouldn't need an intermediate page.


texts: How do I edit a dropdown field in the charge.onCharge hook?

texts:
I have an invoice that is sent to stripe to be paid. When the thanks.html is shown, I would like the invoices section's invoicePaid dropdown field to change from "No" to "Yes" using the charge.onCharge hook.
I tried the following( and variations ) without success.

 {
    craft()->on('charge.onCharge', function(Event $event) {
        craft()->on('entries.onSaveEntry', function(Event $event ){

            //Is the entry in the section 'invoices'?
            if ($event->params['entry']->section == 'invoices') {

            //Replace values
            $event->params['entry']->getContent()->invoicePaid = 'Yes';
            }
        });

    });
}

Where am I going wrong, or is there a better way to go about this?


texts: Possible to redirect elsewhere after saving an entry?

texts:
I'm editing an entry in the CP...

mysite.com/admin/entries/mySection/33-my-awesome-entry

Now when I save this entry, it will redirect me back to the entry index page. However, I'd like to override this behavior, and get redirected to a different page upon saving.

Is it possible to override the redirect target when saving an entry?


texts: Craft login redirecting to /web instead of /templates?

texts:
I've moved my Craft directory to the below:

Templates
Public_Html
Web
etc..
etc..

My previous directory when I installed was:

Public_html > Craft-setup > Web > Templates

Now when I login from the front-end as a user, I get taken to the old directory even though it's empty,

example.com/craft-setup/web/

The actual directory it should be taking me to is

example.com/

As my index.php craft file is in public_html

What is the correct method to update the redirect to go to the correct place?

I can access my site perfectly fine and use it by going to example.com/ i'm assuming my base path is fine as the site loads and functions by going to the domain, so why is the front-end login taking me to the old directory? this is the login form I'm talking about https://docs.craftcms.com/v3/dev/examples/login-form.html

Appreciate any help


texts: Zero dollar Commerce orders - payment how-to?

texts:
My commerce site is setup using Stripe Checkout for payment.

It's possible a customer might have a zero-balance cart after discounts are applied to their order.

What are my options to allow the user to checkout without adding their credit card info into Stripe Checkout's overlay?


texts:
I need to develop a plugin where the user can modify his pictures (assets) on the fly. I've already done that in another PHP project and am willing to port it on craft, but I cant find any way on how to access assets, and what's the best way of doing it.

First, I want my plugin to act on asset sources, like you enable it or not.
Then, I want to add a button in the small window that opens up when you double click an asset (in an entry for example), how can one achieve this ?

Thanks a lot !

Edit
Usecase : I have an image gallery, where albums are a structure, and you can add images in any of them. New albums can be added by other users. When they double click a picture in the entry editor, I'd like to display a button that says something like "edit" (under the default options). I tried using a new field type but it's not the good and legit solution I guess.

When the button is clicked, they are brought to a new page (still in CP) where they can edit their picture (I did the editor in javascript), then save it.


texts:
I've set up a fixture, but Codeception can't find it. What am I missing or doing wrong?
% php vendor/bin/codecept run functional
...
  [Error] Class 'myname\tests\fixtures\MyFixture' not found

In the sample code the namespaces are under myname but I've also tried using just tests\fixtures, tests\unit\fixtures, and myname\tests\unit\fixtures.
Thinking it's something to do with the namespace or most likely something to do with the Craft fixtures docs saying

Fixtures…can be defined in the fixturesMethod defined in the codeception.yml file.

My codeception.yml doesn't have fixturesMethod. I can imagine that's a way of doing some of this but haven't found any documentation describing what that configuration should look like.
I've also tried loading the fixture on the command line
% ./craft fixture/load ImageAssetFixture
Exception 'yii\base\InvalidConfigException' with message 'Invalid fixture namespace: "tests\unit\fixtures". Please, check your FixtureController::namespace parameter'

% ./craft fixture/load ImageAssetFixture --namespace='myname\tests\fixtures'
Exception 'yii\base\InvalidConfigException' with message 'Invalid fixture namespace: "myname\tests\fixtures". Please, check your FixtureController::namespace parameter'

Here's the setup:
tests/functional/AssetFixtureCest.php
<?php

use FunctionalTester;
use myname\tests\fixtures\MyFixture;

class AssetFixtureCest
{
    public function _fixtures()
    {
        return [
            'myFixture' => [
                'class' => MyFixture::className(),
                'dataFile' => codecept_data_dir() . 'my-fixture.php',
            ],
        ];
    }

    public function testMyFixture(FunctionalTester $I)
    {
        $myFixture = $I->grabFixture('myFixture');
        codecept_debug($myFixture);
    }
}

tests/fixtures/MyFixture.php
<?php

namespace myname\tests\fixtures;

use Craft;
use craft\test\fixtures\elements\...;

class MyFixture extends ...
{
    /**
     * {@inheritdoc}
     */
    public $dataFile = __DIR__ . '/data/my-fixture.php';
}

test/fixtures/data/my-fixture.php
<?php

return [
    ...
];


texts: Relating a Category Entry to a Categories Field Type

texts:
I've been trying to get this working but can't seem to find a solution.

I have two different types of Categories in a commerce project.

Level One
Level Two

Examples

Level One would be Mens, Ladies, Kids etc
Level Two would be T-Shirts, Jumpers, Shoes etc

When I click on 'Mens' on the navigation, it brings me to the Mens page, I then get a sub navigation on that page which shows me any Level Two categories that are related to the Level One category (Mens).

These are related by using the categories field type.

This is got easily by the following:

{% for subCat in craft.categories.group('levelTwo').relatedTo(category) %}

The problem that I encounter now, is when you click on one of the Level Two categories on that sub nav (T-Shirts for example), it brings me to the t-shirt category page.  I want to be able to display the same sub nav that is on Level One (Mens), on the Level Two (T-shirts) page.

{% for subCat in craft.categories.group('levelTwo') %}

The above snippet shows me all the categories in Level Two, which is wrong.

I need to be able to show all the categories in Level Two, that have have the same categories field type.  The handle of this categories field type is topLevelConnection.

Any suggestions would be greatly appreciated!


texts: Which string identifiers for field types do exist?

texts:
There are several enum classes containing constants such as the SectionType class which I can use to create sections:

//  …
$section = new SectionModel();
$section->type = SectionType::Single;
//  …

But what about creating fields? Currently I create fields like so:

//  …
$field = new FieldModel();
$field->type = 'PlainText';
//  …

Is there any enum class containing valid identifiers I could use to create a field? Like in the following way?

//  …
$field = new FieldModel();
$field->type = FieldType::PlainText;     // Does something like this exist?
//  …

I can't find such a class or any other listing of existing field types, where do I?

Unfortunately, a list of string identifiers is missing on the guide for plugin development and field types. The list of field types only tells me which field types exist but not what identifiers they have.


texts: renderTemplate in a plugin for front end request using front end template

texts:
I want to be able to render a template in the main 'templates' directory from within a plugin controller.

Basically the controller gets the url request, does some work and then renders a template saved in the 'craft/templates' directory instead of the 'plugin/templates' directory.

I have tried the plugin path trick mentioned on this page https://craftcms.com/docs/plugins/templates without any success.

Any ideas?


texts: Deprecation Warning: Use the all() function to fetch the query... in PHP

texts:
I am getting this warning message:

"Looping through element queries directly has been deprecated. Use the all() function to fetch the query results before looping over them.  "

It is pointing out all lines that have a PHP foreach function (not twig).

Below is one example of many other functions using the normal PHP foreach.

The code works and produces no front error messages.

This file was created in /config/myfolder/Something.php used as a custom class for "Element API"

function myForEach($arr)
{

    $a_parent         = array();
    $a_child          = array();
    $a_accepted       = array('slug','title','groupId','id');

    // Foreach category assigned
    foreach($arr as $key => $value){

        // Foreach category values eg, uri, title etc.
        foreach($value as $k => $v){
            $a_child[$k] = $v;
        }

        // Too many items so only accept specifics stated at $a_accepted
        $f = array_intersect_key($a_child, array_flip($a_accepted));

        $a_parent[$key] = $f;

    }

    return $a_parent;
}

How can I adjust my code to clear this deprecation warning.


texts: What's the best way to create public profile and content forms?

texts:
It's great to have Craft CMS on SE at last!

We're working on a Craft site that'll allow public visitors to register, maintain a profile, and create entries in an Events channel.

Should we create individual user templates (signup, profile, content), or is there a more automatic way to do this with Craft?

For example, some of our profile fields are dropdown menus, but they don't seem to render as form dropdowns without us manually recoding them to do so. Is this correct?

Look forward to some great answers!


texts: How do I check if a structure has any entries at level 3 when I'm at level 1?

texts:
I'd like to output a special link in level 1 upon current top-level entry doesn't have any entries at level 3. If It have move that special link one level above.

To picture it:

Page 1

Subpage 1
Subpage 2
Special link A

Page 2

Subpage 1

Subpage 1.1
Special link A

Currently I didn't have any difficulties with level 2:

{% set lvl = entry.level %}
{% if lvl == 2 and entry.children|length %}
    A link
{% endif %}

To set that special link at level 1 is.
Most logical way to me is to use EntryModel's method getDescendants( distance ) as I don't have to set any variable. If I understand it correctly It should get descendant entries at given level? of a current entry's variable.  When I set to (distance) other integer than 1 let's say 2 It prints out all entries from second level including level 2. So It's unclear to me what distance does in this case.

{% if lvl == 1 and entry.getDescendants(2)|length %}
    A link
{% endif %}

Argument is true even if there are no descendant entries of second level. Because When looping in It prints all entries from second level up including second level as I mentioned before.

Or I can't use this method?


texts:
I'm trying to install Sprout Report plugin, so I downloaded from here
so I followed the instructions from the plugin documentation site: here
According to that documentation the zip folder from GitHub just need to be placed on craft/plugins folder but after I do this the plugin still does not show on dashboard.
Do I have to do something else so it can be displayed?
Also the zip file from GitHub gives me a folder name: craft-sprout-reports-1 but according to the official documentation the plugin folder's name should be named as: sproutreports
Will be the name of the folder the reason why it's not showing?
Thanks for any help.
plugin-sproutreports
plugin-sproutforms


texts: Help developing point system for sports league (w/o plugins)

texts:
I'm in the middle of a very long project developing a league site for the National Collegiate Wrestling Association in my spare time (once finished, could be a great showcase for Craft).

Currently, I'm trying to implement a points system, where athletes accumulate points based on the matches they win & how they win them.

Here's a screenshot of an athletes stat page (wip) http://cl.ly/image/3L2A0e2x1q3v

All the results are tied to an event, so the points can be recalculated easily if an event has to be removed for whatever reason, or a coach inputs the wrong kid by accident.

There is quite a bit of logic being done here, but manageable, and can be cached- but teams also accumulate points based on the points of the top 11 athletes in their roster!

This means the points will have to be calculated and displayed on

The Team's page (11x the queries)
The Index page of all Teams

Currently, the only way I know how to do this, will be some heavy nesting of conditionals in loops- repeating the process of each athlete.

I know doing it this way, all in the templates, is extremely unorthodox. I'm 99.9% this would be much easier to implement with plugins somehow, but unfortunately I don't know PHP nor do I have the time to invest in the trial/error learning process of how to write plugins in the time needed. So I'm kinda up against a wall here and looking for solutions to smooth out this process, regardless of how hacky it may be.

Maybe there's a way to only perform these massive queries in the middle of the night, and the points total only updates once per day, no matter how many results are inputted in the 24-hour period? I don't know. Please help me, very kind Craft community :)

Update: Added requested template logic... Removed extra unnecessary code for readability & sake of space. Team pages & Teams Index page won't require all the information displayed in screenshot (date, opponent, score/time, pt diff)

{% set athlete = craft.users.id( craft.request.lastSegment ).first %}
{% set results = craft.entries.section('results').relatedTo({
    targetElement: athlete,
    field: 'matches',
}) %}
{% set points = 0 %}
{% if results|length %}

  {% for result in results %}
    {% for block in result.matches %}
      {% if (athlete.id == block.winner.first.id) or (athlete.id == block.loser.first.id) %}

          {% if block.winner|length and (athlete.id == block.winner.first.id) %}
            {% if (block.result == "Maj") or (block.result == "Dec") %}
               {% set points = (points + 5) %}
               {% set difference = "+5" %}
              {% else %}
                {% set points = (points + 6.1) %}
                {% set difference = "+6.1" %}
            {% endif %}
          {% endif %}

          {% if block.loser|length and (athlete.id == block.loser.first.id) %}
            {% if athlete.id == block.loser.first.id %}
              Lost by {{ block.result.label }}
                {% set points = points - 1.75 %}
                {% set difference = "-1.75" %}
                {% set negative %}{% endset %}
            {% endif %}
          {% endif %}

      {% endif %}
    {% endfor %}
  {% endfor %}
{% endif %}

{% set tournaments = craft.entries.section('results').relatedTo({
  targetElement: athlete,
  }) %}
{% if tournaments|length %}
  {% for tournament in tournaments %}

    {% if tournament.type.handle == 'minorTournament' %}
      {% for w in 1..3 %}
        {% for p in 1..3 %}
          {% if (tournament['w'~w~'p'~p]|length) and (tournament['w'~w~'p'~p].first.id == athlete.id) %}

            {% switch loop.index %}
              {% case "1" %}
              {% set points = (points + 6) %}
              {% case "2" %}
              {% set points = (points + 4) %}
              {% case "3" %}
              {% set points = (points + 2) %}
            {% endswitch %}

          {% endif %}
        {% endfor %}
      {% endfor %}
    {% endif %}
  {% endfor %}
{% endif %}

Points:>{{points}}


texts:
I'm quite new to Craft CMS and have takeen over an application (using Twig templates).  I'm trying to run a filter but not having much joy so maybe I might get some help!

So, there is a people section (craft.entries.section('people')) with over 1000 entries. These are displayed in an HTML table, each row has 3 columns (handled using the batch() call). I want to exclude certain entries that match a particular condition.

For example, I want to exclude all 'people' that partially match a list of names (e.g 'xyz', 'zzzz', 'joebloggs')

{% for people in craft.entries.section('people').order('title asc').limit(500)|batch(3) %}

Is it possible to do a query like this before the loop? Or is it something I need to check on each iteration inside the loop? Doing this might make the batch() unusable?


texts:
When I reset my password with the same password I used before.
I checked the MySQL database the old encrypted password is different from new encrypted password.

Do you guys know why?


texts:
I have decided to use Structures as a section type for a section of our site. Can anyone point me to some good documentation for this?

In particular I have set up a structure and I have an _entry.html and an index.html file in a directory for the structure section. When I call the url domain.com/mystructure I am served a 404 error page instead of the index.html page.


texts:
I haves dev setup of a site that i want separate craft config, db and plugin folders for.

define('CRAFT_CONFIG_PATH', '../../../craftdevconfig/');
define('CRAFT_PLUGINS_PATH', '../../../craftdevplugins/');
define('CRAFT_STORAGE_PATH', '../../../craftdevstorage/'); //'../storage/');
define('CRAFT_TEMPLATES_PATH', '../craft/templates/');

I am trying to debug a plugin in craftdevconfig.

However I am having a nightmare knowing where craft is looking.
For my plugin it seems to get its default configuration from the live craft/plugins folder. But for code changes, seems to change its mind about where the plugin service calls should be found. I can debug it locally as it has IP based service calls to third parties. Slowly going bald.

Any ideas on how to clarify where craft thinks stuff is would be great


texts:
Craft 2.6.2999

I have two channels that I've set to structure. In my local install I can drag/drop entries no problem. HOwever on the staging server the drag drop function doesn't work - there are no handles and the entries look like they are a regular channel.

I've tried changing the section type to channel and back to structure but no change.

Please advise


texts: Path to asset file shows "Template not found!"

texts:
I have a headless Craft CMS site and now the frontend development should start.
I have absolutely no frontend or templates as I only worked on the backend.
The asset url got created at /images. If for example the file 1.jpg got uploaded it should be shown in example.com/images/1.jpg when I click on view in the file manager in Craft.
Sadly I get the error Template not found when I only want to see the uploaded file or rather get access to the file.
What can I do to get access to the assets from my asset link /images?
Thanks in advance!


texts: Ajax pagination not loading last entries if not equal to pagination number

texts:
I've got ajax working on a page but if the number of articles is not exactly 3 (this is the pagination limit) then the remaining 1 or 2 entries do not get loaded. I'm not sure why or how to resolve this.

I used this post as a guide to my code.

My js code is here:

  {# set current url so we can page with the correct entries #}
  {% set current_url = "improve-your-club/topic/" ~ craft.request.getSegment(3) %}

  $(function () {

      // load the first page of entries
      var page = 1;

      // set this equal to pagination number
      var count = 3;

      // Get the total count that we set above
      var totalCount = $("#totalRelatedCount").val();

      $('#loadMore').click (function (e) {
          e.preventDefault();

          if(count < totalCount){
            $('#loading').fadeIn();

            $.get( "/{{ current_url }}/p"+page , function( data ) {

              $( ".remaining .feat-box-container" ).append( data );

              // this won't hide why not?
              $('#loading').fadeOut();

              // increase page
              page++;

              // Increment count by 3 entries
              count = (count) + 3;

              // Check if count is greater than or equal to the total count. If so hide the load more button.
                if(count >= totalCount){
                    $("#loadMore").fadeOut();
                    console.log('count is larger than total count');
                }

            });
          }// endif

      });
  });

I've recorded a gif showing that the page only loads the first 6 entries despite there being 8 entries available to load - dropbox link to gif (too large to upload here) https://www.dropbox.com/s/79datzwa2qktpi0/ajax.gif?dl=0

** link to pastebin with full template** https://pastebin.com/cNUJW4xr
removed google tags from this template but otherwise intact


texts: Check if a value exists in a Matrix field

texts:
http://sanderson.brycekirk.com/floor-plans/1-bedroom-1-bathroom/f123-f148-f248

This page displays a floor plan, of which there are many. Currently, within each floorplan entry, you add the floors it is on, along with the image of each floor:

I'm using a for loop to display a big button for each available floor, as you can see on the linked page.

My problem: I want to add disabled buttons for each floor the floorplan isn't on, but I can't figure out how to do it.

The logic should be something like this ("floors" is the name of the matrix field, "floor" is the block type handle):

IF '1' exists in entry.floors.floor.floorNumber
    Show the big selectable '1' button
ELSE
    Show the disabled '1' button

IF '2' exists in entry.floors.floor.floorNumber
    Show the big selectable '2' button
ELSE
    Show the disabled '2' button

etc for 3 and 4

It seems like their should be some straightforward solution, but I've had no luck.

Current code for displaying the floor number buttons:

{% for floor in entry.floors.all() %}
{% if floor.type.handle == 'floor' %}

{% endif %}
{% endfor %}

Floor matrix:


texts: Undeleting entries (or restore previous version of deleted entry?)

texts:
Is there a way to "undelete" an entry that has been deleted? (Kind of like the "Trash/Recycling Bin" functionality of our computer OS.)

I don't see any obvious way to do this, but since Craft Pro has page versioning it seems like perhaps there should be a way to restore an old version of a page that has since been removed?


texts: How to create a faceted search/facet filter in Craft Commerce

texts:
I want to create these kinds of filters on my Craft Commerce site:

I have poked around with the Faceted Navigation plugin, but haven't gotten it to work the way I want yet (posted an issue about high bandwidth usage) (Fixed in version 1.1.80), and it seems to work nicely- and it's quite fast. However, I wanted to check out 3rd party enterprise search as-a-service.
I also see there is pretty good support for a third party enterprise search service called Algolia through the Scout and Algolia plugins. I have no previous experience with Algolia, but it seems that they should be able to spit out these kinds of filters.
There also seems to be a somewhat abandonned plugin called Search Plus (which I believe stalled at Craft 2.5) and the ElasticSearch-plugin which also seems to be stalled because of a dependency on a YII2->ElasticSearch plugin.
So... should I build my own? NyStudio107 talks about using React with the GraphQL API or the Element API and Webstoemp has an example of building this using Twig.
How would you go about doing this?