texts: Creating a sitemap/index page, ordered by A-Z and 0-9

texts:
I'm created an Index like page (like at the back of a book) for entries within a certain section, ordered alphabetically with the letter proceeding it.

My code below seems like a tedious way to do it, is their an easier way?

How would I handle the entries with a number as the first character (0-9) of the title?

A

      {% for entry in craft.entries.section('artists').search('title::A*').order('title').find() %}

...

        {% endfor %}

B

      {% for entry in craft.entries.section('artists').search('title::B*').order('title').find() %}

...

        {% endfor %}

C

      {% for entry in craft.entries.section('artists').search('title::C*').order('title').find() %}

...

        {% endfor %}


texts:
I am using the Dukt Twitter plugin and want to display the time since the tweet was created.

The Twitter API returns a string in the format:

Fri Sep 02 14:42:42 +0000 2016

I can use the date filter on this string to alter the format, but cannot pass this through the diff method that twig exposes. I think I need to create a dateTime object, would this require a plugin to be created for this task or can I achieve this in twig?

A reference post on this forum discusses the diff method: Get Age from Date of Birth - however I think I need to have a date object, not a string, to use it. Ideally I'd like to just achieve this in twig as I have never written a plugin before! Thanks


texts: How to display an asset (pdf) from both site languages on both sites?

texts:
How do I display an asset (PDF) from both site languages on both sites? I would like to offer both German and English versions of a PDF on both the English and German sites.
I now have {{ entry.PDF.url }} and wondered if I can add a .site() direction to the entry query.


texts:
I successfully imported my tumblr blog with the amazing Feedme plugin over the rss feed of the blog. The plugin creates posts and feeds the "title", "date", "tag" and of course the "content" inside my craft and I can assign a field to each of those elements.

Here is the thing: The images in tumblr are included in the content. Feedme isnt able to crawl for img tags and make an asset out of it in craft. So the images are still on tumblr and are just linked in the html:

für Hotels und Gastronomie.

Does anyone have an idea how I can get the first image in my template? the prettiest solution would be of course if I find a way to make it an asset. But if not, it would be nice if I could crawl the html content for img tags and get the link to the image on the tumblr server......


texts: Show events in month by specific category - Solspace Calendar

texts:
I've set up a category field for events. Multiple categories can be chosen. And I've set up a form to "filter" events to a specific category using query parameters.

The URL looks something like this (simplified; region is the category):

domain.com/events/month?&region=portland

Is there a way to show events that pertain to the category param in the month view?

Been banging my head and can't figure it out.


texts: How can I populate a dropdown via Globals?

texts:
I have a registration form that has a dropdown that allows the user to choose a color. This form input will be the same across all pages that allow a user to register.

So, I thought using a Global to populate that dropdown would make sense as the client could manage the color choices. In essence, this is what I'm trying to do:

{% if colorOptions.color | length %}

        Color Option
        <select id="colorOption" class="form-control">
            <option value=""> Select</option>
            {% for option in colorOptions.color %}
                <option value="{{ option }}">{{ option }}</option>
            {% endfor %}
        </select>

{% endif %}

But I'm struggling with what kind of field type color needs/should/could be within the colorOptions group.


texts: Troubleshooting Slow Craft Website - New Relic

texts:
I am troubleshooting a client website and I have installed new relic on VPS.

Summary:
RESP. TIME = 12,300ms
USER CPU BURN = 7,000ms (56.9%)
SYSTEM CPU BURN = 115ms (0.935%)

Slowest components  Count   Duration    %
YiiBase::autoload   116     2,570 ms    21%
Craft\ElementsService::buildElementsQuery   175 1,960 ms    16%
Craft\ElementsService::findElements 175 1,690 ms    14%
Craft\BaseElementModel::setContent  153 1,300 ms    11%
__TwigTemplate_8a189a6b8bb1cda953a4a38f8aa3c4ccaccd30c1b5a2b790673a05284bb0de6b::block_menu 1   519 ms  4%
Composer\Autoload\includeFile   19  432 ms  4%
Remainder   1   3,840 ms    31%
Total       12,300 ms   100%

I have attached a trace.

It looks like a lot of time is spent on autoload. Any ideas what will cause this? Or what should I be looking at to fix this issue?


texts: Multiple contact forms - Different recipients

texts:
I'm creating a website that has a contact form on two different pages.

I am using the Pixel & Tonic ContactForm plugin and currently have a working contact form on one page - This one requires the user to provide their name, email, telephone, company name and message.

On the other page, the contact form is different as the user needs to select which department they would like their message to be sent to. For example:

  <div class="select-wrapper">
   <select name="department" id="department">
    <option value="">- Please Select -</option>
      <option value="one">Business One</option>
      <option value="two">Business Two</option>
      <option value="three">Business Three</option>
      <option value="four">Business Four</option>
   </select>
 </div>

In the README document for this plugin, I can see that it is possible to programatically add email recipients by adding a hidden input field named “toEmail” and changing the craft/config/contactform.php config file

But, is it possible to do this when there is another contact form on the site?
If so, what do I need to add to the department dropdown code?


texts: Freeform Pro Plugin Submission to Google Spreadshet

texts: I have a perfectly working form using the Freeform Pro plugin on a CraftCMS 3x installation, however I'd like to allow team members access to the submissions without having to login to the CraftCMS backend. So I was hoping to ask if the Freeform Pro plugin has the capability to copy submissions to a Google Spreadsheet file automatically.


texts:
I'm trying to display results from a search. I want to display the categories represented by the search results and the entry count for that category. Think of how Amazon's "refine results" sidebar works, something like:

  Results listing
  ...

  Categories
  Planning and Funding (9)
  Design (19)
  etc.

I can easily get the count of ALL ENTRIES in each category with this:

{% for category in craft.categories.group('resourceCategories') %}
  {% set entryCount = craft.entries.relatedTo(category).total() %}
  ... do something...
{% endfor %}

However, if I want to get counts for ONLY the returned search results. I've tried this:

{% set resourceEntries = craft.entries(queryParams).section('and, not organizations, not presentersAndAuthors') %}
{% for category in craft.categories.group('resourceCategories') %}
 {% set entryCount = resourceEntries.relatedTo(category).total() %}
  ... do something...
{% endfor %}

But I get the count for ALL entries (the same results as the top example).

Any idea as to what am I missing or not understanding?


texts: How do I create a structure side navigation that will show active parent list-item and active child list-item

texts:
A bit of a background on the project. I have a features structure section, that has 2 levels: Parent features & Child features.

{% set features = craft.entries.section('features').all() %}

My goal is to get an active class on the parent if the parent page is active or if it's got a child that is active and also get an active class on the child if its active.

The {% children %} tag doesn't allow for custom HTML.

I am looking to get something similar to this left navigation. But instead of anchors, each feature will be its own page.
https://craftcms.com/features/all#section-types

Thanks


texts:
I get the following error upon submit of the contact form (Pixel and Tonic's version).

  proc_open() has been disabled for security reasons

Using Craft 3.0.5 and Contact Form 2.1.1. Email is being sent by Sendmail

Client's website host are not willing to enable proc_open. Is anyone aware of a simple way around this?

Here's the Stack Trace:

yii\base\ErrorException: proc_open() has been disabled for security reasons in /home/blahblah/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php:296
Stack trace:
#0 /home/blahblah/vendor/craftcms/cms/src/web/ErrorHandler.php(84): yii\base\ErrorHandler->handleError(2, 'proc_open() has...', '/home/blahblah/...', 296)
#1 [internal function]: craft\web\ErrorHandler->handleError(2, 'proc_open() has...', '/home/blahblah/...', 296, Array)
#2 /home/blahblah/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php(296): proc_open('/usr/sbin/sendm...', Array, Array)
#3 /home/blahblah/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php(58): Swift_Transport_StreamBuffer->establishProcessConnection()
#4 /home/blahblah/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(126): Swift_Transport_StreamBuffer->initialize(Array)
#5 /home/blahblah/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php(52): Swift_Transport_AbstractSmtpTransport->start()
#6 /home/blahblah/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php(67): Swift_Transport_SendmailTransport->start()
#7 /home/blahblah/vendor/yiisoft/yii2-swiftmailer/src/Mailer.php(151): Swift_Mailer->send(Object(Swift_Message))
#8 /home/blahblah/vendor/yiisoft/yii2/mail/BaseMailer.php(263): yii\swiftmailer\Mailer->sendMessage(Object(craft\mail\Message))
#9 /home/blahblah/vendor/craftcms/cms/src/mail/Mailer.php(159): yii\mail\BaseMailer->send(Object(craft\mail\Message))
#10 /home/blahblah/vendor/craftcms/contact-form/src/Mailer.php(100): craft\mail\Mailer->send(Object(craft\mail\Message))
#11 /home/blahblah/vendor/craftcms/contact-form/src/controllers/SendController.php(51): craft\contactform\Mailer->send(Object(craft\contactform\models\Submission))
#12 [internal function]: craft\contactform\controllers\SendController->actionIndex()
#13 /home/blahblah/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#14 /home/blahblah/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#15 /home/blahblah/vendor/craftcms/cms/src/web/Controller.php(76): yii\base\Controller->runAction('', Array)
#16 /home/blahblah/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('', Array)
#17 /home/blahblah/vendor/craftcms/cms/src/web/Application.php(272): yii\base\Module->runAction('contact-form/se...', Array)
#18 /home/blahblah/vendor/craftcms/cms/src/web/Application.php(520): craft\web\Application->runAction('contact-form/se...', Array)
#19 /home/blahblah/vendor/craftcms/cms/src/web/Application.php(256): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#20 /home/blahblah/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#21 /home/blahblah/web/index.php(21): yii\base\Application->run()
#22 {main}


texts:
I am trying to add eager loading to a query. The original query was as follows (‘sticky’ is a custom lightswitch field for marking sticky entries):

{% set news = craft.entries.section('news').order('sticky desc, postDate desc').limit(9) %}

Is the following ok syntax for adding eager loading?

{% set news = craft.entries.section('news').order('sticky desc, postDate desc').limit(9).find({
    with: [
        ['newsHighlightImage', {
            withTransforms: ['newsMedium', 'newsSmall']
        }]
    ]
}) %}

I ask because although the above seems to work, in the examples in the documentation, the find/with bits come right after the section parameter. But if I do it that way, I get an error about not being able to apply the “order” method. I reckon that’s because find() turns the result into an array so “order” is not longer available. But I couldn’t figure out the correct carry syntax to make it work that way. Is there a better way to do this?

Thanks!

Willhaus


texts: Craft 3 - Plugin - Override Control Panel column values for field or field types

texts:
How can I override the column value for a plugin in the Craft CMS control panel?

For example:

Append "Hello " in front of a particular column value, or add hyperlink HTML markup to a value, in each row where the value makes a particular condition.

For the life of me, I can't figure out how to hijack column values!


texts:
I have a site setup using a single article detail page for multiple channels. Each channel has a different category group and I need to output the categories as breadcrumbs

so it would ideally look something like this

category 1 > sub category (if exists) > entry title

Different category fields include:

businessIntelCategories
learnCategories
trainingCategories
savingsCategories

Not sure how to proceed.


texts:
I've tried the LanguageLink and the last solution described here: How can I build a language switcher? but it never returns any URI. I'm not using translated slugs.

As setup I've used: http://buildwithcraft.com/docs/localization-guide. The language dropdown is part of top.html which I've included in each page

Things I have checked:

/config/general.php and that looks fine
index.php in public_html/stagingtest/ (for english) and public_html/stagingtest/es/ and public_html/stagingtest/nl/ and appears to be ok
when I go to www.example.com/stagingtest/es/report/ its loading fine. craft.locale appears to be ok, but the language uri's are still blank. I can see siteUrl is displaying the correct uri.

Any suggestions?


texts:
So we are moving to Google App Engine Flexible which means we cannot store sessions on files. So I wanted to know if anyone has been able to make Craft 2 Stateless and how was it accomplished?

Thanks.


texts: Dymanic 'active' class using nav tag looping through a structure

texts:
My question is related to this page... How can I add a dynamic "active" CSS class to the navigation on any given page?

Thank you in advance my code is the following:

    {% nav menu in craft.entries.section('mainMenu') %}

            {{ menu.title }}

    {% endnav %}

I am using Ben's code from this page but I am struggling to get this method working. I was wondering if someone could help me get to the bottom of this. I assume menu.id does not match entry.id and therefore the class is not added but how can I check the two id's are matching?


texts:
I have a content site and I want to launch a department store, but I have over 5000 products.

I want to launch a department store with Craft CMS; of course, my blog's section is WordPress.

Is this possible?


texts:
To get around a temporary issue where two urls go to the same site, I wanted to set all my site links to be relative rather than using the full url. Looking through the Craft docs I found that it's apparently possible to place something like this in the index.php file:

define('CRAFT_SITE_URL', "http://{host}/");

However this didn't seem to work - I just get '{host}' appearing in all my links. Instead I set the site url as below, which has had the desired effect...

define('CRAFT_SITE_URL', "/");

...but is this a bad idea?


texts: Building a simple search by multiple categories

texts:
Is it possible to build the following/is it the right way in Craft. Been through the docs and searched but stuck.

I just need to build a form on one page with a dropdown select for 2 categories;

Location
Type

That then takes the user to the results page and returns entries where the location and type match.

Can someone be so kind as to provide a sample to get me going please?


texts:
Seems like a very obvious (and missing) feature, but maybe I'm missing something. If we have a generic "page" template how could an editor (as in someone not confident with using settings) just create a new single page?

E.g they may have singles for about, history, faq's etc but then want to add a new "page" for a one-off thing. Right now the developer has to create a new single in settings for them which is really clunky.


texts: When sending email notifications to users via FreeForm, the recipient's name is a zero; see screenshot. Looking at the documentation, it doesn't appear I can set the recipient's name in the heading comment block. Thoughts on why this "0" is appearing as the user's name? Is there any way to override it?


texts: P&T Contacform plugin: what's the use of the errors if fields are not required?

texts:
In the Contactform plugin page there's a code example that's confusing me.

Only the email and message are required in the code, but the fromName field does have an error syntax:

<input id="fromName" type="text" name="fromName" value="{% if message is defined %}{{ message.fromName }}{% endif %}">
{{ message is defined and message ? errorList(message.getErrors('fromName')) }}

What's the use of the getErrors here? I've tried using rare characters, but no errors?


texts:
Following this topic, I have an additional question.

The results are not ordered by the order of the Dropdown Options.
How can I get this done?

Code:

{% set players = entry.myPlayersMatrix %}
{% set playersGrouped = players|group('myPositionDropdown.label') %}

{% for position, playersInPosition in playersGrouped %}

{{ position }}

    {% for player in playersInPosition %}
        {% set playerData = craft.entries.section('myPlayersChannel').relatedTo(player).first() %}

            {{ playerData.fullName }}
            {{ playerData.age }}
            ...

    {% endfor %}

{% endfor %}


texts: Store a redirect URI for use after login

texts:
I need to pass the current page's URI into either the HTTP headers or as a URL query string so that after being taken to the login page and successfully logging in, the user will be sent back to where they came from.

I think that by attaching a query to any login button around the site I can then tell the login page where to go. The Login button is part of many of my templates / partials show when conditionally displaying content depending on if user is logged in.

By using <a href="members/login?p={% craft.request.path %}">

For example I thought that:

{% if craft.request.getQuery('p') and craft.request.getQuery('p')|length %}
    {% set p = craft.request('p') %}
{% else %}
    {% set p = '/' %}
{% endif %}

would set me up to redirect if the url contains http://craft.fira/members/login?p=/members/directory/json. However that results in a 404. Is there a safe way to pass a path into a url query?

Secondly, I then need to know how to deal with this after logging in successfully.

All help greatly appreciated, thank you!


texts: Is there a way to send offsite backups of the whole site to Amazon S3?

texts:
I used to use a plugin for ExpressionEngine called "Backup Pro" (http://devot-ee.com/add-ons/backup-pro) that would allow me to backup the entire file system and database to an offsite location like Rackspace or Amazon S3.

Is this functionality built into Craft anywhere or does a similar plugin exist?


texts:
I'm trying to extend the ElementCriteriaModel using the guide here:

https://blog.tighten.co/craft-cms-building-complex-queries-by-extending-the-elementcriteriamodel

However I need to re-implement relatedTo keyword somehow. This is what I have so far but doesn't seem to work at all

    $criteria = craft()->elements->getCriteria(ElementType::Category);
    $criteria->slug = 'seasonal-event';
    $criteria->limit = 1;

    $category = $criteria->find();

    $this->criteria->relatedTo = array(
        'targetElement' => $category
    );

    return $this;


texts: Struggling with language switcher for Craft 3

texts:
I am using SEOmatic helper class to get localizedUrls which is making life much easier! I would like to only display the localizedurl if the current entry is enable on that site. Below is what I have, has anyone successful done this for craft 3?

{% set currentSite = craft.app.sites.currentSite %}

{% set currentSiteLanguage = currentSite['language'] %}

{% set localizedUrlsArray = seomatic.helper.getLocalizedUrls() %}

{% for localizedUrls in localizedUrlsArray %}

{% if currentSiteLanguage != localizedUrls['language'] %}

    {% if entry is defined %}

        {% if entry.enabledForSite %}

             {{ localizedUrls['language'] }}

        {% endif %}

    {% else %}

         {{ localizedUrls['language'] }}

    {% endif %}

{% endif %}

{% endfor %}


texts: craftcms/vue-asset Related Error on Craft and Plugin Update

texts:
When updating my plugins or craft I get the following error...

Error: The "https://composer.craftcms.com/p/nystudio107/craft-imageoptimize-imgix/c642ab1cfc1bf5e4c9c3c265837b1e5201a6ed55436f1bbb47558a9c63a49384.json" file could not be downloaded (HTTP/1.1 404 Not Found)

Composer output: Package "craftcms/vue-asset" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies

Doing a google on craftcms/vue-asset - it looks like it is depreciated - so I'm not sure why I would need it.


texts: Can I eager load Super Table fields in a Matrix block?

texts:
I have a Matrix with a Super Table in many of its blocks that I'm trying to eager load, but I can't figure out the syntax (or if its possible). The Super Table field's handle is columnSize and it contains two rows with dropdowns, screenSize and columnSize. My Matrix's handle is contentBlocks. The template code is below:

entry.contentBlocks.with(
    [
        'text:columnSize', // Super Table field
        'image:columnSize', // Super Table field
        ['image:image', {
            withTransforms: [{width: 1600, width: 1024, width: 768}]
        }], // Asset field
        ...
    ]
)

The syntax above works for every field I have except columnSize, which returns empty in the template when loaded using this method. Are there additional parameters needed for Super Table similar to image transforms?


texts:
I'm trying to attach a custom header image for each entry, if none is selected then the default one will be displayed.

contentBuilder is the Matrix field.
imgHeader is an assets block type.
img is the actual field

{% for content in entry.contentBuilder.type('imgHeader') %}

    {% if content.img|length %}
        {{ content.img.first.url }}
    {% else %}
        default jpg
    {% endif %}

{% endfor %}

However this doesn't work. Please advise :)


texts: Permissions at field level. Can this be done?

texts:
I have a public registration form process which assigns a specific group/permissions 'eventeer' to a user. This user can then login and can enter/edit information in a 'shared' section. 'Shared' meaning both admins + eventeer groups use the same admin cp section form.

Issue: I have one field that I dont want to expose to an 'eventeer' but only expose for admin. Can this be accomplished with craft v2.6+ and/or plugin?

Thanks in advance.


texts:
I am attempting to create an 'a to z' listing on a site with 1000+ entries of people. The catch is that it needs to be indexed by surname unless that person doesn't have a surname, in which case it will use their forename.

I know what I need to end up with — an array of 'a' to 'z' as keys, with the value another array of people, indexed by their name with the entry id as the value. I can then iterate over this and create the relevant sections for styling.

Is this even possible in Twig? If so, how?


texts: How to import entries from Craft 2 to Craft 3?

texts:
So, I've been working on a Craft 3 upgrade, managed to set everything up, including configuring new plugins etc. Since I've started working on the upgrade process, some new entries have been published on the original site (running on Craft 2).

What's the best way to import only the blog entries from the latest database dump? I tried to replace the craft_content table in the database, but that doesn't seem to work well - I assume the table structure is different on Craft 3?

Is there maybe any plugin for doing such thing?

I also thought of getting the fresh DB dump from the live site, converting it to Craft 3 and then replacing the craft_content table, but I'm not convinced if that's the best way to do it.

Or maybe I should replace some other tables too? Couldn't find any DB description in Craft documentation.

Thank you.


texts: Exclude path in NGINX config (for FastCGI Caching)

texts:
I've got a Craft 2 site on an NGINX server that uses FastCGI Caching (based on Static Page Caching with Craft CMS), but I've got a few pages that have some dynamic content that I'd like to exclude from the cache. I understand I can do this within the NGINX config, but my client has asked if they can somehow manage this within Craft.

I've tried doing this with headers and cookies, but haven't had any luck yet. What I think is happening is that these things are set after the request is made.

Is there a way to use a plugin that can get information on which path to exclude into my NGINX config on a per-path basis? If so, where would be a good place to start?


texts: Getting all content, including Matrix fields from an EntryModel

texts:
Initially I was doing $entry->getContent()->getAttributes(), but noticed my Matrix fields were all null.

What is the right way to do this?

I see that $entry->myMatrixField gives me the ElementCriteriaModel for my Matrix that I need, I thought that would be the same as using `getAttribute('myMatrixField'), but i guess not.


texts:
I've setup multi domains with a single Craft 2 core folder using the Path Constants methods in the docs. It's seems like a nice setup as I only have to update the core Craft files once when there's an update for all the domains. But under this setup all the domains have their own separate control panel and plugins but share the core Craft app folder.

The reason I've done this is that my client wants to be able to add micro sites in the same install as their main company site for specific marketing.

However, the licensing of Craft says that: You’re allowed to run a single Craft license on multiple domains (e.g. example.com and example.fr), so long as they’re all a part of the same website. In order to enforce that, Craft does have one technical limitation: you may only access Craft’s control panel from one public domain per Craft license.

So am I right in assuming that my setup will be ok for example.com, example.co.uk, subdomain1.example.com, subdomain2.example.com, example.fr etc, but if the client wants to use a completely different domain name for the micro site like brilliantmarketingurl.com then the license won't be valid? As each site has it's own control panel and database with this setup.

Is this the case and is this still applicable with Craft 3 introducing multi-sites support?

Would appreciate some advice on this, as I need to discuss the potential implications with my client. Thanks.


texts: Internal Server Error after Craft update through admin

texts:
Anyone ever experience getting this after an update through the admin?

Internal Server Error
mb_strpos(): empty delimiter

And know of a solution?


texts:
Instead of a standard 404 error page, I want to send 404s to the homepage and can't seem to get this working right.

If I add {% redirect '/' %} in my 404.html template, that works except it gives a 302 found code instead of a 404.

If I change it to {% redirect '/' 404 %} I get the correct 404 code but just a white screen instead of the homepage.

I've also tried adding ErrorDocument 404 / to the .htaccess file, but that doesn't take effect as I think the Craft 404 mechanism overrides that.

Can anyone help? Thanks.


texts: Installing and using super-filter plugin

texts:
I'm currently testing the super-filter and I was wondering if someone has experience working with this plugin. The instructions are unfortunately very unclear to me. I've come as far as trying to create a new search setup but I'm dumbfounded by the following

What exactly do I have to put here and what does it do?

The documentation offers the following, but it doesn't make sense to me: "Template Override Folder - the folder of the templates that you'll override to modify html's. The items.twig must be copied to this folder to modify element attributes."

I am also unclear where to put the following code mentioned in the documentation.

    {{ craft.superFilter.setup('searchList') }}

            {{ craft.superFilter.displaySearchFields() }}

            {{ craft.superFilter.displaySortOptions() }}
            {{ craft.superFilter.items() }}
            {{ craft.superFilter.getPaginateLinks() }}
            {{ craft.superFilter.close() }}

Thanks for any hints.


texts: Dynamically setting a channel's Entry URL Format with Craft tags

texts:
I have a Structure section and a Channel section.

Entries in the Channel will be listed on one of the Structure Entries, and it's entry page will fit the same URL format.

So for example, the Structure Entry may be:

Title: "Our People"
URL: /about/our-people"

...and the Channel entry may be:

Title: "Jamie"
URL: /about/our-people/{slug}

When I set up the Channel is there any way of dynamically setting it's "Entry URL Format" based on another entry's URL/slug? I can set it to "/about/our-people/{slug}" but if the Structure entry's slug ever changes it'll be wrong.

I've tried adding the following to the Channel's Entry URL Format field and it seems to work (high fives P&T).

{% set parent = craft.entries.section('site').id('32').first() %}{{ parent.uri }}/{slug}

Is there anything I should be worried about using that? Obviously if that parent entry is deleted things will break. Anything else?


texts:
I'm trying to query entries in a section where the (activities) entry has an item in a matrix field timeSlots -> timeSlot -> startDate.
The startDate must be >= NOW().

$query = Entry::find()->section('activities');

// something like
// $query->where('timeSlots.*.startDate >= NOW()');

$activities = $query->all();


texts:
I'm having a strange problem on a recent craft install. The plugin store doesn't load, and only reports "Page not found".

I've tried another craft install on the same system, and it's working fine.
I tried replacing all core craft files with freshly downloaded 3.0.2 files.
I've cleared caches, ran updates, loosened all permissions to 777 and everything in between.
I've tried two different browsers with cache cleared.
I have only 2 plugins installed: Redactor and Position Fieldtype — but I have those on another install as well and that install is fine.
The logs in /storage/logs don't show any errors. I tail them, and nothing is reported.

Aside from the plugin page, all other craft systems work. Even the backups can run and save locally.

Is there anything else I can try to either diagnose or solve? Feel like I've hit a wall. Any advice is appreciated.


texts: Leave search term active in control panel

texts:
i have to edit entries with the same titles. That's why i search for these titles in the search bar of the control panel, edit the first entry, save it and then search again for the same titles and edit the second and so on. I know i could double click on the entry to open a pop-up but i don't find this convienient.
If i could leave the search term in the search bar until i delete it, that would be nice. Or if there's a function like column autofilter from office programms like libreoffice calc or excel..
Thank you for helping.


texts:
I want something sorted like this:

MyString8
MyString9
MyString10
MyString11

$criteria->order = 'myField asc doesn't get things quite right, as MySQL has not native "natural sorting".


texts: Feed Me: importing google sheet values in matrix

texts:
Is there a way to import data into a matrix field using google sheets?
Ive tried using the delimiter in my fields but only one block is being created.
The docs only mention xml / json.
https://docs.craftcms.com/feed-me/v4/guides/importing-into-matrix.html


texts: Output Radio or Checkboxes with A+M Forms

texts:
Does anyone know how to output a checkbox or Radio Button Group with A+M Forms using the custom HTML option?  I'm assuming it's some kind of loop through the available options?

My static HTML looks like below and i'd like to retain the structure if possible.

Many thanks

  Choose your class type

<input type="checkbox" value="personal" tabindex="4">One to One Class

<input type="checkbox" value="business" tabindex="5">Business Class

<input type="checkbox" value="smallgroup" tabindex="6">Small Group


texts:
User's account has mysteriously vanished and entries default to another user. This has happened multiple times. Not sure what to do so we can not have this happen again. Any help is warranted.

Thanks!


texts: Using Element API to output Super Table fields

texts:
I am building a feed using Element API. I am currently looping through Matrix blocks to get various data (based on the help from this post). One of the matrix blocks contains a Super Table field, with various fields inside of that. Here is the relevant section of my Element API config file.

'transformer' => function(Entry $entry) {
  $contentBlocksArray = [];

     foreach ($entry->contentBlocks as $block){
       switch($block->type->handle) {

         case 'introText':
           $contentBlocksArray[] = [
             'introText' => [
               'body' => $block->body,
             ]
            ];
            break;

          case 'twoColumnText':
             $contentBlocksArray[] = [
               'twoColumnText' => [
                  'columnTextBlocks' => [
                      'icon' => $block->icon,
                      'text' => $block->text
                  ]
                ]
              ];
              break;

The first case in this switch works as expected. 'introText' is the Matrix box and 'body' is a plaintext field inside that block. The second case is where I'm having trouble. 'twoColumnText' is the Matrix block and 'columnTextBlocks' is a Super Table field with two plaintext fields. The api returns a response, but both 'icon' and 'text' = null.

I have also tried calling some of the functions as demonstrated in Super Tables docs here but no luck. I am by no means a php / laravel / etc developer, so I might be missing something that would be obvious to such a developer.

I suspect it's something similar to retrieving images where I have to loop through the Super Table fields, but I don't know what that syntax would look like.


texts: Twig url() function returns CP path when called from plugin

texts:
I'm using Postmaster plugin to handle my e-mails using a custom service for SendGrid. In my templates I use Twig's url() function to create my URLs.

When they are sent by Postmaster, craft->template->render() method creates a Control Panel url instead of a normal front-end URL. Which results in URL's not found when clicked in the e-mail.

Is this normal behaviour when the render() method is called from the control panel? Or can I override this in Twig templating maybe? The Craft docs don't mention it.

In the meantime I can create my URL's using {{ siteUrl }}, but I'm wondering if I'm missing something here.


texts: Plugin Multi-Environment config not working

texts:
I have set up the plugin's multi-environment configuration as outlined in this answer.

The config.php file for the plugin is as follows:

<?php

return array(
    // All
    '*' => array(
    ),

    // Development
    '.domain.dev' => array(
        'apiKey' => 'APIKEYDEVVALUE'
    ),

    // Staging
    'dev.domain.com' => array(
        'apiKey' => 'APIKEYSTAGINGVALUE'
    ),

    // Production
    'dev.domain.com' => array(
        'apiKey' => 'APIKEYPRODVALUE'
    ),
);

But calling craft()->config->get('apiKey', 'pluginhandle') returns null.

If I var_dump(craft()->config) I can see that the config file for the plugin is loaded by craft.

What am I missing?  Please let me know if I can provide any more useful info.


texts: Is it possible to use Twig in a Rich Text Field?

texts:
I have global variables that I want to include in Rich Text Fields, for example:

This is a rich text field, call us today at at {{ phone.number }}!

This doesn't work out-of-the-box, are there any ways of doing this? I am coming from working in another CMS where this was possible to do.

Update: Specifically in this case I the global variable includes a javascript code that dynamically updates the phone number with a tracking number:

<script type="text/javascript">{ document.write(_ibp_phone_number); }</script>


texts:
I noticed the following new feature in Craft CMS 2.6.2973: Added the “HTML Purifier Config” setting to Rich Text fields.

I can't see any mention or any example of config files in the Craft CMS docs for Rich Text fields though, and the only thing I can see in the Rich Text Field settings in the control panel is this:

  You can save custom HTML Purifier configs as .json files in craft/config/htmlpurifier/. View available settings

Can someone help me with a custom HTML Purifier config .json file that I can use with Craft that would allow me to start using YouTube video embed code like this in Rich Text fields?

<iframe width="560" height="315" src="https://www.youtube.com/embed/HdYfAmrzVlc" frameborder="0" allowfullscreen=""></iframe>

At the moment, the above code will disappear when saving an entry unless I disable the Purify HTML? option in the Rich Text field settings. Thanks in advance for any help with this.


texts: Is it possible? I have a situation where a client needs the production site to be completely shut down and void of content updates. They do all of their content management on a staging site, then publish the database when changes are approved.


texts: How do you insert the site name into a default asset path?

texts:
Multisite question.... how do I output the site into the assets path? currentSite won't work because its the admin panel, so the current site is always the default site.
Using the below, I will always get /default/footer-content with this, regardless of which site is having its field edited.


texts: GraphQL mutation or query, how to target specific site?

texts:
Is there a restriction on graphQL that only allows it to work on the primary site?
My system has for unknown reason switched primary (and I can't change it back due to a bug), and ever since then my graphQL mutation fails claiming there is no such entry (switching primary in my dev env fizes the problem).
I figured that the base URL of the api request controlled which site it was querying, but that doesn't seem to be the case either?
I'm using the mutation save_sectionHandle_entryTypeHandle_Entry(). The ID I send in seems to be the same across different sites, so I need some way to distinguish between them to edit the right entry it seems, or in my case, allowing the call to even find the entry...


texts: Can you add duplicates fields in a structured section's GUI?

texts:
Is there a way to duplicate fields when creating "structures" in the visual editor. If I wanted to add four simple textfields, it appears I can't just drag-and-drop four textfields in and give them IDs as that field disappears.

i.e. If I have four tabs with headlines... would I need to create four separate fields called "headline"?


texts: Moved server (centOS7) "Please ensure that $craftPath is set correctly"

texts:
I previously ran Vesta CP on Ubuntu and wanted to run something a little faster so chose centOS7 minimal. Installed Vesta CP and restored my backup. All my sites are running fine. Except for the ones running Craft CMS.
I would like to stress that the backup worked perfectly before
I get the error "Please ensure that $craftPath is set correctly"
Now I'v been (honestly) trying for the past 6 hours to fix this on my own but I can't figure it out.
PHP runs as adminBOB (determent using: )
And checking my chmod the user and group are adminBOB:adminBOB (same as if I make a new folder or upload a new file)
Apache/httpd runs as "apache:apache" changing the owner of all my files for this site doesn't make the error go away either.
I'm also my http.conf (and tried php.ini) configured to have:

php_admin_flag safe_mode off
php_admin_value open_basedir none

So I'm almost certain those two are not on.
Everything (folder/files) wise is the same. Same control panel (that installs all services)
I have no idea what to do next to try and get CraftCMS working again.
Please assist! Thank you!!


texts: Making Craft\DateTime Object from string in Twig

texts:
I'm trying to use Craft's native datepicker with a plugin I've made for the admin section.

I've got some code that works;

{% from "_includes/forms" import date %}

Start Date

{{ date({
    id: 'startDate',
    name: 'startDate',
    value: now
}) }}

but I can't seem to get it to work with any other date, no matter what I do.

In my URL I have;

startDate=09/02/2017

and in my twig template I have;

{% set startDate = craft.request.getParam('startDate') %}

What do I need to do to startDate in order to get the date picker to read that date?


texts: "PHP Warning: var_export does not handle circular references" when devMode = true

texts:
When devMode is true, both the front end and admin of my site give me the PHP warning:

  "var_export does not handle circular references".

I've tried disabling plugins, with no luck.


texts: Unable to call a service method from controller in my custom plugin

texts:
I know there are similar questions here, but I don't see a definitive answer, nor one that works for me.

I've generated a plugin via pluginfactory.io, which has some controllers and a single service.

I can call the controllers in the CP without issue - if I just return a 'Hello world' from any of the controller methods, it works.

But when I follow the example supplied in the code comments (for the service file) inside of my controller action:

MyPluginName::$plugin->importer->exampleService()

I get an exception:

  Unknown Property – yii\base\UnknownPropertyException
  Getting unknown property: amphibian\mypluginname\MyPluginName::Importer

I have a service file called Importer in my services folder, with a class name of Importer, and a method named exampleService().

The extra section of my composer.json file lists:

"components": {
    "importer": "amphibian\\mypluginname\\services\\Importer"
}

What else am I missing?


texts:
Following https://docs.craftcms.com/commerce/v2/adjusters.html I am unable to register an adjuster in my module.

in my Module.php file I have placed the following inside init() alongside other stuff being registered (that are working)

use craft\events\RegisterComponentTypesEvent;
use craft\commerce\services\OrderAdjustments;
use modules\mymodule\adjusters\DiscountAdjuster;

Event::on(OrderAdjustments::class,
    OrderAdjustments::EVENT_REGISTER_ORDER_ADJUSTERS, function(RegisterComponentTypesEvent $event) {
    $event->types[] = DiscountAdjuster::class;
});

And in src/adjusters/DiscountAdjuster.php I have

namespace modules\mymodule\adjusters;

use Craft;
use craft\base\Component;
use craft\commerce\base\AdjusterInterface;
use craft\commerce\elements\Order;
use craft\commerce\models\OrderAdjustment;

class DiscountAdjuster extends Component implements AdjusterInterface
{

    public function adjust(Order $order): array
    {
        $adjustments = [];

        foreach ($order->getLineItems() as $item) {
            $adjustment = new OrderAdjustment;
            $adjustment->type = 'discount';
            $adjustment->name = '$2 off';
            $adjustment->description = '$2 off everything in the store';
            $adjustment->sourceSnapshot = [ 'data' => 'value']; // This can contain information about how the adjustment came to be
            $adjustment->amount = -2;
            $adjustment->setOrder($order);
            $adjustment->setLineItem($item);

            $adjustments[] = $adjustment;
        }

        return $adjustments;
    }
}

This should take 2 off of every line item when I add items to the cart, no? Nothing happens though. And if i put something like die() in public function adjust, that isn't registered either.

What am I missing?

I also tried adapting this example: Demo repo for an Adjuster module for Commerce 2? However I'm faced with the same issue.


texts:
I'm pulling in entries which are the descendant of the current entry id.

This is an example of my structure: Your Adventure > Honeymoon > A trip entry.

The below code is being used on the Honeymoon entry to list any trip entries that are children of the current page.

The below code is working fine apart from the if statement I'm wrapping it all in as I don't want any of the wrapping divs if there are no child pages within 'Honeymoon Trips'.

{% if entry in craft.entries.section('yourAdventures').descendantOf(entry.id)  %}

Available {{ entry.title }}

            {% for entry in craft.entries.section('yourAdventures').descendantOf( entry.id).find() %}

            ...

            {% endfor %}

{% endif %}


texts: Craft CMS Structure: How can I display parent and child items on an active parent page?

texts:
I'm currently setting up a Structure nav and am trying to set it up so that child pages only display if;

1) The child page itself (or it's sibling) is currently active
2) The parent page of that child is currently active

At the moment all I can get working is having the child pages display regardless of what page is active. Even if a page has no children, the child pages are still being shown beneath another parent page, whereas ideally those child pages would not be seen until those pages are become active.

{% set pages = craft.entries.section('about').level('1') %}

{% for page in pages %}
{% set activePage = (entry.slug == craft.request.segment(2)) %}

  {{ page.title }}&nbsp;
  {% if activePage %}
    {% set subPage = craft.entries.descendantOf(page) %}

      {% for child in subPage %}

{{child.title}}

      {% endfor %}

   {% endif %}

{% endfor %}

Is there any solution out there for this as I feel like I maybe close to getting it working. Can anybody shed any light on this?


texts:
Is it possible to turn a query into an element criteria model? Currently I'm doing this:

$criteria = craft()->elements->getCriteria('Conference_Session');
$criteria->conferenceId = $conferenceModel->id;

$query = craft()->elements->buildElementsQuery($criteria);
$query->order("conference_session.cs_start_time ASC");

$queryResult = $query->queryAll();

I would prefer to be able to be able to add my MySQL commands then turn it back into a element criteria. I don't have to do this but I want to know if I could.


texts: Is there a way or a plugin that allows you to add columns and change columns heading from within the entry? Instead of defining column heading while creating the table field. It would be nice to have the ability to add/delete columns and have the table be dynamic.


texts: Conditional to detect mobile devices with getUserAgent?

texts:
I want to create a User Agent check. (Yes I know. It is evil.)

So I created an Array. The whole idea is to see if the user agent contains a specific word. This way I hope to circumvent regex trickery. But I have a hard time figuring how to return true only once:

This would be the array:

{% set browserValues = [ { agent: 'android'}, { agent: 'iemobile'} {# and so on #}]

This is how I get the user agent:

{% set userAgent = craft.request.getUserAgent()|lower %}

I came this far:

 {% for item in browserValues %}
   {% if item.agent in userAgent %}
     You're on mobile
   {% else %}
     You're not on mobile
   {% endif %}
 {% endfor %}

This actually works. But there are two problems: If the conditional is false (not on mobile), the conditional is applied for each key in the array. You're not on mobile You're not on mobile You're not on mobile

If the user agent string contains the word android twice the conditional is applied twice.

How can I prevent the conditional from looping over and over? (My brain starts to loop over and over too).

Thank you.


texts: Express Form: Get submitted data on success page

texts:
I have a very simple question.
In Craft CMS, using Express Forms (free edition), I have a classic scenario.

Page with the form, created by the form.openTag() method
A success page which has '/success' url, and an associated success.twig template file

In the success page, I would like to say something like:
"Thank you {{ surname }}!"
Where {{ surname }} is the surname that user has inserted in the form page, on the input with name="surname".
Is this possible?


texts: Possible to override Garnish.Modal? [Plugin]

texts:
Is there a way to override Garnish.Modal?

For example, I have a custom modal which uses a custom form but I want to be able to use the built in forms.elementSelect to select from a user list. When I select a user and press "select" it closes both my custom modal and my user select window.

Can I override this to just close the most recent modal?

This is in reference to Custom Modals inside Plugins: How can my plugin generate a generic modal window in the Control Panel?

Edit: It looks as if Garnish hides any other modals before loading a new one.


texts: Using ADLDAP plugin in Craft 2.6 - can't bind to LDAP

texts:
I'm working with the ADLDAP plugin in order to provide frontend authentication against my organizations Active Directory.  The problem is that I continually receive the message "Can't bind to LDAP server!" after attempting to log in.

I tested the LDAP connection first on Windows Server 2016, by using the built in LDP.exe utility, and that test proved successful.
Next, I constructed a pure PHP page, and the LDAP binding was successful.
Here is that code:

<?php

// using ldap bind
$ldaprdn  = '*****';     // ldap rdn or dn
$ldappass = '*****';  // associated password

// connect to ldap server
$ldapconn = ldap_connect("***.***.***.***")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

    // verify binding
    if ($ldapbind) {
        echo "LDAP bind successful...";
    } else {
        echo "LDAP bind failed...";
    }

}

?>

In Craft, I carefully followed the installation instructions, per the page: https://github.com/thepitagroup/adldap_craftcms as well as the changes introduced in the thread: https://github.com/thepitagroup/adldap_craftcms/issues/1.
These changes were helpful and got me a little further along, but now, I'm stuck with the error message: "Can't bind to LDAP server!"
The url remains on the 'login' page.

Is there a way to find more detail as to the cause of the error?

Thanks for any help.


texts: How do I dynamically define Asset Volumes' Base URLs for different Sites?

texts:
There must be a simple answer for this but despite fumbling around with it for quite a while and searching the web for answers I am stymied. Perhaps I'm approaching it in the wrong way. I'm feeling like a beginner and I may not be using the right terminology here.

Here is a similar question without an accepted answer: How to setup assets in multi site where each site should have its own assets?

I have two sites, Site A and Site B, with their own assets folder. They are separate sites that will not share assets at all and it would be ideal to keep them completely separate (just as the templates are separated in folders with each Site's handle).

/site-a
-- /site-a-assets
/site-b
-- /site-b-assets

I've seen that @web should not be used for Asset Volumes' Base URL when using multi-site, but I haven't been able to understand how to set up config/default.php to accommodate different addresses for different sites AND different environments (e.g. dev, production). I've seen mention of using aliases but don't understand yet how to make them work with multiple sites to have different values for the same alias depending on which site you're viewing and in which environment.

I have this for my local siteUrl in config/default.php inside of environment settings:

'siteUrl' => [
  'site-a' => 'https://org.site-a',
  'site-b' => 'https://org.site-b',
]

It feels like I'm close but I can't get the pieces put together.

Any pointers you can give will be greatly appreciated!


texts: Would it be possible to create a plugin to warn a user if a page is being edited

texts:
In a previous CMS we used (Processwire), one of the authors created a very useful plugin that would warn a user on an edit page that the page was currently being edited by another user.

I'm thinking this would be a useful addition, unless Craft's use of automatic versioning would somewhat rule out the risk of overwriting someone else's work?

Has anyone had any similar thoughts on the issue?

Thanks.


texts: Force download of asset file from template

texts:
I have a template called download that receives an asset ID, looks it up and should force the browser to download the file. I've gotten this far with the {% headers %} tag, but I can't figure out how to read the raw contents of the file and output it.

{% set asset = craft.assets.id(craft.request.getLastSegment()).first() %}
{% header 'Content-Description: File Transfer' %}
{% header 'Content-Type: '~asset.mimetype %}
{% header 'Content-Disposition: attachment; filename='~asset.filename %}
{% header 'Content-Transfer-Encoding: binary' %}
{% header 'Expires: 0' %}
{% header 'Cache-Control: must-revalidate' %}
{% header 'Pragma: public' %}
{% header 'Content-Length: '~asset.size %}
{# How to print raw contents of asset.url ??? #}

Can anyone help?


texts:
I am trying to show an image that is defined on a category - named photos. I have an entry page with a list of all category entries listed at the bottom. I'd like to show this image but I'm still green on Craft categories and I'm getting errors in dev mode. This is what I have so far:

{% set entries = craft.entries.section('sermons').find() %}
{% for category, catEntries in entries | group('series.first().title') %}

 {% if category.photos | length %} {# if a photo exists, show it #}
    {% for image in category.photos.limit(1) %}
    {% set params = { width: 300, height: 200 } %}

    {% endfor %}
  {% else %} {# if no photo exists, show a default image #}

  {% endif %}

{# output all category entries #}

   {% for entry in catEntries %}

{{ entry.title }}

   {% endfor %}

{% endfor %}


texts: What is the most efficient way to code matrix blocks by type in a template?

texts:
Is this the most efficient way to use matrix in a template where different block types need outputting in various area of the HTML markup? I have 9 block types that need to be placed in various areas of the HTML markup.

{# Create a variable with the matrix fields in #}
{% set var = entry.sofa %}

{# Is the block in the variable #}
{% if var.block.type('twoSeaterSofa') %}

    {# block is in variable #}
    {% for block in var.block.type('twoSeaterSofa') %}
        {# output block #}
        {{ block.price }}
    {% endfor %}

{% endif %}

Grateful for any advice or code.


texts: What are the yaml files in config/project? Should I commit them?

texts: See the title. I'm currently committing the YAML files to our git repo so they deploy to our production server. Is that appropriate? Should I ignore the config/project folder?


texts: Hosting a Craft install in a subfolder of a Wordpress site on Windows IIS

texts:
Alright, I know the question is kind of a doozy but I'm running out of options.

I've uploaded my Craft install to the subdirectory website.com/travel and left in the base web.config that comes with Craft:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
         <rewrite>
             <rules>
                <rule name="Rewrite" stopProcessing="true">
                    <match url="(.+)" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        <add input="{URL}" pattern="^/(favicon\.ico|apple-touch-icon.*\.png)$" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php?p={R:1}" appendQueryString="true" />
                </rule>
             </rules>
         </rewrite>
        <urlCompression doStaticCompression="true" doDynamicCompression="true" />
        <defaultDocument>
            <files>
                <clear />
                <add value="index.php" />
                <add value="index.htm" />
                <add value="index.html" />
            </files>
        </defaultDocument>
    </system.webServer>
</configuration>

I've also moved the Craft/ directory right next to travel/'s index.php.

Visiting website.com/travel/about takes me to Wordpress' 404, however website.com/travel/index.php/about takes me to the correct page.

However, visiting the cp at website.com/travel/index.php/admin removes index.php from the url (but still gives me a Wordpress 404).

I've also tried /index.php/ and /index.php?p= but both results are the same.

I'm not very well-versed in IIS or web.config settings, so I've just been trying things randomly to no avail. Is there something I am missing?


texts: How to replace a html entity within script tags using Craft replace

texts:
Apologies if this has been asked before, I can only find questions dealing with the reverse scenario (i.e. replacing special characters with html entities)

I need to output special characters as part of a JavaScript array using Craft. Currently the values are output with all special characters replaced by their html equivalent. (e.g.: ampersands are replaced by &amp )

I have tried restoring the special characters using craft replace but without success.

The following code works to replace text, but does not, for example, replace &amp with &, or rather perhaps it does not distinguish these values as distinct.

<script>

    var myVariable = [{% for value in myArray %}"{{ value|replace('raw-html-entity', 'special-character') }}"{%- if not loop.last -%},{% endif %}{% endfor %}];

</script>

This code is being used for an array which is used for jQuery autocomplete values, so raw html is not appropriate.

Any suggestions appreciated.


texts:
The project I was working on was put on hold a few months back. Back then I was on version 2.1.2570. Now the project is back on. After having gone through the pain of manually restoring the InnoDB tablespaces because I switched development systems in the meanwhile and didn't bother to do a proper mysqldump, I'm now facing the task of upgrading Craft from 2.1.2570 to the latest revision. It fails while updating the database. Is there any place where I can download older releases (i.e. 2.2.2579) to see if they come through?

Thanks


texts:
I have a Structure section that contains most of the pages on my website.

We have users that need to edit only some of those pages. Since permissions are set on a per-section basis, right now they can edit either all or none of those pages.

How would I go about building custom user permissions for only some of those pages?


texts: Ordering elementtype by custom field throws an error

texts:
In my plugin, when I go to the elementtype index page with the search bar and the dropdown for ordering by certain fields, when I choose a field which has been added through the fieldLayout, the response throws an error.

The problem in the query is in the ORDER BY clause. Specifically: ORDER BY 'field:22'.

How would I go about resolving this issue?
Thanks!


texts: How can I delete all entries that belong to a user?

texts:
It is 100% possible I am going about this the wrong way, so please feel free to correct me.

I have a registration form that creates a user. I have a plugin that is listening to the onSaveUser event:

MyPlugin.php

craft()->on('users.onSaveUser', function (Event $event) {
    if ($event->params['isNewUser']) {
        $entry = new EntryModel();
        $entry->sectionId = 16;
        $entry->typeId = 1;
        $entry->enabled = false;
        $entry->getContent()->title = craft()->request->getPost('firstName') . ' ' . craft()->request->getPost('lastName');

        ...

        if (craft()->entries->saveEntry($entry)) {
            // success
        } else {
            // trouble!
        }
    }
});

Everything works great. The entries I am creating are basically an extension of the user's account (height, weight etc).

I know there are events for deleting a user, but what is the best way to relate the newly created entry so it gets deleted along with the user?

I thought about having an entries field on the actual user account that somehow I populate with the newly created entry?

EDIT

Or, should I have a user field on the newly created entry? In that case, I'm not sure how I populate the newly created entry with the newly created userID.

For example:

...
$user = $event->params['user'];
$entry = new EntryModel();
$entry->sectionId = 16;
$entry->typeId = 1;
$entry->enabled = false;
$entry->getContent()->title = craft()->request->getPost('firstName') . ' ' . craft()->request->getPost('lastName');

// account is the handle of my users field
$entry->getContent()->account = $user->id;  // im not setting this correctly

if (craft()->entries->saveEntry($entry)) {
    // success
} else {
    // trouble!
}

...


texts: Only Install migration is applying on plugin install

texts:
I have a custom plugin which is added via path repository on local.
I have some migrations in the src folder.

My problem is if I uninstall the plugin and install it again, I can see all of the migrations in the migration table, but only Install migration is applied.

If I change the version and schema version of the plugin and remove and require the plugin again, I get update plugin notification on the dashboard and all of the migrations are applied correctly.

also if i create and apply these migrations via command i can see change in databases.

i don't why migrations aren't applied on plugin install -except Install migration-?


texts:
Is it possible to get the Font Color plugin into Redactor?

I tried adding it to my redactor json file as below but no luck.

{
buttons: ['html','fontcolor','table','formatting','bold','italic','alignment','unorderedlist','horizontalrule','orderedlist','outdent', 'indent','link','image','video'],
plugins: ['fullscreen','video','table','fontcolor'],
toolbarFixedBox: true
}

Font Color Redactor Plugin - http://imperavi.com/redactor/plugins/font-color/

I'm not sure what the correct process is to get it working in my Craft admin.


texts:
I am trying to pass an array on template render like this:

public function actionConfirm()
{
   $variables['confirm'] = array(
      'name'   => 'Silvanus',
      'office' => 'OOTS',
    );
    $this->renderTemplate('confirm', $variables);
}

And output it in layout like this:

{%for variable in variables%}
  {{variable.name}}
  {{variable.office}}

This is just an example, mainly after client pays using paypal I get a payment Object that I want to pass it to the confirmation layout as per explanation above. I have tried it doesn't work.

Anyone has an idea on how to achieve this?

Thanks

Cheers.


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

texts:
I'm trying to upgrade from 2.7.10 to Craft 3. I follow the instructions/ docs to the letter, go to https://###.com/admin and am greeted with the above can't connect to database message.

So far, I have pretty much done everything to eliminate possibilities and the conclusion I have come to is that the .env file isn't being loaded. Obviously, I could well be wrong, but I tried a die Hello World on the db.php file and it worked. I put the database details directly into the db.php file and it worked, albeit took me to the current install rather than the upgrade page. I even created a new database (just to try it) and still got the same error.

The db file looks like this:

<?php
/**
 * Database Configuration
 *
 * All of your system's database connection settings go in here. You can see a
 * list of the available settings in vendor/craftcms/cms/src/config/DbConfig.php.
 *
 * @see craft\config\DbConfig
 */

return [
    'driver' => getenv('DB_DRIVER'),
    'server' => getenv('DB_SERVER'),
    'user' => getenv('DB_USER'),
    'password' => getenv('DB_PASSWORD'),
    'database' => getenv('DB_DATABASE'),
    'schema' => getenv('DB_SCHEMA'),
    'tablePrefix' => getenv('DB_TABLE_PREFIX'),
    'port' => getenv('DB_PORT')
];

And the env file:

# The environment Craft is currently running in ('dev', 'staging', 'production', etc.)
ENVIRONMENT="dev"

# The secure key Craft will use for hashing and encrypting data
SECURITY_KEY="*************"

# The database driver that will be used ('mysql' or 'pgsql')
DB_DRIVER="mysql"

# The database server name or IP address (usually this is 'localhost' or '127.0.0.1')
DB_SERVER="localhost"

# The database username to connect with
DB_USER="####"

# The database password to connect with
DB_PASSWORD="**************"

# The name of the database to select
DB_DATABASE="####"

# The database schema that will be used (PostgreSQL only)
DB_SCHEMA="public"

# The prefix that should be added to generated table names (only necessary if multiple things are sharing the same database)
DB_TABLE_PREFIX="craft"

# The port to connect to the database with. Will default to 5432 for PostgreSQL and 3306 for MySQL.
DB_PORT="3306"

Can anyone shed anymore light on how I can resolve this please? I am new to this so please be gentle and let me know if you need more info.
Thanks.


texts: How to populate Category field form frontend form?

texts:
I have a frontend form that has a select list for language. This field will allow for one language to be selected. In the backend I have a field set up for my entries as a category field populated by country categories set as required. I can not seem to get the database to update this category field from my frontend form. The select field is set up as follows for the form field handle language.

<select id="language" name="fields[language]">
    <option value="English">English</option>
    etc
</select>

Anything I am missing to get this to populate correctly.

Cheers


texts: How do I filter / restrict entries field in CP with a category

texts:
Is there a way to restrict the entry field type to specific categories? For example when adding a new field with type "Entries" to select the categories from where entries will be available.

I found this https://github.com/lewisjenkins/craft-lj-dynamicfields which is cool, but offers dropdowns and checkboxes that only work with a single entry. http://screencast.com/t/15nIkpHTQ1


texts:
We've recently set up a Redis cluster to handle our PHP sessions since we use a load balancer to direct traffic into different craft instances.

We're seeing issues with redis when making back to back PHP session calls (using craft wrapper) very quickly. If we update a variable in the httpSession and then try to update it/get it very quickly it isn't updating. If we wait to access it then it is updated correctly.

How it's set up:
We modified the Apache2 php.ini to update the session handler to redis and the save path to our redis cluster (bypassing doing this via Craft). So Craft still uses its' default session handling but when it makes the request to save the session it gets redirected by apache to our redis.

Is it more beneficial to tie this to Craft by updating the General.php with the session override options? Will we see faster/better session handling? Is there a session lock happening in craft? Is Craft opening/closing the session after each httpSessionService call?


texts: How can I link to a controller and return/redirect with data?

texts:
We have a plugin that logs you in and out of a third party service.

Login is easy as we can POST to a controller action, but for logout, we have a link that goes straight to an action URL.

My problem is that I want to redirect back to the URL the user submitted from, with some data that we use in the view (a message to say you've logged out).

redirectToPostedUrl() is no good as this isn't a POST request, and from what I can see in the docs redirect() doesn't give us the option to add data and anything we add in craft()->urlManager->setRouteVariables() doesn't come through when you redirect.

And if we don't redirect or return, we get a 404 as the user is just left on the controller action URL, for which there is no template output.


texts: First Image in a Series always references /cpresources/transforms/

texts:
I am having some odd behavior with an assets field.

I have an assets field that pulls a series of images. The template pulls the image transforms using {{ asset.getUrl('galleryThumb') }}. Odd thing is, the first image added always references the /cpresources/transforms/(number)b and not the actual file. All the other files work as expected.

I have tried clearing the caches. I tried a rinkydink solution of uploading a dummy image, making it the first and then deleting it... which worked until I cleared the caches again which made the first real image disappear again.

This happens also if I change the getUrl to another transform or even just the {{ asset.url }} so I am assuming it is the field.

The db assettransformsindex has a "0" in the fileExists column, but if I look in the actual transforms folder, it's there and was created.

The field is an assets field set to go to a specific folder in the path settings of the assets field I have the name of the folder(set to 777 out of frustration) "before-and-after" (without quotes and no slashes).

I've seen other questions here regarding images referrencing the /cpresources/transforms and tried all the solutions but this slightly different as it is only one image(the first) of a series.


texts:
So I'm used to JS where I can console.log() most errors to assess the best way to debug what's going on.
In Craft, as many of the sites I am working on are live and in production and I struggle (horribly) to find solutions to issues! Also because the site is live I cannot enable dev mode....
Is there a way to console log errors? (from looking at posts here I do not think there is, but I must ask directly).
If there is not, maybe someone could explain how they would handle this situation (Which I am currently in so this is not hypothetical).
I'm using SS twitter feed to populate a page with twitter tweets.
I would like to see what data is available to me, to use (or not use if some posts are different - and have to write conditions for).
In JS I would console log this i.e.
var tweets = getTweetsFunction
console.log(tweets)

this would display an array of objects and from there I could find out what fields are available.
But in Twig, posting
{% for tweet in craft.ssTwitterFeed.displayPost( '4' ) %}
  {{tweet}}
{& endfor &}

just gives me the "Server error" message.
Side note here, I have enabled the craft dev tool bar

And can see that it has a log section, can you log twig variables to this section to review them?
I understand that this might be a really basic question but it's driving me mad that every wrong turn ends in Server Error.
Thanks for any help,
W

As of craft 3.2 dump and die is enabled even for sites that are running without dev mode - dump and die is the solution to this issue.


texts: Pass radio button values to invisible field in Sprout forms

texts:
I have a form built with Sprout forms that has a few radio button fields, all with numeric values. I'm looking to provide the total sum of these fields to a hidden/invisible field upon submit.

Is it possible to provide the value of the radio button field directly to the Invisible Field Value using twig syntax? Or should I just go the scripting route and use jQuery to update the hidden/invisible field's value?


texts: Problem pulling Tweets with media using Dukt's Twitter API plugin

texts:
{% set tweets = craft.twitter.get('statuses/user_timeline', { tweet_mode:'extended' }) %}

{% for tweet in tweets %}

    {% if tweet.extended_entities.media is defined %}
        {% for item in tweet.extended_entities.media if item.type == 'photo' %}

        {% endfor %}
    {% endif %}

{% endfor %}

Anything obviously wrong here? I tested the API with a {{ dump(tweets) }} which seems fine.

This thread describes a similar issue but without a solution.


texts: Imager plugin not working inside the loop

texts:
so I am using trying to use the Imager plugin to compress my images. It works fine this way:

    {% set imagePath = "/path/to/img.jpg" %}
    {% set compressed = craft.imager.transformImage(imagePath, { pngCompressionLevel: 9, webpQuality: 10, jpegQuality: 50 }) %}

But if I try to use it inside a {% for %} loop it doesn't work and I get an error. Here's the code Im trying to use:

{% for image in logos %}
    {% if image %}

            {% set compressed = craft.imager.transformImage(image, { pngCompressionLevel: 9, webpQuality: 10, jpegQuality: 50 }) %}

    {% endif %}
{% endfor %}

Then I get this error:

Unable to open image /Applications/MAMP/htdocs/project/files/logos/my-logo.jpg

Does anyone know what Im doing wrong?

Thanks!


texts: Structure(s) vs. Categories for product catalog

texts:
So I am working on a project that includes an online product catalog. Is there a recommended way of setting up a catalog regarding the use of structure(s) vs. categories or a combination both?

I will have

brands with a couple of product families and a few products in every
family
accessories by the same brand for the whole family
accessories by the same brand for various product families
accessories by the same brand for only certain products
accessories by other brands for a whole product family
accessories by other brands for a certain product only

Wondering if one structure or two (for brands and products) and relations would work and be efficient and flexible, or if I should work with categories as well? In total, it will be about 100 to 150 items in the catalog.

Thanks for opinions!


texts: Is there a way to require the Expiration date

texts:
I can't find a way for a section (a channel in this case) to require the use to enter an expiration date.

I know I could add a new field and require that field, but that would get rid of the default functionality of entry/expire date fields.


texts: Display all fields without knowing object type?

texts:
I was looking for a way to show all fields/properties of a given object, and came across this useful tidbit: How to display all fields belonging to current entry?

I'm new to Craft/Twig and didn't actually know what type of object I'm trying to output properties of. I'm not sure when I output the object with {{ mysteryObject }} it outputs a number. That doesn't seem useful.

When I do the loop like in the question I referenced above like:

    {% for prop in mysteryObject.getFields() %}
        {# get the field Model from the fieldId #}
        {% set field = craft.fields.getFieldById(mysteryObject.fieldId) %}
        {# print the field handle and the field content  #}
        {{ field.handle }}
        :
        {{ entry.getContent()[field.handle] }}
    {% endfor %}

I get the error:

  Calling unknown method: craft\elements\MatrixBlock::getFields()

Cool, so now I know my object is a MatrixBlock, but this makes me wonder how I would go about inspecting the properties of just any object, like you can in JavaScript, without knowing what the object is.


texts: Why two equal variables give false statement?

texts:
I have two equal variables comparing each other which give me false.
One variable is set out of ancestor entry in structure and another one out of ancestor entry as well.
Both variables are set a bit differently.

{% set parent = craft.entries.ancestorOf(entry).order('lft desc').first() %}

Following variable is set within table field

{% for row in entryId.table %}

    {% set id = row.entryId %}
    {% set rowParent = craft.entries.ancestorOf(id).order('lft desc').first() %}

    {% if rowParent == parent %}
        // Go
    {% endif %}

{% endfor %}

Both variables print the same text with case sensitive letters and spaces.


texts: Hide flagged (inappropriate) comments from comment list

texts:
Craft CMS V2.
Comment Plugin: verbb comment

{% set comments = craft.comments.all({
    limit: 10,
    status: 'approved'
}) %}

{% for comment in comments %}
    {{ comment.comment }}
{% endfor %}

This query fetches all approved comments including flagged (Comment marked as inappropriate) comments because flagged comment status is 'approved'.

But I want to hide flagged comments from approved comments.


texts: Using Feedme to import data from ExpressionEngine 2

texts:
Im trying to get started using the Feedme plugin to import data from EE. Im working with the json template provided here: https://sgroup.com.au/plugins/feedme/guides/migrating-from-expressionengine

Ive been able to import data but when I include a rich text field Im getting errors – eg.

IGS Updates Test: Unexpected token "punctuation" of value ":" ("end of print statement" expected) in "
On Thursday the 1st of December last, the Limerick Chapter of the Irish Georgian Society opened the Christmas season with a fundraising Christmas party. The event was held in The Georgian House, No. 2 Pery Square, in Limerick. This historic house was built between 1835 and 1838 by Pery Tontine Company, forming part of a terrace known collectively as the Tontine Building. It was the last Georgian terrace built in Limerick. The building was restored by Limerick Civic Trust, with the support of the Irish Georgian Society and opened in 1999. We were delighted to give our guests an opportunity to enjoy an evening in the magnificent first floor rooms of the house and we thank Limerick City and County Council for use the venue.

Some of the entries are importing, but the majority are not. Any help / pointers appreciated...


texts: Craft 3 Plugins - Setting Template Path To Site Templates

texts:
In Craft 2, if you have a plugin that needs to load a view from the site templates directory, you could just go:

# Set the template context to site templates.
$path = craft()->path->getSiteTemplatesPath();
craft()->path->setTemplatesPath($path);

# Now we can load sweet templates from the sites templates dir, not the plugin one.
craft()->templates->render("/path/to/particular/site/template");

I'm struggling with doing this in a Craft 3 plugin. I thought I was on the right track with the below, but the context isn't updating.

# Set the template context to site templates.
$path = Craft::$app->getPath()->getSiteTemplatesPath();
Craft::$app->getView()->setTemplatesPath($path);

# Or this seems like it might do the same?
# Craft::$app->getView()->setTemplateMode(View::TEMPLATE_MODE_SITE);

# Render the view!
Craft::$app->getView()->render("/path/to/particular/site/template")

This results in explosions. It shows the error:

  Unable to resolve view file for view
  '/path/to/particular/site/template': no active view context.

Setting the template context is the bit that's not working. It's still looking at the plugin template directory.


texts: How to set stability version in plugins?

texts:
I've made a plugin, that I'm now trying to include in a live project, but when I try to install it via the plugin installer, I get a 500 error, and if I try to include it using composer, I get the following error:

$ composer require mustasj/expanded-search
[InvalidArgumentException] Could not find a matching version of
package mustasj/expanded-search. Check the package spelling, your
version constraint and that the package is available in a stability
which matches your minimum-stability (stable).

I've set the version to 1.0.1 in GitHub: https://github.com/mustasj/expanded-search/releases


texts:
This code worked fine in Craft 2:

 {% set entries = craft.entries.section('events').relatedTo(category).orderBy('startDate asc').limit(3) %}
 {% set extraEntries = craft.entries.section('events').relatedTo(category).orderBy('startDate asc').offset(3) %}
 {% if extraEntries | length %}
    //do some stuff
 {% endif %}

In Craft 3, {{ extraEntries | length }} is giving a value a 1 even when there are no entries. For example, {% for e in extraEntries %}>>>{{e}}{%endfor%} doesn't output anything. Any thoughts?


texts:
Is it possible to create a "Quick Link" in the control panel, similar to the way quick links function in ExpressionEngine?

If you have a Single that is frequently accessed by the client, it would be really helpful to save a link to the publish page right in the CP, rather than having the clients select Entries > Singles > Title every time they need to make an edit.


texts: Craft\EntryModel and its behaviors do not have a method or closure named "siteUrl"

texts:
Getting the above error when trying to add a new entry to a structure section.

The Section has an Entry URL Format of:

{siteUrl}/{slug}

In my general.php in the config folder I have:

return array(

    '*' => array(
            'omitScriptNameInUrls' => true,
        ),

    'local.ontherocks.dev' => array(
        'devMode' => true,
        'environmentVariables' => array(
            'basePath' => 'C:/Users/User/Documents/My Websites/Sitename/public/',
            'baseUrl'  => 'http://local.ontherocks.dev/',
            'siteUrl'  => 'http://local.ontherocks.dev/',
        )
    )

);

I don't see why I am getting this error - I have the same set up in another site I did.


texts:
Is it possible to have an "entries" field but only allow selection to entries of a specific "entry type" within craft?

I'm trying to use entry types as a sort of way to enable interfaces with chunks of content. Requiring specific fields for one type of content and different fields for another type of content.

I realize I could create many channels and accomplish the same thing, but these data structures are similar in a lot of respects with only minor differences (which are important depending on the context they are going to be rendered). So I would prefer to have an overarching channel with several types.


texts: Craft loading SCSS references rather than CSS

texts:
I am looking at a site at the moment which uses SASS to compile its CSS file. All styling references appear to be referencing the styling from the SCSS file, rather than the CSS file. Previously, all references pointed to main.css, but now points to the .scss file where the class is defined. Moving the .scss file on the server, or changing the filepath for the folder doesn't seem to stop it loading. My concern is that the site is now loading the multitude of .scss files rather than a single, minimized, .css file. Can anyone offer any insight on what is going on here?

The site is http://spiffingcovers.com/


texts: Force craft to do another job (queue) and pause the current one

texts:
I'm currently working on a plug-in for Craft. I have to work with a lot of data and, some steps are slow. So that's why I added them to a job system. This job is doing a lot of stuff.
That job is blocking the other jobs that are also important. Is there a way to push a new job to the top of the list and start it directly in Craft 3?
I tried to priority tasks (https://craftcms.com/docs/3.x/extend/queue-jobs.html#specifying-priority) and, it didn't work.


texts:
I have added the "file" option in my Standard.json file for Redactor.
Wehn using the Redactor field then I can click on the file button and select the image ok.
When I view source the file is linked to fine in the html.
But when I save the entry and go back to view it - the link is stripped out - it just displays:

link text

I have tried disabling Clean Up HTML and Purify HTML on the field options and saving again but still have the same problem - the link is being stripped out.

Anyone have a similiar issue?


texts: Permanently connecting templates to entries

texts:
I have site with a few hundred entries in a structure section. About 95% of these pages use the same template, with the remainder (about 20 pages) needing a special template. I manage this the following way:

The section (main) has a template called _entry.html which consists only of the following:

{% extends [entry.uri, "main/_main"] %}

I then match the uri in the templates folder and that template also extends main/_main with a block override to deal with the special case.

All of this works very well until the content editor moves the special entry in the structure, and then of course it loses its template and goes back to the default.

Is there way I can "lock" an entry to a specific template (which still inherits) so that when the entry is moved in the structure it does not "disconnect".


texts: project.yaml synchronize error (not usable anymore)

texts:
I had a table field and created a new super table field to try something.
After that I removed my table field and gave my super table field the same handle like the old table field had.

I did it locally and synced it via git.
After that I wanted to sync my project.yaml.
I tried ./craft project-config/sync and I got a error: error: Getting unknown property: craft\fields\Table::contentTable

I tried to remove the complete section on my production server but still no changes. At the moment I have no Idea what I could do…

Of course ./craft project-config/rebuild works but then I have my old project.yaml

Thanks for any help!


texts:
I have a very basic macro for a lazyloading responsive image tag:

{% macro isotopeItem(imgParam) %}

  {% set thumb = { mode: 'fit', width: 100, quality: 60, } %}
  {% set tSM = { mode: 'fit', width: 1536, quality: 80, } %}
  {% set tMD = { mode: 'fit', width: 340, quality: 80, } %}
  {% set tXL = { mode: 'fit', width: 1536, quality: 80, } %}

    <img
    src="data:image/gif;base64,{# yadayada #}"
    data-sizes="auto"
    data-src="{{ imgParam.url(thumb) }}"
    alt="{{ imgParam.title }}"
    data-srcset="
      {{ imgParam.url(tSM) }} {{ imgParam.getWidth(tSM) }}w,
      {{ imgParam.url(tMD) }} {{ imgParam.getWidth(tMD) }}w,
      {{ imgParam.url(tXL) }} {{ imgParam.getWidth(tXL) }}w"
    class="lazyload" />

{% endmacro %}

As you can see the image transformations are inside the macro which is not very nice.

How do I write the transformations outside the macro and then pass it into it? I tried tried to write one param for each transformation:

{% set thumb = { mode: 'fit', width: 100, quality: 60, } %}
{% set tSM = { mode: 'fit', width: 1536, quality: 80, } %}
{% set tMD = { mode: 'fit', width: 340, quality: 80, } %}
{% set tXL = { mode: 'fit', width: 1536, quality: 80, } %}

{% macro isotopeItem(imgParam, transformParam1, transformParam2 {# and so on #}) %}
   {# responive image srcset code like the above example #}
{% endmacro %}

{# I then would have to call the macro like this: #}

{{ _self.isotopeItem(asset, thumb, tSM, tMD, tXL) }}

This works but I have to pass all the transforms everytime I use the macro.

There must be a better way right?


texts: Is this the correct and safest way to update / save a new record?

texts:
public function saveGoal(Logic_GoalModel &$model)
{
    // New goal
    $isNewGoal = !$model->id;

    // Populate record
    $record = $this->getGoalRecordById($model->id);
    $record->userId = $model->userId;
    $record->goal = $model->goal;
    $record->complete = $model->complete;

    // Save record
    if($record->save(false))
    {
        // Populate id
        if($isNewGoal)
        {
            $model->id = $record->id;
        }

        return true;
    }
    else
    {
        return false;
    }
}

private function getGoalRecordById($id = null)
{
    if($id)
    {
        $record = Logic_GoalRecord::model()->findById($id);

        if (!$record)
        {
            throw new Exception(Craft::t('No record exists with the ID “{id}”', array('id' => $id)));
        }
    }
    else
    {
        $record = new Logic_GoalRecord();
    }

    return $record;
}


texts:
Fairly new user here.
I am kinda confused how to template. I want to rearrange the order of blocks in my backend and show them in the right order in the front.

Here is how i am currently writing a template.

Created a section called "Homepage"
Then I made a matrix block "content blocks"
After that I created 3 Blocks and called them "Image left", "Image right", "Full Text"
Went into my _entry.html and wrote some for loops. Example

{% for block in entry.contentblocks.type('imageLeft') % }
    do something
{% endfor %}

Now when I order those fields in my backend it won't show the right order on my frontend.

Example:

Backend order:

imageLeft
imageRight
imageLeft

Frontent view:

imageLeft
imageLeft
imageRight

I know this is happening because the first for loop will check all first and print them one after another before moving to the next for loop.

How do I prevent this?

I seriously hope somebody understands my issue.  I am fairly new to Twig and Craft so I take every pointer I can get.


texts: Directories and files being created by "root" user, inaccessible to CMS

texts:
I'm new to Craft and have been asked to support a live site that is running on it. I've run into a problem that seems to be due to files on the server being created by the wrong user.

The vast majority of files are owned by the user skillsadmin in group psacln, but randomly some directories and files are being created by user "root", group "root".

Some of these root files are causing errors because they can't be accessed by Craft.

So far this only seems to be happening within the /storage directory.

One example is a single directory in the /storage/runtime/compiled_templates directory (along with its contents) that is causing an internal server error with the preview feature of the Campaign plugin. Another example (though I haven't seen any errors caused by it yet) is apparently random log archive files being created by "root".

The site is running on a VM. I asked the provider's support desk for help but they just said it's an application issue and not their responsibility.

What can I do to ensure that all files written by Craft are created by the correct user?


texts: Development system with MAMP won't run after MAMP upgrade?

texts:
I have a development system with MAMP and gulp and my localhost version of my website was running fine.  I upgraded MAMP from 3.5.2 to 4.4.1.  When I restarted MAMP it said it needed to upgrade the database, which I let it do.  Now when I try to start the website, it just spins at the localhost:6002 (for example) website address and the site will never launch.

Any thoughts on how to chase down this problem.


texts: DB back-up gives syntax errors on import in new DB

texts:
I had this issue on two different sites on two different occasions and hosts.
When creating a database back-up through the Craft CMS admin and importing that SQL file into a new database through PhP MyAdmin I get syntax errors and import stops.

I tried backing up the database on both sites through the hosting company itself, which resulted in one backup working and one also giving the syntax error.

I just updated the sites to Craft 2.6.x.

Any ideas what goes wrong or how I can solve this? Do I need to manually go through the whole SQL file and fix the syntax errors manually? :/

When I open the SQL file in PhPStorm, it looks like the character where the error happens, all the SQL statements coming behind it are escaped wrong, they are shown as normal text. Maybe an encoding issue?


texts:
I have an entry type called industry and am trying to use this search syntax in the CP to filter my entries by that type:

type:"industry"

I am getting no results whatsoever. How do I filter entries in CP by Entry Type?


texts: In entry.getPrev/Next navigation, show entries from a specific category only

texts:
I have portfolio section that has a ‘portfolio’ category attached to it, which has categories ‘2D’ and ‘3D’.

There are 3 templates:

The index template shows a list of all the entries in the portfolio
section.
The categories template shows the entries within a specific category.
The entry template shows a single entry.

On the index page (/portfolio) you can click on 'All', '2D' and '3D' whereby 'All' takes you the index page, and 2D and 3D lead to /portfolio/2D and 3D (the categories template). Click on any item in the list and you go to the entry page.

On the entry template, I have a simple ‘previous entry’ and ‘next entry’  browsing navigation, using:

{% set params = {section: 'portfolio', orderBy: 'postDate desc', limit: null} %}
{% set entry_prev = entry.getPrev(params) %}
{% set entry_next = entry.getNext(params) %}

The thing is, this navigation always browses through all of the entries, regardless of what category an entry is in. And that's fine when you've reached the page from the index page, where all of the entries are listed. But I’m trying to make it so when you click an entry on the categories page, and you are then taken to this entry page, the browsing navigation (previous and next entry) takes into account what category you’re in. I use a simple cookie or getQuery() to set and get this information. That way, when you've clicked on an entry in the list with 2D items, you don't get entries from other categories in the prev/next navigation, but when you've clicked on the same item on the index page, you do get to navigate through all of the entries.

I’ve tried:

{% set params = craft.entries.section('portfolio').relatedTo('2d').orderBy('postDate desc').limit(10).all() %}

But this does not work: the navigation still includes entries that do not have the 2d category.

Anyone have any idea how to achieve this?


texts:
I just realized that Craft puts the username into the path of the photoUrl. Since I use email addresses as usernames, I don’t think it’s a good idea to expose the email addresses of all users on the web.

Question: Is there a way to remove the username (in my case email address) from the photo path and replace it with the users ID for example?

I would like to get around adding a new asset field for every user, since the user photo would be fine.

Bonus question: is there any way to protect user photos from access at all? It looks to me like the urls to the user photos could be guessed quite easily.

Best, Mark


texts: Force language segment in URL on multi-lingual site

texts:
I'm setting up a multi-lingual site and want to force the language segments:

domain.com/en/
domain.com/fr/

However if you go in the URL bar and remove the en/ or fr/ it loads up the English page without the language segment. How do I force this to load. Have tried a few .htaccess suggestions found via Google but nothing is working.


texts: Commerce 2 Sales Not Present In Cart lineItems

texts:
I have an issue where sales and sale pricing seem not to be present in the cart. This is on an ecommerce flow where this was previously all working but I had moved onto other dev work on this site for many weeks, applying Craft and Commerce updates over that time - and have now returned to the ecommerce flow to find this not working.

Craft Pro 3.3.20.1

Commerce 2.2.14

What is happening is that when I have a sale for a given product, the discounted sale price does not appear to be in the cart (Craft returns the base price) and the lineItems do not appear to have any sales in place for a given item. I stripped this back to a barebones template:

{% set cart = craft.commerce.carts.cart %}

{% if cart.isEmpty() %}
  Empty
{% else %}
    {% set lineItems = cart.lineItems %}
    {% for item in cart.lineItems %}
      {% set variant = item.purchasable %}
      {% set product = variant.product %}

{{ product.title }}

        {% if item.onSale %}
            Sale: {{ item.salePrice }} - Was: {{ item.price }}
        {% else %}
          No Sale: {{ item.price }}
        {% endif %}

    {% endfor %}
  {% endif %}

{{ dump(lineItems) }}

  itemTotal:{{ dump(cart.itemTotal) }}

  itemSubtotal:{{ dump(cart.itemSubtotal) }}

  total:{{ dump(cart.total) }}

  totalDiscount:{{ dump(cart.totalDiscount) }}

  totalTaxablePrice:{{ dump(cart.totalTaxablePrice) }}

  totalShippingCost:{{ dump(cart.totalShippingCost) }}

  totalSaleAmount:{{ dump(cart.totalSaleAmount) }}

  getTotal():{{ cart.getTotal() }}

  getItemSubtotal():{{ cart.getItemSubtotal() }}

  getItemTotal():{{ cart.getItemTotal() }}

So what happens:

I add a product to the cart which has an applicable sale (I've tested it has one by triple-checking the sale logic in the CP against the product and checking the product details in twig via {% set productSales = product.defaultVariant.getSales() %} to confirm it has applicable sales.
Once in the cart, via the template above, the returned prices all reflect the base price - no sale price.
The sales object has nothing in it from lineItems and item.onSale is false (though I notice lineItems[0].snapshot.onSale is true (but I'm not certain what that is supposed to represent).

I'd normally conclude I was doing something wrong, but I believe my code follows the Commerce template examples and was working fine when I last worked on it (awhile back... maybe October).

I wondered if some commerce update has fundamentally changed something about how this should all work but could find no clues in the changelog.

Can anyone confirm there isn't something fundamentally wrong with my cart code above - or has something changed in Commerce? Or could there actually be a bug?

EDIT: The non-sale (base price) I see in the cart is reflected in the actual order details in the CP.


texts: Dates for entries are in different language

texts:
When the user wants to edit the Post Date or Expiry Date of an entry (channel/structure), the calendar is in Welsh language.
I have no clue how this happened.
How can I change this?
Thank you


texts: EVENT_AFTER_CREATE_SUBSCRIPTION can someone confirm this means successful purchase?

texts:
Regarding Event: EVENT_AFTER_CREATE_SUBSCRIPTION
https://docs.craftcms.com/commerce/api/v2/craft-commerce-services-subscriptions.html#events

The document states "The event that is triggered after a subscription is created. Plugins can get notified after a subscription is created."

Using the commerce 2 as an example:

I just need an expert to confirm that a subscription is created or EVENT_AFTER_CREATE_SUBSCRIPTION has executed only when a user has successfully made payment to a subscription.


texts: Transform: Image {file} cannot be found with

texts:
Why do i get an error

throw new Exception(Craft::t('Image “{file}” cannot be found.', array('file' => $file->filename)));

for

{% set myImage = entry.pr_foto.first %}
{% set params = { width: 300, height: 200 } %}

while

{% set myImage = entry.pr_foto.first %}

shows the image?

The filesystem path for photos is uploads/photos/. The upload works fine in the admin. It's only the transform.

Full trace error: