texts: How to see which database Craft is currently connected to?

texts:
I was able to install Craft using a Vagrant/Homestead setup, but I can't seem to connect to the database I want. I set up my hosts file to point to a '.dev' address while working locally on my machine.

My db.php file seems to be set up ok:

return [
  '*' => [
    'server' => 'localhost',
    'tablePrefix' => 'craft',
  ],
  '.dev' => [
    'database' => 'dev',
    'user' => 'homestead',
    'password' => 'secret',
  ],
  '.org' => [
    'database' => 'prod',
    'user' => 'root',
    'password' => '********',
  ],
];

When I ssh into my vagrant box and log into mysql, I can SHOW DATABASES and see:

+--------------------+
| information_schema |
| dev                |
| prod               |
| homestead          |
| mysql              |
| performance_schema |
+--------------------+

I'm overwriting the dev, prod and homestead databases with a backedup .sql file, however when I visit my local '.dev' address, my Craft site doesn't appear to carrying over any of those changes.

Is there a way to see which database Craft is actually connected to?


texts:
I'm pretty new to Craft, just installed my first one. I've checked the docs, but I couldn't find any useful hints anymore and I think it should work.

I'm trying to rename the default news section to post. I changed everything admin side from news to page, but the path http://site.local/post/2016/we-just-installed-craft leads to a 404 page. The http://site.local/post page lists the entries correctly.

I also renamed the news folder in the templates to post. If I change it back to news, the 404 problem is resolved, but obviously I want to understand why it still wants to access that folder.

Sections page looks like this

I don't have any custom route set up.


texts:
I am attempting to get a specific entries id from within a specific section. I have looked around, and clearly have not found anything yet.

To clarify, lets say we have a section called "Stories", which is a structure. Inside of "Stories" there is a specific entry named, "Story One" that I would like to retrieve the id of.

I can pretty much get as far as getting the contents of the Stories structure via:

$entry = craft()->sections->getSectionByHandle('stories');

The important piece here, is that I want to find the "Story One" entry id. Reason being is that it looks like you can't do relatedTo queries via the title of an entry, but you need the id.


texts: Twig Runtime Error on settings/general (value: system.name)

texts: When I go to settings/general in the CP i get this Twig Runtime Error.  Does anoyone here know what to do to fix it?


texts: How would I include the first category slug in the section's entry URL format?

texts:
I have a custom section that uses routes like this:

/section/category/entry_url

In trying to program the search form results I realized that I need to explicitly define the entry URL format for the section so that the search results return the proper links to view the entries.

Currently I have /section/{category.slug}/{slug} but it is not working.

How would I set the entry URL format to include only the first category slug of the entry?

Thanks.


texts: Best practice for adding a title to a channel overview page

texts:
I have a Blog where everything is on one template. The entries don't have an own url.

{% for entry in craft.entries.section('blog') %}
    {# everything #}
{% endfor %}

Now I want to give this page a title.

I could create a single called Blog page to have a title and a url. But isn't that a bit much for just a title? I hate to have a single with almost no content in the control panel.
Could there be a better way to add a title to that page?

Globals?
Categories?
Something else?

How do you handle that?


texts: How do I wrap my Youtube video from a Redactor field with Bootstrap's responsive classes?

texts: In my Redactor field, I'd like to programmatically wrap all Youtube videos that have been added through Redactor's video plugin with Bootstrap's responsive embed classes. This answers how to add a single class, but Bootstrap requires multiple classes to be added to the wrapper.


texts: Why does {{ user.getPhotoUrl(64) }} point towards storage/runtime and not to storage/userprofiles?

texts:
I am trying to load user profile pictures (the Craft ones), but they don't load. The getPhotoUrl() seems to point to the wrong folder(?).

The profile images seem to be stored in the userprofiles folder by default

{% set users = craft.users %}

{% for user in users %}

{{ user }}

    {% if user.getPhotoUrl %}

    {% else %}

    {% endif %}

{% endfor %}

  2017/04/24 11:24:10 [error] [application] Tried to read the folder contents of /Applications/MAMP/htdocs/craft/storage/runtime/assets/sources/, but could not.
  2017/04/24 11:24:10 [error] [application] Tried to read the folder contents of /Applications/MAMP/htdocs/craft/storage/runtime/assets/tempuploads/field_3/, but could not.
  2017/04/24 11:24:10 [error] [application] Tried to read the folder contents of /Applications/MAMP/htdocs/craft/storage/runtime/assets/tempuploads/field_4/, but could not.
  2017/04/24 11:24:10 [error] [application] Tried to read the folder contents of /Applications/MAMP/htdocs/craft/storage/runtime/assets/tempuploads/user_1/field_3/, but could not.
  2017/04/24 11:24:10 [error] [application] Tried to read the folder contents of /Applications/MAMP/htdocs/craft/storage/runtime/assets/tempuploads/user_1/field_4/, but could not.
  2017/04/24 11:24:10 [error] [application] Tried to read the folder contents of /Applications/MAMP/htdocs/craft/storage/runtime/temp/uploads/userphotos/harry/, but could not.
  2017/04/24 11:24:10 [error] [application] Tried to read the folder contents of /Applications/MAMP/htdocs/craft/storage/runtime/temp/uploads/userphotos/remco/, but could not.

the console gives this error

GET http://localhost/cpresources/userphotos/remco/64/17492405_10212330524487585_7776812525773615973_o.jpg?x=UoEZXg1dH net::ERR_CONNECTION_REFUSED


texts: How to cache location per guest in craft cache via plugin

texts:
I am looking at setting the currency of a guest site visitor. I have the look up and currency retrieval working OK based on the individuals IP.

The problem i seem to face is how to cache the currency per site visitor and not set it for the whole site/all visitors.

A dump of craft->session shows no unique guest ids available.

Should i set a cookie for current user (IP address) and compare with cached IP?

Any slaps around the head welcome :)


texts: Stop Redactor automatically creating hyperlinks

texts: Each time I write a link such as www.link.com Redactor automatically turns it into an active hyperlink. Is there a way to turn this function off?


texts:
I try to update my craft3 cms system.

Ошибка: An error occurred

Вывод: Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package oneup/contao-security-checker-bundle could not be found in any version, there may be a typo in the package name.
Problem 2
- Installation request for craftcms/cms 3.0.22 -> satisfiable by craftcms/cms[3.0.22].
- craftcms/cms 3.0.22 requires enshrined/svg-sanitize ~0.9.0 -> satisfiable by enshrined/svg-sanitize[0.9.0] but these conflict with your requirements or minimum-stability.
Problem 3
- craftcms/cms 3.0.22 requires enshrined/svg-sanitize ~0.9.0 -> satisfiable by enshrined/svg-sanitize[0.9.0] but these conflict with your requirements or minimum-stability.
- craftcms/redactor 2.1.6 requires craftcms/cms ^3.0.0-RC15 -> satisfiable by craftcms/cms[3.0.22].
- Installation request for craftcms/redactor 2.1.6 -> satisfiable by craftcms/redactor[2.1.6].

Potential causes:
- A typo in the package name
- The package is not available in a stable-enough version according to your minimum-stability setting
see for more details.
- It's a private package and you forgot to add a custom repository to find it

Read for further common problems.
Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.

Solution I've found is - to remove roave/security-advisories, but I still don't understand how I can do this. Same problems I have with plugin install.

Composer File

{
  "name": "craftcms/craft",
  "description": "Craft CMS",
  "keywords": [
    "craft",
    "cms",
    "craftcms",
    "project"
  ],
  "license": "MIT",
  "homepage": "https://craftcms.com/",
  "type": "project",
  "support": {
    "email": "support@craftcms.com",
    "issues": "https://github.com/craftcms/cms/issues",
    "forum": "https://craftcms.stackexchange.com/",
    "source": "https://github.com/craftcms/cms",
    "docs": "https://craftcms.com/docs",
    "rss": "https://craftcms.com/changelog.rss"
  },
  "require": {
    "craftcms/cms": "3.0.18",
    "vlucas/phpdotenv": "v2.4.0",
    "craftcms/redactor": "2.1.5",
    "dolphiq/craft3-forms": "1.1.0",
    "craftcms/contact-form": "2.2.2",
    "craftcms/guest-entries": "2.1.3",
    "nerds-and-company/schematic": "4.0.14",
    "symfony/yaml": "v3.3.6",
    "illuminate/contracts": "v5.5.40",
    "illuminate/support": "v5.5.40",
    "nesbot/carbon": "1.32.0",
    "psr/container": "1.0.0",
    "psr/simple-cache": "1.0.1",
    "symfony/translation": "v3.3.6"
  },
  "autoload": {
    "psr-4": {
      "modules\\": "modules/"
    }
  },
  "config": {
    "optimize-autoloader": true,
    "platform": {
      "php": "7.0"
    }
  },
  "scripts": {
    "post-root-package-install": [
      "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
      "@composer dump-autoload -o",
      "@php craft setup/welcome"
    ]
  }
}

thank for your answers


texts:
We have a site with multiple languages so I created a site for each language.
I named these according to the language so, one is named "French", another "English" etc.

Now in the backend this is all fine, when creating entries its clear what the language is you are working in.

I soon noticed these are also used in the front-end and that creates some problems. The site name in a template is easily override by adding something like {% set siteName = getenv('SITE_NAME') %}.

But harder to fix are for example the mails send out when creating a account, they now say something like "Thank you for creating an account on English!"

I tried a fix by setting the same site name in the config/general.php, this works, but now all the sites in the site switcher in the backend are the same. So not really a good fix.

Having to set a different name for each site is kinda weird, in most cases the brand name is the same in every language. Google is Google no matter the language.

Anyone who knows a decent way to handle this?


texts: Redactor: Set a min height and preserve line breaks

texts:
I'm looking to set a min height on the redactor text area.  The vendor site shows how it can be done, but doesn't specify where to add this code snippet.
$R('#content', {
  minHeight: '500px'
});

I added that to the redactor.js file in the vendor/craftcms/redactor/lib/redactor folder, but it didn't work. Can someone point me in the right direction? I'm trying to avoid installing additional plugins like Control Panel CSS just to do that one thing.
Additionally, is there a way to preserve line breaks in the text area? I work only in the code view mode and after every save, line breaks disappear. I did a search and found some pages on Github that talk about the issue, but I couldn't find a resolution.


texts: Displaying gallery when viewing category page or entry with related categories - code review

texts:
I have a gallery in my site's  with images that are defined in a matrix field on each of my categories. If I'm viewing a category page or an entry with related categories I want to display this image gallery in the footer.

What I currently have is this:

{% if category is defined %}
    {% if category.actionBilder.exists() %}

            {% for block in category.actionBilder.limit(3).orderBy('RAND()').all() %}
                {% if block.type == "actionImg" %}

                {% endif %}
            {% endfor %}

    {% endif %}
{% endif %}

{% if entry is defined %}
    {% set categories = craft.categories.relatedTo(entry) %}
    {% for category in categories %}
        {% if category.actionBilder.exists() %}

                {% for block in category.actionBilder.limit(3).orderBy('RAND()').all() %}
                    {% if block.type == "actionImg" %}

                    {% endif %}
                {% endfor %}

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

While it's working fine, I don't think that this is the best solution.

How would you change my code to make it better?


texts: How to use a global variable in a conditional statement if an entries relation field is empty?

texts:
{% if entry.fieldHandle %}
  {{ entry.fieldHandle}}
{% else %}
  {{ global.fieldHandle}}
{% endif %}

Doesn't seem to be rendering for me. The entry field shows up when it's true, but the global field doesn't in the cases it needs to.


texts: Is Redactor's default config saved as a .json file anywhere?

texts:
When I need to make one tiny change to the default config it would be handy to be able to duplicate the current default.json file and just change a one thing instead of building a duplicate from scratch.

It's a small thing, but it would be a nice time saver. I've had no luck finding it, does anyone know if the default is saved somewhere?


texts:
I want to strip every headline tag from all Rich Text fields site-wide.

So I thought about adding a replace filter.

But since this will be site wide I wanted to write the replace rules in a variable:

{% set replaceHeadline = '"
" : "
", "
" : "
"' %}
{{ entry.richText | replace({replaceHeadline}) | raw }}

This produces the error:

  A hash key must be followed by a colon (:). Unexpected token
  "punctuation" of value "}" ("punctuation" expected with value ":").

Is this not possible? Is concatenation with ~ somehow the way to go?

Is there a more sane approach to stripping all headline tags from Rich Text fields?


texts: How can I find LinkIt Field values and the entries they're on?

texts:
We've got a sprawling site built up over 4+ years, and someone decided we'd no longer use X page, but now we'll use Y, and sadly the authors don't always know to use an entry, so they copy in the ~whole blasted~ url. We've set up redirects to handle the change, but we'd optimally like to find and change those.
We have linkit fields both as simple fields and within matrix fields, so they're embedded. I'd love to figure out a way to show the URLs or Entries that are used, and all the pages that they are used on, so authors can go in to fix them.


texts:
We've had a half a dozen cases now of people editing content in different Craft 2.6 sites taking down our webservers.

One staff member here editing a basic entry in the CMS has taken down a large cloud server multiple times over the past couple of months.
A group of 20~ students uploading some basic projects in the CMS took down a different quad core webserver with 12GB of RAM and spiked the load to 250 - again multiple times.

I have little info to go off at this stage but I do know the load was caused by post requests made by php from the CMS. Front end traffic isn't the issue.

I'm nervous enough about this at the moment that the latest craft site I launched is on its own VPS to keep it away from other sites.

--

Happy to provide login/server deets to any of the Craft guys if they're curious, or if there's any more info people want, please let me know.


texts:
Hi hope you can help with this and hoping it's simple. I need to write a javascript module and would like to use the js tag:
{% js %}

        //script here

{% endjs %}

This is good because it only gets embedded when needed and it gets placed at the bottom of the page and I can add craftcms variables to it. The problem I have is that the script is being outputted as
<script>
// script here
</script>

and what I need is
<script type="module">
// script here
</script>

Any idea how I can do that?
Thanks


texts: Best way to use saveCookie and craft.request.getCookie('location')

texts:
Following up on this question: Prescribed way to set cookies (from plugin or Twig) the following works great.

craft()->userSession->saveCookie($cookieName, $data, $duration);

I can see Location being set as my cookie in the Application Log but when I try to use {{ craft.request.getCookie('location') }} It returns blank.

What am I missing here?

Edit - Upon closer inspection it doesn't look like saveCookie is working correctly either. I see location from when I was using setFlash but I need the data to persist even if the page is reloaded.


texts: How to make a sortable table in frontend?

texts:
I need to display a sortable table of organization member records in frontend, preferably with pagination. Before I start coding this from scratch, I want to ask:
Does anyone have some ideas on how to do this, and what Craft/Yii/plugin functionality I could use to accomplish this?

I'm fairly new to Craft, so at the moment I don't know where to start looking.

Some more details
I'm writing a frontend customer portal plugin, that uses the built in Craft functionality for handling user registration/login/etc. On top of that I've added a MyPlugin_UserRecord and a MyPlugin_OrganizationRecord record, with some service functionality to handle those.

The MyPlugin_UserRecord can be either a private user by it self, or belong to an organization as a member, and it's the latter that I want to display in the table.

Below you can see the relations I have defined:

UserRecord (Craft)

MyPlugin_OrganizationRecord
    'craft_user' => array(static::BELONGS_TO, 'UserRecord', 'craft_user_id'),
    'members' => array(static::HAS_MANY, 'MyPlugin_UserRecord', 'organization_id'),

MyPlugin_UserRecord
    'craft_user' => array(static::BELONGS_TO, 'UserRecord', 'craft_user_id'),
    'organization' => array(static::BELONGS_TO, 'MyPlugin_OrganizationRecord', 'organization_id'),


texts: Just upgraded to Craft 3, environmentVariables changed or stopped working

texts:
In my Craft 2 install, I had many links in Twig templates like this:

<link rel="stylesheet" href="{{ craft.config.environmentVariables.baseUrl }}assets/css/styles.css">

I recently upgraded to Craft 3, and on my local environment, these links no longer work. I get this error:

Neither the property "environmentVariables" nor one of the methods "environmentVariables()", "getenvironmentVariables()"/"isenvironmentVariables()"/"hasenvironmentVariables()" or "__call()" exist and have public access in class "craft\web\twig\variables\Config".

Is there a new way of using environment variables (or whatever they are now called) in Craft 3? I'm just trying to set links to the site URL, but I'd like to have that be different for my local development site and the production site. I found some documentation on how to use environment variables in Control Panel settings, but nothing about Twig templates.


texts: Category query returning one fewer items than requested

texts:
I'm building a knowledgebase for a client. The client has asked for content to be restricted by category and then by user. This part is easy enough - the users now use the same category field as articles. However, the templating is proving troublesome.

Currently I'm querying for the category IDs, building an array and using it in the main category query.

{% set searchQuery %}[{% for category in currentUser.kb__category %}{{ category.id }}{% if not loop.last %}, {% endif %}{% endfor %}]{% endset %}

This returns, for example, [268, 270, 273, 276]

Consistently, the page is displaying all but the first category. This happens no matter what the first assigned category is.

{% for category in craft.categories
  .group('knowledgeBase')
  .id(searchQuery)
  .level(1)
  .all()
%}

If I replace searchQuery with [268, 270, 273, 276] it works perfectly, which is baffling me as that's what has been output.


texts:
Can someone explain why and when we need to use .first()?

An example to use would be this code.

{% set featuredProductsHome = craft.entries.id(2).first() %}
{% for product in featuredProductsHome.featuredProducts %}
    {% import '_macros/_product' as m_product %}
    {{ m_product.teaser(product, 500, "product-teaser--featured") }}
{% endfor %}

The above works, but when I had {% set featuredProductsHome = craft.entries.id(2) %} without calling .first() it returned nothing.


texts:
I guess I could always loop through the structure but is there a simple way to directly get the n-th entry in a structure? (at a given level)
Something like:

{% set $fifth_listing = craft.entries.section('listing').level('1').pos('5') %}


texts: Hide users photo (avatar) from admin panel grid

texts:
Is it possible to remove the field for users' photo from the grid of the tab Users?
It also appears on the user's profile page.
Examples
Grid:

User's profile page:


texts:
I'm attempting to merge in postDate restrictions based on the url segment. However I get twig errors with my code.

So for a link of domain.com/news/archive/2016 I want to see all entries with a postDate in 2016.

current code:

{% set params = { section: 'news', limit: 5 } %}

{# check for annual archive in the url #}
{% if craft.app.request.getSegment(2) == "archive" %}
    {% set year = craft.app.request.getSegment(3) %}

    {% set start = date( year ~ '-01-01') %}
    {% set end = date( year ~ '-12-31') %}

    {% set params = params | merge({
      postDate(['and', ">= " ~ start, "< " ~ end])
     }) %}
{% endif %}
{# end check for annual archive #}

And the Error I get

A hash key must be followed by a colon (:). Unexpected token "punctuation" of value "(" ("punctuation" expected with value ":").

Also not working
I tried a couple of variations - this gets no errors, but also no entries are output

{% set params = { section: 'news', limit: 5 } %}

{# check for annual archive in the url #}
{% if craft.app.request.getSegment(2) == "archive" %}
    {% set year = craft.app.request.getSegment(3) %}

    {% set start = date( year ~ '-01-01') %}
    {% set end = date( year ~ '-12-31') %}

    {% set params = params | merge({
      postDate: "['and', '>= ' ~ start, '< ' ~ end]",
     }) %}
{% endif %}


texts: SproutForms: User permissions to edit form settings not being honored

texts:
I am trying to setup a user permissions such that only a specific user group has permissions to create and edit SproutForms.

When editing the permissions for a user group, there is an option for SproutForms labeled Edit Form Settings. If I leave this setting unchecked, but check the Access SproutForms under the General heading so that the user may view form submissions, a user in this group is still able to create and edit forms.

Is this a bug? Running SproutForms version 2.3.2.

Any help would be much appreciated.


texts: Smart Map - Outputting locations from a Matrix field for all entries within a single section

texts:
I'm using the Smart Map plugin, and I can't seem to figure out how to output all the locations of my entries from a single section onto one single map.
I think the issue I'm having is trying to get the information out from a Matrix block within each entry or knowing where to start!
The section is 'buildings' which contains all the building entries. For each entry, there is a matrix block called 'buildingContent' which has 5 matrix blocks, and the one I want to pull information from is 'howToGetThere' (last block out of the matrix array). In this block, I have a field 'smartMap' which contains the location of the building.
How would I extract the location from the 'smartMap' field for all my entries and output them onto one single map?
I know the code below outputs the location of one entry (St Bartholomew The Great), but thought it might be useful to include what I've tried so far. I adapted it from the documentation:
{% set entry = craft.entries.slug('st-bartholomew-the-great').first %}

{% set locations = entry.buildingContent %}

{% set options = {
     height: 600,
     zoom: 13,
     draggable: true,
     markerInfo: '_includes/mapInfoBubble',
     markerOptions: {
        icon: 'images/map-marker2.svg',
     }
 } %}

{{ craft.smartMap.map(locations[4], options) }}

Any help much appreciated, thanks!


texts: Can a plugin add JS or CSS to the control panel?

texts:
Say for example, I wanted to add a "Expand/Collapse All" button to Matrix fields.

Is there any way to do this, or is this something more appropriate for a feature request for P&T?


texts: Translation files on load balanced multiple instance site

texts:
We have quite a large Craft based site that requires load balancing so there are often multiple instances of the site.

The problem we are having is with the translation files. Because these are stored as files when you update them through the admin they are only updated on the site instance you are currently on. Obviously this isn't scalable.

What would be the best solution to make these static translations scalable in this sort of environment? Move the translation files to an S3 bucket? (this would be ideal but have don't think this is possible) or move all translation fields to the database somehow? (what would be the best field type to store them as and where?) or is there some other solution?


texts: Date/Time field outputting time with additional minutes

texts:
I've having an issue where a Date/Time field (time only) is outputting the time in the front-end template with an extra 10 minutes.

In my template I'm using entry.startTime|date("g:ma”).

In the DB the field_startTime for the entry is 2016-10-15 16:00:00, but on the front-end I’m seeing 4:10pm.

Could anyone tell me where are these extra 10 minutes coming from, please?

This is happening both locally and on the dev server, using Craft CMS 2.6.2949


texts: All, we have a website built by third party company and they gave us the pack which includes cms, craft and MySQL database. But our hosting server is hardcoded to run the website from public_html folder (can't change this). Could you tell me how can change cms references to public_html? Tried to copy everything under cms folder to public_html only to see misconfiguration errors. Let me know if you need more info.


texts: calculating average ratings from a series of review fields

texts:
I've setup a section for reviews with several fields as numbers for a rating 0-5, I'm trying to figure out how to get the total of all reviews and sum of all reviews to provide a single average for an entry the reviews relate to.

What's the best approach to this.

Example of my fields:

Value
Condition
Reception
etc

all graded 0-5 (number fields).

So how to go through the foreach and get the sum of all fields from all reviews then divide by total reviews for the related entry to get the average for each field.


texts:
This is super simple, and I don't get why it's not working.

{% set results = craft.entries.section('events').lightSwitchField('1') %}

Returns all entries in Events where the light switch field is green.

{% set results = craft.entries.section('events').lightSwitchField('0') %}

Returns all entries in Events. Period. Not all entries that the lightswitch is set to off.

I want to get all entries where the lightswitch field is off. Later I'm going to chain some other fields to the query too.

What have I not understood about how this works?


texts: How to get the Twig Text extension loaded

texts:
I'd like to add the Text extension:

http://twig.sensiolabs.org/doc/extensions/index.html#extensions-install

Which seems very useful because of the truncate functionality. Any idea on how to accomplish this?

(this could've been installed by default)


texts: How can I clone a specific Site in Craft, not the default?

texts:
I have many sites in Craft and I group them by language. For example, German has Germany and Austria sites in them. Spanish has Spain, Mexico and Colombia.

The sections are set to propagate entries across sites.

When we need to create a new site, the entries from the others are created, because of the propagation, BUT they are created from the default English site. So if we create a site in say the Spanish group, it does not create the entries from the other Spanish content, but it creates it from the default site which is in the English group.

How can we create a site and have it created from the group we add it into?

Thanks


texts:
I need to access just the ID of a specific section.

I do that like this and it works:

{% set enroll = craft.sections.getSectionByHandle('workshopEnrollments') %}

But when I do:

{% for e in enroll %} {{ e.sectionId }} {% endfor %}

or:

{% for e in enroll %} {{ e.id }} {% endfor %}

I get the error:

Impossible to access an attribute ("sectionId") on a string variable ("32")

However, when I view the variable inside my form what I actually see is exactly this

32Workshop EnrollmentsworkshopEnrollmentschannel1workshop-enrollments/_entry1

So my question is, how can I just display the id.  Both ".id" and ".sectionId" produce the same error mentioned above.

"32" is the id I want so it is the correct return, but this seems to show everything about it in a string and I need just the id. I am using getSectionByHandle because I have no other data to use in this particular view.

Thanks for any help.


texts: Register a user as part of a Commerce checkout?

texts: Is it possible to register a user for a Craft user account as part of a Craft Commerce checkout flow? Ideally something where you can ask if the user wants to create an account and save their details as part of the checkout flow. Is this doable? (I'm surprised this isn't somehow in Commerce, given how incredibly prevalent such a UX flow is.)


texts:
When I run ./craft gc I get the following error:

Running garbage collection ... Exception 'yii\base\InvalidConfigException' with message 'Invalid section ID: 30'

The Section ID of 30 that it's referencing is one of the deleted

EDIT: Adding Stack Trace (Craft Pro 3.4.9):

Delete all trashed items? (yes|no) [no]:yes
Running garbage collection ... Exception 'yii\base\InvalidConfigException' with message 'Invalid section ID: 30'

in /srv/www/website.com/vendor/craftcms/cms/src/elements/Entry.php:836

Stack trace:
#0 /srv/www/website.com/vendor/craftcms/cms/src/elements/Entry.php(867): craft\elements\Entry->getSection()
#1 /srv/www/website.com/vendor/craftcms/cms/src/elements/Entry.php(812): craft\elements\Entry->getType()
#2 /srv/www/website.com/vendor/craftcms/cms/src/base/Element.php(2740): craft\elements\Entry->getFieldLayout()
#3 /srv/www/website.com/vendor/craftcms/cms/src/base/Element.php(2564): craft\base\Element->fieldLayoutFields()
#4 /srv/www/website.com/vendor/craftcms/cms/src/elements/Entry.php(1287): craft\base\Element->beforeDelete()
#5 /srv/www/website.com/vendor/craftcms/cms/src/services/Elements.php(1213): craft\elements\Entry->beforeDelete()
#6 /srv/www/website.com/vendor/craftcms/cms/src/services/Drafts.php(474): craft\services\Elements->deleteElement(Object(craft\elements\Entry), true)
#7 /srv/www/website.com/vendor/craftcms/cms/src/services/Gc.php(57): craft\services\Drafts->purgeUnsavedDrafts()
#8 /srv/www/website.com/vendor/craftcms/cms/src/console/controllers/GcController.php(56): craft\services\Gc->run(true)
#9 [internal function]: craft\console\controllers\GcController->actionRun()
#10 /srv/www/website.com/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#11 /srv/www/website.com/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#12 /srv/www/website.com/vendor/yiisoft/yii2/console/Controller.php(164): yii\base\Controller->runAction('', Array)
#13 /srv/www/website.com/vendor/craftcms/cms/src/console/Controller.php(187): yii\console\Controller->runAction('', Array)
#14 /srv/www/website.com/vendor/yiisoft/yii2/base/Module.php(528): craft\console\Controller->runAction('', Array)
#15 /srv/www/website.com/vendor/yiisoft/yii2/console/Application.php(180): yii\base\Module->runAction('gc', Array)
#16 /srv/www/website.com/vendor/craftcms/cms/src/console/Application.php(87): yii\console\Application->runAction('gc', Array)
#17 /srv/www/website.com/vendor/yiisoft/yii2/console/Application.php(147): craft\console\Application->runAction('gc', Array)
#18 /srv/www/website.com/vendor/yiisoft/yii2/base/Application.php(386): yii\console\Application->handleRequest(Object(craft\console\Request))
#19 /srv/www/website.com/craft(22): yii\base\Application->run()
#20 {main}


texts:
I have 3 freeforms - form 1, form 2 and form 3. I want a select option on which I click and the necessary form opens as per the selection.
Can I render the Freeform which are build using VUE js Select method?
If so how? Because when I try to render Craft.Freeform it shows me this error


texts: Thumbnails broken in CP after migrating images to AWS S3

texts:
I migrated my images over to AWS S3 using the Amazon S3 plugin; however, now I'm seeing that the thumbnails in the CP are broken, and a brokenimage is displayed.

The full size images display fine in the CP and the front end. If I re-upload them, the thumbnails display correctly in the CP, but that's not an ideal solution.

Is there a way to make the images display correctly in the CP without re-uploading them?


texts: Adjusting Max File Size - Stuck at 16M After Adjusting general.php

texts:
I'm adjusting the maxUploadFileSize in Craft, to 50MB.
In following the post below, I made several adjustments to both: php.ini and craft/config/general.php.
https://stackoverflow.com/questions/3263480/upload-max-size-in-php

First, I adjusted settings in php.ini:

upload_max_filesize
post_max_size

In general.php (craft/config), the following was already set:

  define('URI_SCHEME',  ( isset($_SERVER['HTTPS'] ) ) ? "https://" : "http://" );
  define('SITE_URL',    URI_SCHEME . $_SERVER['SERVER_NAME'] . '/');
  define('BASEPATH',       realpath(CRAFT_BASE_PATH . '/../') . '/');

 return array(

  '*' => array(
        'environmentVariables' => array(
        'omitScriptNameInUrls' => true,
        'siteUrl'  => SITE_URL,
        'basePath' => BASEPATH,
        'maxUploadFileSize' => 62914560,
        ),
  ),
  'dev' => array(
    'devMode' => true,
  )

 );

I know that that is around 62MB, but I keep receiving an error message saying that there is a 16MB limit on files.  All other files great than 2MB and less than 16MB now are upload-able.
Can anyone make a suggestion as to why the standard CraftCMS default of 16MB is now in place?

Thanks for any leads


texts:
I need to set up a custom route for a particular page, but can't seem to get anything to work.

For instance, I set up this route:

From what I gather, this should match just about anything... mysite.dev/hello, or mysite.dev/goodbye. But no matter what I try, I get tossed back to my index.

My only theory right now is that the Craft url structure is strange. I navigate around just fine, but there is no rewrite happening. So instead of http://mysite.dev/site-sections/we-work-on, it's http://mysite.dev/index.php?p=site-sections/we-work-on. I think this is because I'm developing on a Homestead box, which uses nginx and not apache.

Do dynamic routes depend on url rewriting?


texts:
I've got a channel named "locations" that has an entry fieldtype which allows me to select the corresponding store/brand (limited to 1).

How can I define the slug of the related entry in Entry URL Format of a locations channel?

The final result should look like this: {related-entry-slug}-{slug} of the location entry itself.

Thank you.


texts: get session data by cookies CraftSessionId

texts:
Is there a service method I can use to get (any kind of) session data by giving the cookies CraftSessionId as a parameter?

if would look something like this.
craft()->userSession->getSessionBySessionId($craftSessionId)


texts: How can I get entries where a date is within a dynamic date range?

texts:
{% set params = {
      section : 'events',
      order : 'eventStartDate asc',
      eventStartDate : '>=' ~ now,
      limit : row.itemsPerPage.value
} %}

I am trying to pull a set of event entries for a basic event calendar and I'm trying to figure out the syntax for the eventStartDate parameter to have it pull starting with the current date and ending with a value of the current date + 1 month, 3 months, or 6 months depending on the value set in another field named eventDateRange. I need help with how to write that as a command like the one listed above.


texts: Is there a way to treat variants in a similar way as products?

texts:
I'm trying to figure out if there's a way to either treat product variants as ww.site.com/product/variant or pass variables from a variant list (for example thumbnails that click to product and passes along variables for the layout of that page). Any takers?

I'm assuming it would be better to create a category > sub-category > product. Just would be great to have the same product information but be able to point to .com/pillow/green whilst returning the same basic product information.


texts: How to get latest entries, after X number?

texts:
I have a site where I want to feature the latest 5 entries and show the next 10 in a separate list. How would I do this?

The first part would be easy: craft.entries.section('news').limit(5)

But I can't figure out how to bring the next 10. Any suggestions?


texts:
Not sure if this belongs here but decided to post it after all...

I've set up a craft site (Version 3.3.x) and since we're about to add more sites to it etc, we decided to start using a project config to keep everything & everyone synced.

So per the documentation, I started out of our production site, enabled the useProjectConfigFile setting and used the cli command to build it properly, than I continued by taking a database backup and setting that backup up on our dev/staging envs.

I copied the project config to our dev env, did some changes (added a new site & sitegroup, enabled some sections for the new site) and when I tried to apply these changes to our staging env, they only partially get applied and I get the following error:

Applying changes from project.yaml ... error: Undefined index: 684d2471-bc50-4aa2-b59c-e174e8250d74

When I run the project config sync command again after that, it gives no error or so but it still did not apply the changes.

I looked in to the project.yml file for that key and it is the key for the primary site, that was unchanged.

I'd really like to keep using the project config, but I've got the feeling I missed a step somewhere or so because it only applies the changes partially.

Let me know if any extra information is desired.


texts:
So it seems that Matrix fields don't work with the object syntax so I've changed my field structure to use standard dropdowns, checkboxes and a number field.

I have the dropdown (gender) and number field (maxPrice) working fine, but I can't seem to figure out what to enter for the checkboxes. I assumed it'd be in a similar format to what I've seen elsewhere, as you can see below:

Search Results

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

{# Gender is a dropdown, so it's a single value or no value
 # - If an empty value is selected, it returns both genders #}
{% set gender = craft.request.getParam('gender') %}

{% set maxPrice = craft.request.getParam('maxPrice') %}
{% set maxPrice = maxPrice is not empty ? maxPrice : '99' %}

{% set sessions = craft.request.getParam('sessions') %}
{% set sessions = sessions is not empty ? sessions : ['skype', 'chat', 'phone', 'email'] %}
{% set sessions = ['and']|merge(sessions) %}

{% set hours = craft.request.getParam('hours') %}
{% set hours = hours is not empty ? hours : ['office', 'overtime', 'weekends'] %}
{% set hours = ['and']|merge(hours) %}

{% set results = craft.users({
  group: 'verified',
  search: "tagsSpecialismSearchable:#{tags}",
  gender: gender,
  profilePricingSession: [
    'and',
    '> 0',
    "<= #{maxPrice}"
  ],
  profileSessions: sessions,
  profileHours: hours,
}) %}

{% set users = shuffle(results) %}

Everything works except profileSessions and profileHours, which are both checkboxes. I assumed it might be that they need to be passed a key: value pair, i.e: skype: true or some other method, but nothing I've tried so far is working.

I happened on a post saying checkboxes store in a query unfriendly way, so perhaps I'm better off changing the field again for something more friendly. They'd need to be multi-select of course, so categories would be the best bet if what I'm doing isn't possible.

Suggestions?


texts: Show parents of entry in custom entries field extending BaseRelationField

texts:
The default BaseRelationField shows only the name of the selected entry in the field (e.g. "SubEntryX"). I created a custom entries field by extending the BaseRelationField in a module. Now what would be an elegant way to also show the parent of an entry in the field (e.g. "ParentEntryX > SubEntryX".
I think this would be possible by using a custom template for the field using protected $inputTemplate = 'customtemplate'; but it seems like an overkill.


texts: Craft Commerce: Sort products by Sale price

texts:
Trying to sort products by price.

{% set products = craft.commerce.products({
  type:  'footwear',
  limit: shopSettings.productsPerPage,
  order: 'defaultPrice asc',
}) %}

It works fine.

Please tell me how to sort products by Sale price?

Thanks.


texts: Client is coming from WP and is used to Elementor (https://elementor.com/). Can create own rows, columns, etc. in content. Is there a visual editor for Craft 3? Client hasn't specifically requested but think they'd like more than just rich text.


texts: Can Section access be restricted at Entry Type level?

texts:
I have a structure section that is driving the majority of a site, which works great with multiple entry types letting us handle different needs across different areas of the site.

The client now wants a new user group that can only access pages in one particular area of the site. as user group access is tied to sections without granular control of entry types within each section, that means we need a wholesale refactor of the way the site is built and managed, which is going to be a real headache at this point.

Does anybody have any approaches for this?


texts: Feed Me: How to format CSV data for a table field

texts:
Similar to the other post Feed Me: How to format JSON for a table field. I'm looking for a solution on how to format the CSV field so I can import it as a table field. Basically I have a list of products and each product has multiple serial numbers which I'd like to have each as a row in the table. So for the serial number field I've tried things like:

"[12345, 54211, 55511]"
"[{12345}, {54211}, {55511}]"
"[{"12345"}, {"54211"}, {"55511"}]"

Any thoughts on the best way to approach this field?


texts:
Are there any poll plugins available for Craft 3?
As in have radio buttons, show % results for number of people that have voted for the different options after submission.

Thanks


texts:
This is probably very straight forward but unfortunately I can't seem to solve it.

We want to create a dynamic URI structure that allows us to easily create pages and link them with parent directories. So basically we have 4-5 pages that need to be added as "singles". Then we have around 40 pages (with around 3-4 total layouts) that we don't want to create a "Single" for each. So we've created a "Structure" called Pages and inside have 3-4 entry types. Grid list, plain template, big image and small image. We just want to create a bunch of "pages" and specify the parent URI.

For example, we have a single "Our Company", but then inside that parent we have multiple pages which we want to add in the "Pages" structure. But as our Entry URI for "pages" is set to {slug} this URL is www.website.com/slug. We need it to be www.website.com/our-company/slug. Of course we can simply update the Entry URI to have "our-company" but this won't work as all of the Entry URI's for all 40 pages will be our-company.

So basically, how can we manually or dynamically specify the segment 1 that page's URI should be?


texts: Override admin template with own template

texts:
How can I override the following admin template in Craft 2?

craft/app/templates/users/_edit.html

I've tried placing the template in my own template directory, like:

templates/users/_edit.html

but this doesn't override Craft's own template.


texts: Custom Plugin forms.textareaField Redactor buttons not rendering

texts:
I am struggling with how to get Redactor to show the source and image buttons within a custom plugin. Are there only certain buttons that are allowed if you are extending textareaField? Below is the code I am using to render buttons.
{% includeCssResource "lib/redactor/redactor.css" %}
{% includeJsResource "lib/redactor/redactor.js" %}

{{ forms.textareaField({
        label: "Question Text"|t,
        id: 'question-' ~ entry.id,
        name: 'question',
        class: 'question',
        value: entry.question,
    }) }}

{% includeJs "$('.question').redactor({buttons: ['bold','italic','lists','link', 'image', 'horizontalrule'], plugins: ['alignment', 'source']});" %}

Here is what it renders

What am I missing?


texts: What would be the best way to select and display featured entries? For example, if I want to choose at least 3 entries to feature in a sidebar apart from the main content?


texts:
I can't for the life of me figure out what's going on. When assets are added, they upload fine but when I add them to entries or try to view them in the browser, they won't display and show a 403 Forbidden page instead.
Help! :)


texts:
I am getting error message while loading entries from dashboard. Please see attached screenshot -

While looking into browser console, I found the error message Request must accept JSON in response (using Craft v3.1.18)


texts: Sort entries by best match to multiple categories

texts:
I've got a channel where entries will be tagged with multiple categories. I want to use those categories to show related content for each entry.

So if an entry has cat_a, cat_b and cat_c, I want to pull in any entry that has cat_a, cat_b or cat_c, then order by how many categories they have in common – so an entry matching two of those categories would come before and entry only matching one.

Finally, I want to also sort by date. So I'd first show entries matching all 3 categories (newest first), then entries matching 2 categories (newest first) etc...

Any thoughts on how to do this?


texts:
I have 3 locales set up - en_ca, fr_ca, en_us.  en_us was selected when installing Craft.  I had to change the default locale to en_ca and did so in general.php after installation.  I'd like this change in the CP as well.  Currently, entering new entries and the CP site link all still point to en_us.

How can I change the default locale?


texts: Changing the name of the Craft folder when placed above the webroot?

texts: Can you change the name of the Craft folder? I run several sites on a VPS and to place the Craft folder above the webroot, means that it sits in the User Directory, which has multiple domains running and potentially more domains could run Craft CMS and therefor the Craft folder(s) would conflict if they are all placed in the User Directory.


texts: How to set and test a variable in child template to modify a block in parent template

texts:
I would like to load some javascript on specific pages only.

I'm trying to set a block in my parent template, then test a variable and include the javascript in the child template only when necessary.

I thought I could do this by declaring the variable beforehand, to make it  accessible outside it's scope, but this is not working (nothing is returned):

Parent '_layout' template:

<html>
    <head>...</head>
    <body>

        {% block content %}
        {% endblock %}

        ...

        {# site-wide script #}
        <script src="global.js"></script>

        {# page-specific script #}
        {% block script %}
        {% endblock %}

    </body>
</html>

Child template:

{% extends "_layout" %}

{% set page_assets = '' %}

{% block content %}
...
{% set page_assets = 'true' %}
...
{% endblock %}

{% block script %}
    {% if page_assets is defined and page_assets is not empty %}
      <script src="page-specific.js"></script>
    {% endif %}
{% endblock %}


texts: Just wondering there is current any way to control the order of navigation items in the Control Panel. Obviously not a deal-breaker, but was just interested in being ultra-crafty in my Control Panel layout for clients :)


texts:
I have created several asset sources in craft and now i created user groups, with different view rights to this sources. When a user with restricted rights goes to the "assets" tab in craft, the rights management works as excepted: the user only see assets sources, where he has access to. But in redactor wysiwyg editor, using the insert image button or link to a asset function, it shows always all asset sources, even if the user has no view access to. Is there a way to restrict this list, based on users "view" permissions?  Maybe i missed it and there is something like a global config option (for example: restrictAssetsInRedactor = true)?

When i look in firebug, i see, that the modal window is called without any sources. Is there a way to modify/overwrite this call with a custom plugin?


texts: Prev/Next Buttons not showing in a multipage form

texts: How can i achieve that the next/prev buttons appear in a multipage form ?


texts: Is there a way to compare what has changed on an entry while it's being saved?

texts:
I'm taking my first baby steps into the php side of Craft, and my php experience in general is extremely fledgling. But I'm pretty much forced to create a module for a project I have, so here I am flailing around in a space I know virtually nothing about. So thanks for reading.
Basically, I need to send notification emails based on specific (very specific) user actions. Right now I have it running so that I'm catching the EVENT_AFTER_SAVE event in my module's init() function and successfully sending out emails with the Mailer. So that's good. But the issue is I need to be able to see if certain fields have changed on entries to know what email to send out.
Is there a way to compare the pre-saved and post-saved entry, or maybe alternatively to catch the fields that are being sent to /entries/save-entry to determine what the user is doing? I know it's probably likely that what I really should be doing is creating my own controller and/or action that I use on my templates in places that designate what action should be taking place, but I'm so barely holding on to comprehension of what I'm doing as-is that I'd prefer to create something caveman simple first before trying to give it better coding practices. But I'm also open to any advice at all on how to proceed.


texts: Pagination / Custom Routes (Based on Entry Existing)

texts:
I've created a custom route for my entries based on week like so:

'events/(?P<year>\d{4})/(?P<week>\d{2})' => 'events/_weekindex',

I know i can group entries by week like this:

{% set allEntriesByWeek = allEntries|group('postDate|date('Y-W')') %}

What i'm not quite sure how to do is how to show navigation ONLY for weeks that have entries present, and then of course output the entries in my template when those navigation items are clicked.


texts: New Install, Permission Errors With /storage

texts:
I've configured Apache vHosts on a local box and installed a Craft 3 website onto it. This new instance will serve as my "staging" environment for an upcoming website.

I've installed with composer from a Git repo of my work-in-progress site.

Everything installed fine, and I can access the site through my browser. However, the site displays the error message:

  /var/www/vhosts/wine/storage isn't writable by PHP. Please fix that.

Now, I've run into this before, normally I would just chmod 775 and chown the folder to apache. But, this isn't working. I've even chmod 777 on the folder and it still gives me the error message.

An ls -la on the storage folder gives me (currently 774):

drwxrwxr--.  2  apache apache

This should be working.
I've been at it for 4 hours, and I'm at a loss. If anyone has any ideas, please let me know.

CentOS 7
Apache 2.4.6
PHP 7.2.20


texts: How can I change CP language in Craft 3 after installation?

texts: I saw how I can change system language (CP) after installation in Craft 2, but I can't find how to do it in Craft 3.


texts:
I want to check if there is a number less than 10 in an array.

{% if 10 in [0, 30, 50, 10, 9, 200]  %}
  {# checks only if there is a 10 in it. not if there is anything below 10. #}
   yep. there is a number 10
{% endif %}

That's close, but I want to find find out if there is any number below 10 in it, disregarding how many.

Not possible: {% if 10 > in [0, 30, 50, 10, 9, 200] %}

Also not possible: {% if > 10 in [0, 30, 50, 10, 9, 200] %}


texts: Filter results by users contained in a Users Relations RelatedTo field

texts:
I would like to exclude entries from appearing in the template results that contain Users from specific User group.

My code below works if all the User(s) in the RelatedTo field are part of the excluded User group, but it doesn't work if the field contains Users from both the excluded group and a non-excluded group.

{% set excludeFellows = craft.users.groupId('not 11') %}

{% set entries = craft.entries.section('logsQA').logGeneral_statusWorkflow('submitted').relatedTo(
    { targetElement: excludeFellows, field: 'logGeneral_sonographerName' }
) %}

(Also if it's better to check for specific User IDs rather than a User Group for my excluded list that's fine too. I only have 3 Users to exclude.)


texts: How to troubleshoot Inline Image Transform when there is no error logged?

texts:
Having some odd issues in 2.5 with image transforms (apparently). They are defined in the template, and saved to a Rackspace Cloud Files container. Often, we are getting a 500 Internal Server Error when loading the page or doing a live preview, and nothing about the error is logged anywhere. Trying to figure out how to troubleshoot this. Happens on our production (apache) server, not seeing it on my dev/MAMP machine.

We do have this set in general config:

'generateTransformsBeforePageLoad' => true,

The server is running Ubuntu 14.04 and has ImageMagick 6.7.7-10 2014-03-06 Q16

The dev machine (which will transform the images just fine) is running MAMP and does NOT have ImageMagick installed (it does use GD though).


texts:
I use Matrix to select products through a "Commerce Products" field type.

In the template, the following code displays nothing (not even an error in devMode.)

{% for block in entry.MatrixHandle %}
    {% set relatedProducts = craft.commerce.products.relatedTo({
        targetElement: entry, field: 'BlockTypeHandle.FieldHandle'
    }) %}

    {% for entry in relatedProducts %}
        {{ entry.title }}
    {% endfor %}

{% endfor %}


texts: How do I write custom model validators for my plugin that refer to other fields?

texts:
I'm looking at this guide to writing custom validators:
https://experiencehq.net/blog/the-definitive-guide-to-validation-in-craft-part-5-custom-validators

However, this only allows code that refers to the current field.  The comparison validators exist so I know it's possible.  I want to do a CVV and credit card number validator that check against the credit card type, and also make some fields conditionally required.

In this example only the attribute itself is referred to:

public function validateUsername($attribute)
{
    $value = $this->$attribute;

    if ($value && strtolower($value) == 'spartacus') {
        $message = Craft::t("No, I'm Spartcus!");
        $this->addError($attribute, $message);
    }
}

How do I refer to another field in the model in my validator?


texts: Need to make a wish list / favourites system

texts:
Has anyone made a plugin which allows for a visitor/user to remember an entry and then see a list of them?

I need to make a "short list" page for our new site.

I was sure there was a plugin that did this, but I can't for the life of me find it anywhere now!


texts: Displaying a list of fields in a form select

texts:
In a plugin's settings view, I'm looking to show a list of fields to choose from:

{% set fields = craft.fields.getAllFields() %}

{{ forms.selectField({
    label:          'Salary Mapping'|t,
    id:             'broadbeanSalaryMapping',
    name:           'broadbeanSalaryMapping',
    instructions:   'Choose a field in which to store this value.'|t,
    value:          settings.broadbeanSalaryMapping,
    options:        fields,
    errors:         settings.getErrors('broadbeanSalaryMapping')
}) }}

However I get an error:

  Craft\FieldModel and its behaviors do not have a method or closure named "optgroup".

Am I going about this the wrong way?


texts: If Conditional for Lightswitch in Matrix Field

texts:
I have a section that needs to display a certain block type (heroVideo) if a lightswitch (displayHeroVideo) within it is active. Otherwise, it should display a different block type (heroImage).

How can I write a conditional to accommodate this?

Here's what I have already which outputs both blocks if the lightswitch is active. How do I apply the conditional earlier?

{# Start hero section #}
{% for entry in entry.heroFeatured.limit(1) %}
  {% for block in entry.hero %}

  {% if block.type == "heroVideo" and block.displayHeroVideo == "1" %}

Hero Video Markup

  {% else %}

Hero Image Markup

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


texts: Is there a way to output the events that belong in a month after a specific date using the Calendar plugin by Solspace?

texts:
I would like to get the events with all their occurrences that belong to a specific month but ignore any of those occurrences before a certain date.
From the documentation, the dateRangeStart parameter should the trick but it doesn't work for me. The following query returns all events starting from December 1st.

{% set month = craft.calendar.month({
    dateRangeStart: '2017-12-17',
    calendar: calendarHandle
}) %}

Any help?


texts: Craft Commerce one time billing address creation

texts: Could it be possible in Craft Commerce to let an admin create a customer with a one time set billing address and that the customer can only set shipping address in the order process?


texts: Possible to change view of related entries field?

texts:
Is it possible to change the display of the related entries field, to include extra info (hoping to add thumbnail, because otherwise these entries are damn hard to identify!)

I don't think they are quite the same as a standard table view and therefore hookable by defineAdditionalEntryTableAttributes
Or can you override the normal view of the field type?


texts: Is there any way of setting / forcing a default image transform for images inserted via rich text blocks?

texts:
I have an image transform that is designed for images inserted into posts, and I'd like to make sure this is always applied to any image in a post. The problem I'm having is that for images inserted via Rich Text Fields, selecting a transform is optional, and the wrong transform may be selected.

Ideally I'd like to set a default transform so I can tell content editors that they can insert images directly into posts and don't need to do anything with the "Select image transform" option... is there any way of doing this, though? Any help or advice would be much appreciated!


texts: Craft Commerce - Bad Request The CSRF token could not be verified

texts:
I've been following the Craft Commerce tutorials at Mijingo, (running on CraftPro 2.6.2983) all good so far, except when I go add a product to my cart. I'm getting a "CSRF token could not be found" error.

The debug message with dev mode on reads:

  Warning: Declaration of Craft\UserSessionService::login($username, $password, $rememberMe = false) should be compatible with CWebUser::login($identity, $duration = 0) in /Users/username/projectname/craft/app/services/UserSessionService.php on line 17

  Warning: Declaration of Craft\UserSessionService::afterLogin() should be compatible with CWebUser::afterLogin($fromCookie) in /Users/username/projectname/craft/app/services/UserSessionService.php on line 17

Is there a step or setup option I'm missing? Atm, it's running on Mamp, but I want to make sure it's workable before I license up and go live.


texts: So I want to hide certain items if a user is not logged into the website. I already have a custom lightswitch field on each of the items but I'm not sure on how to write the code for it. Can anyone help?


texts:
I'm building a Vue.js site with Craft as the backend, which works pretty well so far. The only thing I can't get to work yet is live preview.
Vue-Router relies on the window.location which is flawed in live preview (https://example.com/admin/entries/pages/1-homepage instead of https://example.com/homepage). Is there any way to get this right?

Update: A new issue popped up. About to test things, I noticed the content does not change because - obviously - I pull it from the Element API, which pulls it from the database. I'll update my answer below when I've found a way around this.


texts: Check if submitted email address belongs to a user account

texts:
How could I go about allowing a (not logged in) guest user to submit their email address, check behind the scenes if it belongs to a user account, and then return:

A login form if it does
A registration form if it doesn't


texts: Can Craft handle social-esque frontend user interactions?

texts:
I've got a potential client I'd like to build a Craft site for, but they have some specific features I'm not quite sure how to handle. Could someone tell me if Craft can handle the following features?

Frontend ability for users to create and join "groups". "Groups" is in quotation marks since I don't think they need to be actual Craft User Groups; they don't need differing permissions, just segregation—so Categories, perhaps, or Tags?
Frontend ability for users to invite others to specific "groups"—basically an email-a-friend a link with a signup/login token that will add them to the specified group.
The ability for users to have their own blog on the site, where other users can comment. I'm fairly certain Craft can do separate author-specific blogs natively, as it's essentially just a listing page of a specific author's entries. I also know comments are either Disqus or the Comments plugin by Engram Design. I'm leaving this point in here though because I haven't done this in Craft yet, so I'm blissfully unaware of any gotchas there may be... ;)

Thanks for any help!


texts: Prepping a field's value from a fieldtype before it hits Craft\BaseModel->__set()

texts:
I'm trying to create a FieldType that takes a POSTed day/month/year array and saves it into a datetime column, but I think because of the column type it's tripping up before it ever gets to prepValueFromPost().

So far I'm extending Craft\DateFieldType, which defines the content attribute as AttributeType::DateTime for me, and I've got my prepValueFromPost() function:

public function prepValueFromPost($value)
{
    if ($value)
    {
        $value = join('-', array($value['year'], $value['month'], $value['day']));

        return parent::prepValueFromPost($value);
    }
}

To work it into a string that DateFieldType::prepValueFromPost() can use (probably). The issue is, during $entry->setContentFromPost($values), it first sets the raw post content (an array) to the attribute:

/vagrant/craft/app/models/BaseElementModel.php(888): Craft\BaseModel->__set("userDateOfBirth", array("day" => "01", "month" => "1", "year" => "1986"))

Which then looks at the column type for that field, sees its a DateTime and tries to shoehorn my array into createFromString:

/vagrant/craft/app/models/BaseModel.php(349): Craft\DateTime::createFromString(array("day" => "01", "month" => "1", "year" => "1986"))

Which is no good. And all this happens before my fieldtype's prepValueFromPost() ever gets called, so I'm not sure what to do :(


texts: Passing variable from block within including template

texts:
I have this situation, where variable param doesn't exist.

skeleton.twig

{# Inject template #}
{% block var %}{% endblock %}
{% include '_includes/template' %}

Now I want to extends index.twig with skeleton.twig and output all rendered data.

{% extends "skeleton" %}

{% block var %}
    {# Set parameter #}
    {% set param = {
        section: ['handle1', 'handle2']
    } %}
{% endblock %}

template.twig

{% paginate craft.entries(param) as entriesOnPage %}
    {# data #}
{% endpaginate %}

As I go step by step in rendering process, I think, that the reason Why I'm getting this problem is because, the ECM is printed after {% include '_includes/components/feed/feed' %}.

Otherwise I have no idea, except I put wrong craft.entries(param)


texts: SimpleMap plugin - How to render it on a webpage?

texts:
This question is coming from a complete noob, so pls bear with me.

I am using SimpleMap plugin in a Craft site. I am able to install and configure the plugin, create a field, add it to a section etc. I am not sure how to embed the map as shown in CP, into an article on the site.

In short How to display the map frontend as it is displayed in the control panel?


texts:
I’m trying to setup responsive images with the imager plugin, that has 100% width on mobile sizes and then the images are in a 3 column grid on tablet and desktop. But although I’ve got the code outputting the three sizes, the browser is only showing the largest one at all sizes. So can someone see what I’ve done wrong in the following code

      {% set image = row.image.first() %}
      {% set transformedImages = craft.imager.transformImage(image,
          [
              { width: 360, ratio: 4/3 },
              { width: 294, ratio: 4/3 },
              { width: 720, ratio: 4/3, jpegQuality: 60 },
          ],
          {
              format: 'jpg',
              allowUpscale: false,
              mode: 'crop',
              jpegQuality: 80,

              interlace: true
          }
      ) %}
      {% if image | length %}
      <img class="img-responsive"
           src="{{ transformedImages[1].url }}"
           sizes="(min-width: 768px) 33vw, 100vw"
           srcset="{{ craft.imager.srcset(transformedImages) }}"
           alt="{{ image.title }}"
           width="100%">
      {% endif %}

I’m assuming it’s to do with the sizes="(min-width: 768px) 33vw, 100vw" So the 360 width is desktop, and the 294 width is tablet, and the largest size of 720 width is mobile to account for the 2x density.


texts: Main email address for "Contact Us" in settings is not changing

texts: we have a contact section on our website which is going to an info@ email address.  I need to change this to my email.  I have gone to Globals - Settings - Email address and changed it there, but when I sent a test email it didn't work.  Could you please tell me if I need to try a different section?  Thanks!


texts: How can I create a section or category in Craft 3 that shares its entries (i.e. not multi-site)?

texts: Is it currently possible to create a section or category that shares the same entries across multiple sites? I can currently create a section, and once I save an entry, it is propagated to all sites.  However, those entries are then unique to each site.  I'm looking for a way to share a section's entries across multiple sites so that if an entry is modified, those changes are shared and reflected across all sites.


texts: How to target Sub-Category of Sub-Category

texts:
I have 2 Main Groups of Categories, which themselves have Sub-Categories.
The Categories you see have checkboxes to filter entries below.
One Sub-Group has also Children (With Material/ Without Material) ->Screenshot.
I need to collapse these two groups (on click they open/close).
How can i target these Sub-sub-Category Groups?
Right now i use:

{% ifchildren %}
 <ul class="subcategory-list">
   {% children %}
 </ul>
{% endifchildren %}

I tried some with siblings but cannot get it to work. I also need to add extra html fot the arrow to indicate the collapse and to open the sublist.
 If i add it right now, it gets added to all category-groups.
Thanks.


texts: IS there a way of getting redactor to accept text pasted from arabic in a right to left flow? Should this be solved with custom style for editor based on locale? (Am already doing RTL direction in front end based on locale)


texts: Problem setting security key when installing Craft 3

texts:
I'm new to Composer and am using a Mac along with MAMP as a local web server. I've installed Composer but it's referencing an old PHP 5 version that must be the default on my Mac.

I was able to install Craft 3 via Composer by adding the --ignore-platform-reqs flag as per https://docs.craftcms.com/v3/installation.html#downloading-with-composer

The Craft 3 starter project files were all added successfully. However, at the end of the install output in terminal was the following:

@php craft setup/welcome
Craft requires PHP 7.0 or later.

If I navigate to the project install directory and try running ./craft setup I get the same message "Craft requires PHP 7.0 or later".

The installation docs did say you could alternatively edit the .env file directly, so I entered the database details in there instead. But when I went to access the browser install wizard, I got errors about the security key being missing.

Now I worked around that by just generating a random 32 character string myself and entering this for the SECURITY_KEY setting in the .env file & was then able to complete the install wizard.

However, I'm wondering if that is OK to do? I'm concerned that there may be a particular format needed etc and that just pasting in my own key could cause issues down the line.

Ideally I'd prefer to be able to just complete the standard setup via terminal instead and have the key config automatically set there. Is there a way I can get the craft setup command to use the newer PHP 7+ available from MAMP? Or is there an easy way to update the default PHP version Composer references without disturbing the rest of my Mac?


texts:
I have created an Asset field type and have the "restrict file types" option not checked.

When I attempt to upload a file with extension .PSD i get the message Upload failed for 020516_Action-Buttons_Desktop.psd. The error message was: “Error uploading the file: This file type is not allowed”

Is there a setting someplace else thats preventing this?

I also tried checking the restrict option and selecting "Photoshop file". But this also did not work.


texts: When building a site locally and linking to entries in redactor fields, all of the links are being saved in the database with links to my local dev server (http://mysite.test/path/). Is there a config setting or any way to have these links be dynamic and use the {siteUrl} path instead of being hard-coded to the dev url?


texts: What's the best way to get all content for a field?

texts:
Given an array of field IDs, I want to get all content for those fields.
So, in this situation:

entry 1

field ID 1: 'test'

entry 2

field ID 1: 'test test'

I want to end up with array('test', 'test test').
I now iterate through all content from the content table to check the field's handle against the handle of the field I'm looking for, but there must be a better way.

See this service to see what code I use now.


texts:
I'm in a situation where I have a handful of matrix blocks which have similar subfields. For example, I have a "Bios" block where there's an intro etc., but the a few repeating fields, imagine:

Bio 1 Name (bioName1)
Bio 1 Image (bioImage1)
Bio 2 Name (bioName2)
Bio 2 Image (bioImage2)
etc. up to 6

In my template, I have some pretty redundent code when outputting these fields, like:

    {% if block.bioName1 %}

            {% for asset in block.bioImage1 %}

            {% endfor %}

{{ block.bioName1 }}

{{ block.bioTitle1 }}

            {{ block.bioText1 }}

    {% endif %}

    {% if block.bioName2 %}

            {% for asset in block.bioImage2 %}

            {% endfor %}

{{ block.bioName2 }}

{{ block.bioTitle2 }}

            {{ block.bioText2 }}

    {% endif %}

I'm wondering if it would be possible to somehow set this up as a loop with a counter to increment the vars (the field names always end with the count)? Any ideas? I tried a few things but have had no luck :/


texts:
I'm having trouble in the control panel. I'm get logged out all the time and I can't find the reason. The "Your session has ended" modal window appears all the time, I can just do a refresh and it stays in the control panel (logged in). Sometimes i'm also thrown out completely.

What did i tried to solve it (together)

'overridePhpSessionLocation' => true or false doesn't seem to make a difference
removed my cookies
craft/storage/runtime is on 777
removed database content of craft_sessions
removed craft/storage/runtime multiple times, it's created again.
craft/storage/runtime/sessions stays empty and is on 777

This is the error in the log files:

  2016/02/09 20:31:12 [warning] [application] Tried to restore session from a cookie, but the given hashed database token value does not appear to belong to the given login name. Hashed db value: cf349cc791478ab96e9229dad6367f1358f1404bczozMjoiMGQ0SUJxelZYYmdNUVh6WDhVdHhBODFUb0lWb2dGT0wiOw== and loginName: REDACTED

(I edited the question to narrow down the problem. it's kinda driving me nuts)


texts:
I'm having this weird issue that both of my custom plugin logs are not working but all other third party ones including craft.log work fine. By 'not working' I mean the log file is generated, but empty.

Another weird thing is the issue only happens on production environment. Tested on local environment and staging environment, they all work fine.

I believe I got the code right?

MyPlugin::log("Errors:\n\n" . print_r($fieldsData, true), LogLevel::Error);

It's Craft 2 by the way.

Anything ideas?


texts: Can't include relative JS file from layout

texts:
I'm trying to include the videojs.thumbnails.js file in my layout.html:

<script src="./videojs.thumbnails.js"></script>

It's located at the same level.

I am getting the following error: http://localhost:3000/videojs.thumbnails.js 404 (Not Found)

Any ideas what I am missing?


texts: How do you output images without "?mtime" at the end of the url?

texts: For some rss readers they have issues with the images having "mtime" at the end of the url.  Is there a way to output an image without this?


texts: How to get my license.key after deleting it via Git

texts:
I purchased a Craft Client license for a staging server we have, which uses Git for deployment.

Unfortunately, I forgot to copy the license.key file to my local copy of the site before my last git push, and it got clobbered.

Is there a way to retrieve my license? I have contacted Craft support, which I assume is the only way to get it back, however if there is a way to get it back on my own that would be helpful.


texts:
I have been trying to access craft\commerce\services\Gateways; from a plugin but I can't figure out how I need to access it. I've used the following:

$gateways = Commerce::getInstance()->commerce->getAllGateways();

$gateways = craft\commerce\services\Gateways::getAllGateways();

The first one says Getting unknown property: craft\commerce\Plugin::commerce and the second one tells me
Non-static method craft\commerce\services\Gateways::getAllGateways() should not be called statically

Can anyone tell me the proper way of doing this? Thanks!


texts: How to move Craft from a subdirectory to public_html

texts:
I have my Craft 3 site all up and running on domain.com/2/

I need to move it to just domain.com

The Craft files are all one level above public_html like they should be. Not sure what I need to change to bring everything from /2/ to the root level. Would like to avoid installing a fresh copy of Craft if possible.


texts: Filter Sprout Forms entries based on field value, using parameters

texts:
I'm trying to display form entries from Sprout Forms that match a specific criterium:

{% for formEntry in craft.sproutForms.entries.formHandle('formHandle').fieldname('fieldvalue') %}
    {{formEntry.fieldname}}
{% endfor %}

This does not filter the entries.

This works:

{% for formEntry in craft.sproutForms.entries.formHandle('formHandle') %}
    {% if fieldname == 'fieldvalue'%}
        {{formEntry.fieldname}}
    {% endif %}
{% endfor %}

Can this not be done with parameters, or am I using the wrong Entry model?


texts: Users, by default, do not have middle names. So let's say I create a table with a foreign key linking to the user id, this table will contain middle names. How would I tell craft to join the middle name data? Could I create a plugin with a hook that gets middle name whenever user data is pulled? Where do I begin?


texts:
My database was corrupted after updating to 3.1.0 and no backup. Is there any script to move fields, sections and other staff to new fresh database?

Update
I found something like this scripts, but its not that one I needed


texts: How to set up {siteUrl} to work with both http and https

texts:
I'm looking for a way to set up the general.php file's siteUrl to be able to use both http and https. Only the front-end login would be using the https. This is how I currently have it set up:

'mysite.com' => array(
    'cooldownDuration' => 0,
    'environmentVariables' => array(
        'siteUrl' => '//mysite.com/',
    )
)

The problem with this is when the front-end form is submitted and the user is redirected, the url messes up (i.e.: mysite.com/mysite.com/page-name)

Any suggestions would be great!


texts:
I have two queries on related entries (using Many to Many plugin) to find both related and then reverse related entries:

{% set relatedArticles = article.relatedArticles %}

{% set reverseRelatedArticles = craft.entries.relatedTo(article) %}`

I want to merge these two ElementCriteriaModel, removing any duplicates before processing them further. I've tried this:

{% for item in reverseRelatedArticles %}
    {% if item not in relatedArticles %}
        {% set relatedArticles = relatedArticles|merge([item]) %}
    {% endif %}
{% endfor %}

But it doesn't remove the duplicates. Adding find() to the queries to turn them in to an array doesn't work either. Any way I can do this?

EDIT: I tried this, too:

{% set relatedArticles = article.relatedArticles.find()|merge(craft.entries.relatedTo(article).find()) %}


texts: Correct way to set up development and production environments for Craft?

texts: I'm setting up a new site using Craft and would like to know what's the best way to manage dev and production environments? For instance, keeping entries/fields/ and control panels configurations sane across both environments?


texts: How can i get the current applied route in CraftCMS?

texts:
I'm using a dynamic route that loads a template. I'm on a multisite setup with a language switch in the header menu.

To be able to switch between sites or languages, the dynamic routes need to have some sort of connection.

I figured out you can define routes in a site-specific context and add extra attributes (e.g. 'name') like this:

//routes.php file
return [
  'enSite' => [
      'example/{tag}' => ['template' => 'example/_index.html',
                          'name' => 'example',
                         ],
  ],
  'nlSite' => [
      'voorbeeld/{tag}' => ['template' => 'voorbeeld/_index.html',
                            'name' => 'example',
                           ],
  ],
];

Now I can tell craft that the routes with the same name are variants of each other for the language switcher.

All i need now is the "current applied route". I can't find this information anywhere. I was expecting it in craft.app.requestedRoute, but that's not the case.

Does anyone know how to get the current applied route in Craft?

Others with similar issues loop over craft.app.routes.getConfigFileRoutes and match on the route keys, but with tokens like {tag} in your roue this is not an option.


texts: Second Site Channel URL Route Not Working

texts:
I've set up a Resources section on a multi-site installation with the type of Channel. For Site 1 I've set the routing rule to be {resourcesParent.one.slug}/{slug} and for Site 2 I've set the rule as {slug}.

So for Site 1 a resource titled sample-resource would resolve to www.example.com/parent-slug/sample-resource.

And for Site 2 it would resolve as sub.example.com/sample-resource

Everything works fine for Site 1, however when I go to sub.example.com/sample-resource I get a "template not found: sample-resource" 404 error.

Seems like this should work so I'm not sure what I'm doing wrong.

EDIT: I just noticed that sub.example.com/parent-slug/sample-resource is resolving, so I think something's wrong with my config. Here's what I have for my dev environment in craft/config/general.php:

'dev' => [
    'siteUrl' => array(
        '//www.example.com',
        '//sub.example.com'
    ),


texts: Use sidebar nav icons in modules and plugins

texts:
When adding a navigation item, there is the option to specify an icon, but it seems to have to be a path to an SVG. I can see that Craft has its own icon library, and it has an icon I want to use.

I want to use the "mail" icon, so I tried this HTML:

'icon' => '',

this is inside my registration of the navigation item:

Event::on(
    Cp::class,
    Cp::EVENT_REGISTER_CP_NAV_ITEMS,
    function(RegisterCpNavItemsEvent $event) {
        $event->navItems[] = [
            'url' => 'contact-enquiries',
            'label' => 'Contact Enquiries',
            'icon' => '',
        ];
    }
);

However, it doesn't show the icon.

I can't see anywhere in the docs that explain how to use these icons in your own navigation items, so is there a way to do it? It'd be a lot easier than having to include an SVG that doesn't match the other icons.


texts: Sprout Forms: empty phone field still shows error "Phone is invalid. Example format: (506) 234-5678"

texts:
Running Craft CMS 3.3.20 and Sprout Forms Pro 3.6.8

form has Phone field
submit form with no value in Phone field
form reloads with error message "Phone is invalid. Example format: (506) 234-5678"

If valid phone number entered form submits fine.


texts:
I'm building a site that is driven by Craft Commerce but does not take payment online. Rather, the customer adds what they need to a cart and submits to the company for a quote.

I need to build a contact form that allows the customer to submit their name, email, phone, and company name. When submitted, the form should also turn the cart into an order. I've tried setting 'isCompleted' to 'true' and setting the 'dateOrdered' but cannot seem to get the cart to transition into an order.

Below is the code I've been testing to try to get the cart to convert into an order. I feel like I'm missing something obvious. Any advice is appreciated.

<form method="POST">
    <input type="hidden" name="action" value="commerce/cart/updateCart">
    <input type="hidden" name="isCompleted" value="1">
    <input type="hidden" name="dateOrdered" value="{{ now.format('Y-m-d H:i:s')}}">
    {{ getCsrfInput() }}

    <input type="submit" value="Submit">
</form>

Edit: Here's the working code as suggested below, where "2" is the ID of the manual payment method I created.

<form method="POST">
    <input type="hidden" name="action" value="commerce/payments/pay">
    <input type="hidden" name="paymentMethodId" value="2">
    {{ getCsrfInput() }}

    <input type="submit" value="Submit">
</form>


texts:
I have created a field named inlineCss, which i'm using to set a pageCss variable. However, when no CSS is added to the entry, the {% includeCss pageCss %} is still adding a style tag in the head, albeit empty.

{% set pageCss %}
    {{ entry.inlineCss }}
{% endset %}

{% includeCss pageCss %}

Is there a way to only show the style tag if the pageCss variable is not empty?

I've tried checking for is defined and not null but it just keeps outputting the empty style tag.


texts:
Is it possible to include plural variations? For example if I search for 'apple' but the entry includes 'apples' it appears.

Or would this need to be approached by getting these variations into the entries via tags or similar?

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search(query).order('score').section('newsEvents') %}

{% if entries|length %}

{{ entries|length }} result(s):

    {% for entry in entries %}
         ...
    {% endfor %}

    {% else %}

Your search for "{{ query }}" didn't return any results.

{% endif %}


texts:
I have some content I wish to output in the main parent _layout.html template. Seems like something simple to achieve but can't seem to figure it out. If I call {{ entry.bannerLabel }} etc it throws twig runtime errors.

I'm wondering if it's because it's outside of the {% block content %} section of the template?


texts: Plugin (SyncDB) issue breaking site and unable to do anything

texts:
I was in the process of setting up the UNION co SyncDB plugin and must have misconfigured something as I now get the following error: "Undefined index: skipTables" and seem to be completely locked out of both the admin and site.

This is the first time I've encountered something like this where I got completely locked out (I would have assumed I'd be able to still access admin to disable the plugin manually) and now have no idea how to disable the plugin and either load the site or get into admin.

Help would be very much appreciated.


texts:
I have a field in a matrix block that is used for video embed codes. I want to output the contents of that field directly as HTML. However, it always seems to get entity-encoded (ie. the < and > get converted to &lt; and &gt;), so the html just appears as text.

I know about Twig's |raw filter, so I tried outputting the field's content through it (eg. using {{ element.blockContent|raw }}), but it seems to make no difference. Can anyone tell me what I'm doing wrong?

(Just in case it's relevant, this is a sub-template that is being included in a for loop that goes through the matrix blocks and outputs them)


texts: Templating - printing entry.url throws js error when trying to embed Disqus?

texts:
Default Disqus embed code includes the following:

var disqus_config = function () {
    this.page.url =   // Replace PAGE_URL with your page's canonical URL variable
    this.page.identifier = {{ entry.section }}-{{ entry.id }}; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};

I am trying to use this.page.url = {{ entry.url }}.  This prints the url, but it includes the http:// and the : is throwing an error preventing Disqus from loading.  Is there anyway to template the url without the http://????

Note that the config I am using is straight from Disqus.  The CraftCMS knowledge base article does not include this-page.


texts: How do you limit the number of items that show up in a navigation?

texts:
I have a nav set up which works find but I need to limit the number of top level links to the first 5 in the loop (right now we have 9 plus oodles of children links!). Have tried various flavours of loop.index etc but have run out of ideas.

Here’s my basic nav code:

{% set ppages = craft.entries.section('productPages').level('<=2') %}

  {% nav page in ppages %}

      {{ page.getLink() }}
  {% ifchildren %}

      {% children %}

  {% endifchildren %}

  {% endnav %}


texts: Issue accessing single entry from within category template

texts:
I've got a product section on a website where individual product entries are categorised. On the section landing page all the products are listed organised by category. On the individual category pages only the product entries relevant to that category are shown.

The issue I’m having is that for the category landing page I want to pull in the Section landing page content. However when I try the following:

{% set entry = craft.entries.section(‘productsAndMarketsLandingPage’).first() %}

{entry} returns empty. Any thoughts why this isn’t being pulled into this particular page/template? I can access it just fine from within the

The section, template and URL structure is as follows:

Section landing page
url: /products-and-markets
template: /products-and-markets/index
section: productsAndMarketsLandingPage

Category landing page
url: /products-and-markets/{slug}
template: /products-and-markets/_category
section: productsAndMarkets

Product entry page
url: /products-and-markets/{slug}
template: /products-and-markets/_entry
section: productsAndMarkets

Cheers in advance,

Cole


texts: I made a custom field type (two datetime fields for starting / ending time). They have the good value when I loop in value in an entry, but have null value in Live Preview. Do you have an idea of what can cause that?


texts: How do I add a value to a tag field type using the entries service saveEntry method?

texts:
I am updating an entry using the entries service, I want to add a tag value into a tag field type (classifiedTags).

$entry = craft()->entries->getEntryById(120);
$entry->getContent()->classifiedTags = 'tagtest';
$entry->title = 'Updating title to this';
$entry->getContent()->description = 'this is the new description';
craft()->entries->saveEntry($entry);

It runs and updates everything except the tag field (classifiedTags).

If I change it from a string to array like below:

$entry->getContent()->classifiedTags = array('tagtest');

It gives me this error:

  CDbCommand failed to execute the SQL statement: SQLSTATE[23000]:
  Integrity constraint violation: 1452 Cannot add or update a child row:
  a foreign key constraint fails (ggmg_craft.craft_relations,
  CONSTRAINT craft_relations_targetId_fk FOREIGN KEY (targetId)
  REFERENCES craft_elements (id) ON DELETE CASCADE). The SQL
  statement executed was: INSERT INTO craft_relations (fieldId,
  sourceId, sourceLocale, targetId, sortOrder, dateCreated,
  dateUpdated, uid) VALUES (:row0_col0, :row0_col1, NULL,
  :row0_col3, :row0_col4, :row0_col5, :row0_col6, :row0_col7). Bound
  with :row0_col0='43', :row0_col1='31823', :row0_col3='tagtest',
  :row0_col4=1, :row0_col5='2016-07-14 21:16:04', :row0_col6='2016-07-14
  21:16:04', :row0_col7='d2228ed9-cc60-478d-929c-98efd776b63c'

Which leads me to believe I am getting warmer.

Craft CMS v 2.6.2796
PHP v 5.6.13


texts: Craft 3 query children of sub categories

texts:
Just wondering how to only query the children on subcategories. For example...

Food
├── Fruit
│   ├── Apples
│   ├── Bananas
│   └── Oranges
└── Vegetables
    ├── Brussels sprouts
    ├── Carrots
    └── Celery

I only want to query the children directly of fruit without having to get all of the food then have to loop around. As this isn't the best practice.

I thought it would be something like ...

{% set categories = craft.categories()
.group('food')
.ancestorOf('fruit')
.all() %}

Thanks in advance.


texts:
I scrape content from an external website using JSON API with the FeedMe plugin. Content is saved as entries with plain text and redactor-type Fields.
How can I structure this content so that I can display the most used words?
Example: I fetch content from a chess website. I want to find words or chess terminology (i.e. bishop, checkmate, pawn etc.) that are most often used, and list it like this:

bishop (302)
pawn (278)
checkmate (201)
stalemate (154)

...and so forth.
The number in parenthesis would be the number of times that word or term is counted in the scraped content.
Have anyone done anything similar? I would guess there are many use-cases for this, but couldn't find any relevant discussions on it.


texts: Update field setting value using getFieldByHandle

texts:
I need to update the limit setting for Images allowed to be empty, so as to allow for no limit. How do I go about updating the 'limit' setting?

$fieldsService = Craft::$app->getFields();
$field = $fieldsService->getFieldByHandle('productImages');
// Need to update 'limit' to equal '' (currently limited to '5')
// Then save the new setting
$fieldsService->saveField($field);

SOLUTION

I was able to accomplish this by using setAttributes and setting the second argument $safeOnly to false

$field->setAttributes([
    'limit' => ''
],false);


texts: Updating Craft 3 from RC1 to RC7 throws ErrorException

texts:
I have two Craft CMS 3 websites using Vagrant/Homestead & VirtualBox as the local server. Both were on RC1, and when trying to update to RC7 I get this error:

yii\base\ErrorException: unlink(/home/vagrant/sites/craft-site/storage/runtime/compiled_templates/1d/1d7666988f766c26d98233e048a41c263069493e993709f9ed7989e8bdfcce48.php): Permission denied in /home/vagrant/sites/craft-site/vendor/yiisoft/yii2/helpers/BaseFileHelper.php:347
Stack trace:
#0 /home/vagrant/sites/craft-site/vendor/yiisoft/yii2/helpers/BaseFileHelper.php(347): ::unlink()
#1 /home/vagrant/sites/craft-site/vendor/craftcms/cms/src/helpers/FileHelper.php(101): yii\helpers\BaseFileHelper::removeDirectory()
#2 /home/vagrant/sites/craft-site/vendor/craftcms/cms/src/helpers/FileHelper.php(409): craft\helpers\FileHelper::removeDirectory()
#3 /home/vagrant/sites/craft-site/vendor/craftcms/cms/src/web/Application.php(544): craft\helpers\FileHelper::clearDirectory()
#4 /home/vagrant/sites/craft-site/vendor/craftcms/cms/src/web/Application.php(165): craft\web\Application->_processUpdateLogic()
#5 /home/vagrant/sites/craft-site/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest()
#6 /home/vagrant/sites/craft-site/web/index.php(21): craft\web\Application->run()
#7 {main}

The same error happens whether I update through the admin or through composer. It happened to both of my sites as well.

I'm still learning development with Craft and PHP, but is this error telling me that I don't have permission rights to remove these files or is it something else?


texts: How to link to a page, but only if the page status is active

texts:
This is probably a really basic question, but I can't figure out how to check the status of a page before I link to it.

I have a link in my footer to 'Policy' page. But if the page status is inactive, I don't want that link to show. How can I perform this simple check?

Thanks,

Mark


texts: Website Stuck on Load after few requests

texts:
I'm facing a weird issue here.
I'm developing a CraftCMS based website and all seem to be working fine, until after a few requests (clicking around 4 ~ 5 requests) the website seem to keep loading and gets stuck, then browser returns an ERR_CONNECTION RESET error.
The weird thing is: Accessing any part of that domain on any browser within the network that I'm in gives seem to give an unresponsive (stuck loading forever). However accessing the domain from a different network seem to be working just fine. Restarting Apache server also does not seem to solve the issue.
I moved the site from one domain to another but the same problem persists.
Appreciate your help.

CraftCMS v3.4 (devMode)
PHP 7.4 (with all the recommended CraftCMS settings max_execution_time and memory)
MySQL database


texts: Commerce module - update purchasable ID on save line item

texts:
I'm trying to update a purchasableId against a line item (eg if the variant changes) via a custom module/controller (long story short native controller is not updating options stored against against the line item since upgrading to Craft 3).
If I look at the record in the database the purchasableId is updated but the value in the snapshot does not. On a second save it is.
The cart object references the version in the snapshot - how do I update the snapshot as part of my code so that the cart object shows the correct/intended value?
eg
$lineItem->purchasableId = $purchasableId;
Commerce::getInstance()->getLineItems()->saveLineItem($lineItem, false);


texts: Craft-Multi-Environment-Config redirects to dev url on admin login

texts:
I'm using the Barrel Stength Craft-Multi-Environment-Config to have a dev and live site configuration.

On my local dev install, under Settings > General I've changed to Site URL to {siteURL}. On logging into the admin, I'm redirected to the dev url.

I've also changed the Assets path and URL in the admin to

Path: {basePath}../public/my_assets_folder
URL: {siteUrl}my_assets_folder/

Images on the live frontend aren't displaying - they're served by HTTPS. Dev site is fine.

DB settings are working as expected. I just can't login to the live admin and the images aren't displaying on the dev frontend. What am I missing?


texts: Is it possible to create a field group that can be modified across entry types?

texts:
Sorry if this is asked/answered elsewhere. I tried to search for it with no success.

Suppose I have a common group of fields that I want to include in different entry types, and each entry will have unique data entered in the fields. A concrete example is:

SEO / Meta

meta title
meta description
meta keywords

Later on I want to remove the "meta keywords" field from every entry type that has this "field group". Is there a way — preferably with core Craft abilities — to set it up so I can update the field group in one place and not have to touch every entry type?

A matrix field with max 1 would get the job done but feels plain wrong for this.

I have the feeling there is another way I just don't know about yet.


texts: Can I use getCriteria to only return entries with a specified lightswitch field set to on?

texts:
I'm building a plugin that will check all existing entries in a section when a single entry is flagged as featured and turn off any existing featured entries. I'm using a lightswitch field to turn on and off entries. Is there a way to use the craft()->elements->getCriteria(ElementType::Entry); to return just the entries with the lightswitch field turned on?

Cheers


texts: I have a craft installation (that's up to date), that was installed with english as the system language. Now that Craft has quite a lot of system languages, is there a way to change to another language for the control panel?


texts: The requested URL was not found on this server

texts:
I've cloned an existing Craft site into MAMP Pro, set up my database in sequel pro and am able to access the site's homepage when I go to the URL I set up in MAMPS hosts. But whenever I click on a link, or try to access /admin, I get the following

  Not Found
  The requested URL /(page name) was not found on this server.

I'm sure it's something simple, probably something I'm missing when I set up the site locally, but I'm at a loss.