texts: How to use SSL for local development with Nitro?

texts: I've created a new Craft CMS project and installed Nitro to run everything in a VM. Now I'm wondering if it's possible to use SSL for the local domain? I didn't found anything in the documentation.


texts: Problems with Punctuation in Title using ElementCriteriaModel

texts:
I've noticed something odd and I can't find anything in the documentation.

I'm writing a plugin and when I use ElementCriteriaModel to find an existing entry like so:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'entryHandle';
$criteria->title = 'The Title & Stuff';
$existingEntry = $criteria->first();

The entry is not found, and I believe it's because of the punctuation. The entry is clearly in the craft_content table (with the exact title including punctuation). Is there some sort of processing I need to do before setting the title criterion?

Thanks!


texts: Compress Craft Control Panel CSS and JS per environment

texts:
Is there a way to compress the Craft CSS for a specific environment?
Currently there is a setting for Javascript, useCompressedJs, set to true by default.

useCompressedJs
Tells Craft whether to use compressed Javascript files whenever possible, to cut down on page load times.
https://craftcms.com/docs/config-settings#useCompressedJs

Is it possible to have a similar option in general.php for CSS?


texts: Is it possible to call a variable within a tag pair?

texts:
Having already defined foo, I tried this:

{% for block in availability.{{ foo }} %}

This gives error:

Expected name or number

Can anyone please tell me the right way to go about this.


texts: How to load entries via ajax when a filter is clicked?

texts:
I have a page that lists all entries from the section 'work'. I would like the user to be able to filter these entries by category but via ajax so I don't have to go to a new page.

{% set entries = craft.entries.section('work').limit(null).search('categories:hotel') %}

This works but each category has to have its own page. Is it possibly to load the filtered entries by ajax? Something using {% if craft.request.isAjax %}?
Here is the relevant html:

Categories

All

Hotel

Bar

Club

Restaurant

Retail

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

            {% for entry in entries %}

                        {% for asset in entry.mainPhoto %}

                        {% endfor %}

{{ entry.title }}

{{ entry.address }}

            {% endfor %}


texts: {basePath} creates a folder named {basePath} issue

texts:
just built a blog with craft, and I got some issues with assets pathing.
In the general.php I put

return array(
    'environmentVariables' => array(
            'basePath' => '/images',
            'baseUrl'  => 'https://site.com',
        )
);

But when I put {basePath} to assets path, the system creates a {basePath} named folder in root and looks for the image folder there. Also the {baseUrl} is looking like this in the code:

https://site.com/{baseUrl}/images/image.jpg

Am I doing something wrong?


texts: I have a problem with the admin panel being very slow when saving an entry. It takes about 30 seconds to save an entry. I use a matrix for the different part of the entry (imgs, textfields, titles and so on). Does anyone else have this problem, and have someone found a solution for this? :)


texts: Dynamic routing via plugin with special characters

texts:
After learning how to use dynamic routing in MyPluginPlugin.php, I quickly ran into the issue of if the URL has special characters from url_encode:

public function registerSiteRoutes()
{
return array(
    'myroute/(?P<myVariable>[-\w]+)' => array('action' => 'myPlugin/myAction')
);
}

And then I process some variables before rendering the template in myPlugin/myAction:

 public function actionLoadTemplate( array $variables = array() )
 {
   /*
   process & build $variables
   */

    $this->renderTemplate('layouts/forums/_entry', $variables);

 }

This works great if the route looks like myroute/check-this-out, however if the route had a special character in it, say it was "check-this-out!", it understandably leads to a 404. But with using url_encode on the URL so it looks like myroute/check-this-out%21, it still leads to a 404.

When testing manually in the CP route section, if I create myroute/* with the token, I don't get a 404 with those special characters after using url_encode.

Is there a way to modify (?P<myVariable>[-\w]+) so that it works with url-safe special characters just like the CP version does?


texts: How can I get all entries that are equal to, but not after a date?

texts:
Some of the products on my page are time sensitive (events). Currently I am getting them all like this:

{% set events = craft.commerce.products.type('event').order('eventStartDate desc') %}

I can't use the expiryDate as the end date for my event, as I am keeping an archive that I want users to be able to click though. But, I don't want to include these "expired" events in my "upcoming events" list.

I am reading through this SO thread which I think is doing the same thing I am. It's painfully obvious that I don't know what I am doing though.

{% set today = now %}
{% set events = craft.commerce.products.type('event').eventEndDate('>= today') %}

: Call to a member function getTimestamp() on boolean

eventEndDate is a dateTime field type.

I am trying (and failing) to get all events that have an end date that is equal to, or before today. Once the event is over eventEndDate is after today, I do not want to show it in my list.

Thank you for any suggestions!


texts: How can I pull every entry (large number) in a section?

texts:
I have an extended profile that users can purchase. When purchased, an entry is created, and tied back to the user.

The user can then log in and access the entry with the extended profile fields.

I would like to have a page that pulls every extended profile entry. This could be in the hundreds. I know Craft will limit the number it returns by default. I also know that I can pass null into the limit. limit(null)

That seems pretty risky and expensive to run. Is there a better solution? I only need the page title of each entry, so I don't need the entire entry model.

Is this a place to use elementAPI and make ajax call(s) to get all of the entries so I'm only returning the page titles?

Thank you for any suggestions!


texts: Uploading to a date subfolder within a Matrix

texts:
I'm working on a site that will have lots of content. Our customer now asked to have their images upload into a different subfolder, by date.
I can get it done in a "normal" Assets field, but in a Matrix I get an error: Could not resolve the subpath “{postDate|date("d-m-Y")}”, with postDate being the name of the generated folder.
I did the exact same thing in a "regular" Assets field and that does its job as it should.

Can anyone tell me what I'm doing wrong?

Thanks!


texts: asset sourcetype getLocalCopy() not working?

texts:
I need to use getLocalCopy from LocalAssetSourceType

// Get asset source
$source = $asset->getSource();
// Get asset source type
$sourceType = $source->getSourceType();
// Get asset file
$file = $sourceType->getLocalCopy($asset);

but that function returns the error Tried to copy 2015/ami-l.jpg to /twenrytn/unidram/craft/storage/runtime/temp/assets56050ef792f4e1.75513363.jpg, but the source file does not exist.

The source file definitely exists, so i checked the function itself

public function getLocalCopy(AssetFileModel $file)
{
    $location = AssetsHelper::getTempFilePath($file->getExtension());
      MyPlugin::log($this->_getFileSystemPath($file) . ' > ' . $location);
    IOHelper::copyFile($this->_getFileSystemPath($file), $location);
    clearstatcache();
    return $location;
}

and the log returned 2015/ariel-doron-xl.jpg > /twenrytn/unidram/craft/storage/runtime/temp/assets5605112c1aef83.12097209.jpg

I think $this->_getFileSystemPath($file) should return an absolute path. Why didnt it?


texts:
Is it possible to do the following?

{% if entry.type == 'overview' %}

    {{ entry.title }}

{% elseif entry.type == ['availability', 'specifications', 'sitemap', 'location'] %}

    {{ entry.title }}

{% else %}

    {{ entry.title }}

{% endif %}

At the minute it is not returning anything inside the elseif, can anyone spot anything wrong with the logic or is there an alternative method?


texts: Can you increase the max size of Rich Text fields?

texts:
I'm unable to save an entry, and I'm getting an error saying that a Rich Text field is too long.

If I disable the entry, it saves fine, but when it's enabled, it doesn't save.

Can I increase the max size of a Rich Text field?


texts: Restricting Payment Gatways by User Group using Commerce Pro?

texts:
Is it possible to restrict payment gateways on a per user group basis?
e.g. Say you want a user group to assign users into from a certain country that cannot use PayPal, so you can offer them a different gateway instead?
Thanks


texts: Commerce discount promotions as a fieldtype?

texts: I'd like to create an entry in Craft that talks about a new discount, and then choose that discount via a field (so a bit like you can choose an entry or a product). That way, should the parameters of the discount change, I'm not having to manually update the information in the entry to match any changes to the discount details. Is there a plugin for this?


texts: what does {% set order = 'pin desc, postDate desc' %} do?

texts: I am new to using twig and I do not understand how this line of code works. If you could explain that would be wonderful! thanks:)


texts:
I created a Matrix field with 1 block type called "Logo" and 2 fields inside that: 1) a related entries field and 2) an image asset.  I then created a global that has this Matrix field in it that allows you to create up to 4 logo blocks in the Matrix.

When I try to create any number of logo blocks, whether I add an asset, choose an entry, or both, I get this CDb error when saving the global.

I get that the error is saying it can't locate a column of data it needs, but I don't know what the cause could be. I've tried deleting my Matrix field and global and starting over, but it's the same error each time.

I've checked the asset group for the logo images and everything seems fine: everything's named properly, no missing images, did an asset index update. No dice.

Here's a screenshot of the full error. I'm working on my local machine and the front end is unaffected.


texts: Integrate Google reCAPTCHA into Contact Form plugin

texts:
So I just recently plugged in pixelandtonic/ContactForm plugin into my website and I realized I got about 3 spam emails straight into my inbox on the first day it was up.

Is there a way to integrate the simple "one click" google Recaptcha into this form? Or is there any other/better solution than the Honeypot?

Thanks for the help!

---- EDIT -----
Ever since I've installed the Spam Guard Plugin, I haven't received anymore spam! This is a must with Pixel's Contact form plugin.


texts: for loop: get the title of the first element of an entries field

texts:
I want to get the title of the first element from a entries field in a for loop. I think its easier to understand with a code example:

{% set programs = craft.entries.section('program_point').block.first().title('first-block') %}
{% for program in programs %}
...
{% endfor %}

block is an entries field. And the loop should only consider entries where the title of the first element in blockis first-block.

When I tried this, I always got an error:

  Impossible to invoke a method ("title") on a null variable

But when I did this:

{% set programs = craft.entries.section('program_point') %}
{% for program in programs %}
        {% if program.block.first().title == 'first-block' %}
             ...
        {% endif %}
{% endfor %}

all worked fine.
So how can I check the title of the first element in the for loop?


texts:
I have the following problem:
My Craft site was setted up normally. I made entries with matrix structure and build one after another.

Then after i built a lot of entries i wanted to set up a second locale for the site.

So i used the craft manual on your site and i told the fields that i want to have in the second language as well that its translateable.

But now if i want to translate my matrix fields in the entry, THE HOLE matrix structure is gone :O but of course i do not want to create them new.

If i do ne entries now after setting up the second language, matrix fields are translateable, but not my entries that were exist before... How can i now fix it?
I read on different blogs that is a bug..

Please help me :)

Best Regards


texts: Updating a matrix row in an existing entry using a frontend form

texts:
I am trying to update a specific row in a matrix field using a frontend form, I created them using another form with each row following the [new1], [new2] etc. naming format, but I can't seem to get it working using the code below

{% for block in entry.fieldOrderItemsMatrix.all() %}
    <form method="post" accept-charset="UTF-8">
      {{ csrfInput() }}
      {{ actionInput('entries/save-entry') }}
      {{ hiddenInput('sectionId', craft.app.sections.getSectionByHandle('orders').id) }}
      {{ hiddenInput('entryId', entry.id) }}
      <input type="checkbox" name="fields[fieldOrderItemsMatrix][new{{ loop.index }}][fields][fieldOrderDelivered]" {{ delivered ? 'checked' }}>
      Delivered
      <button>Save</button>
    </form>
{% endfor %}


texts: Search query for entries doesn't seem to work correctly

texts:
In my project I have a tickets which are edited in multiple steps where each step has it's own front end for. Now, of course. to continue editing an ticket I am required to fetch that exact ticket.

To accomplish this I have a search form include which will be displayed before the form is showed. When the search form returns an entry the form is shown, when this fails the search form include will be shown again.

Lastly: The search does work when I search for an entry where the title does not contain a spacebar, So:

When the title is 'Test' I can find it, when the title is test ticket I can't find it using the search form, even though they do both exist!

My code:

General.php settings:

'defaultSearchTermOptions' => [
    'attribute' => 'title',
    'exact' => true,
    'subRight' => false,
    'subLeft' => false,
],

My search form:

<form novalidate>
    <input id="search" type="search" name="ticket_number"/>
    <button type="submit">Search</button>
</form>

My URL after submitting the form:

domain.com?ticket_number=ticket+number+test+search

My page:

{% set searchQuery = craft.app.request.getParam('ticket_number') %}
{% set ticket = craft.entries().search(searchQuery).section('ticketLog').one() %}

{% if ticket|length %}

Start Picking - {{ ticket.title }}

Fill in this form to start picking.

                    {% include '/_components/includes/form' with {
                        'redirect' : siteUrl,
                        'section_handle' : 'ticketLog',
                        'fields' : [{
                            type : 'datetime',
                            handle : 'pickingStartTime',
                        },{
                            type : 'user',
                            title : 'Picker',
                            query : 'teamleader',
                            required : 'required',
                            size : '12',
                        }, {
                            type : 'submit',
                            text : 'Save Ticket',
                        }]
                    } %}

{% else %}

Your search for “{{ searchQuery }}” didn’t return any Tickets, please try again below.

    {% include 'ticket_log/forms/search_form.twig' %}
{% endif %}

Hope someone sees what I am doing wrong there!


texts:
I'm having difficulty returning a category from inside a matrix block.

So I'm returning a student based on a studentNumber variable

{% set studentParams = {
    section : 'students',
    'studentNumber': studentNumber,
} %}

{% set student = craft.entries(studentParams).first() %}

I'm then returning the fee associated with this student

{% set fee = student.studentFee[0] ?? null %}

Inside this fee, I have a matrix block. Within that matrix block I have a field that is set using categories.

{#
    Looping through fee types to get the installment amounts for the course and various fee types.
    Currently not returning the FeeType title - Grant holder etc
#}

{% for block in fee.fee %}

    {% if block.firstInstallment is defined and block.firstInstallment is not null %}

First Installment : {{ block.firstInstallment }}

    {% endif %}

    {% if block.secondInstallment is defined and block.secondInstallment is not null %}

Second Installment : {{ block.secondInstallment }}

    {% endif %}

    {% if block.full is defined and block.full is not null %}

Full :  {{ block.full }}

    {% endif %}

{% endfor %}

I am able to return everything inside the Matrix block aside from the category field.

Any idea why this might be?


texts: Craft 2 CP session expires unexpectedly, requires repeated login

texts:
Environment
Craft: 2.6.3013 (Personal)
MAMP Pro: 4.4.1
PHP: 7.0.12 (CGI Mode)

Behavior
After logging into the CP, and following a relatively short period of time, the session expires unexpectedly and Craft requests a login. Attempting to log in fails and immediately returns to the login modal; however, simply refreshing the page re-establishes the session, but again for only the limited period of time.

Looking at /craft/storage/runtime/sessions I see that Craft is creating a number of sessions, some of them being zero bytes.

Attempted Solutions
I've tried the following, based on other users' past experiences and solutions:

In general.php: 'requireMatchingUserAgentForSession' => false
In general.php: 'overridePhpSessionLocation' => true
In php.ini: session.auto_start = 0
Permissions set to 777 for /craft/storage/runtime
In MAMP, enable/disable "Xdebug (Debugger)" PHP extension
Lastly, tested in both PHP 7.0.12 and 5.6.32 without CGI mode

Next Steps?
Does it appear that I've missed anything in my previous steps? I've been using Craft 2 for a couple of years in a variety of environments--MAMP 3 / Vagrant / Docker--and haven't experienced this before. The issue isn't a showstopper, but certainly an annoyance, and I would be grateful for thoughts on what to try next.


texts: relatedTo doesn't seem to work when using multiple sections in a craft.entries call

texts:
I can do craft.entries.section('mySection').relatedTo(item.id) and it will return the result, so i assumed i could do craft.entries.section(['mySection','mySection2','mySection3']).relatedTo(item.id) but, the latter seems to return no results.

Any input would be greatly appreciated!


texts: Display field from one section in another section

texts:
I have two sections:

Games
Publishers

Games has a field called "GamesPublisher" that is a relation (field type "Entries"), the Source is "Publishers".

In my template to show an entry from games, I want to display the default field "title" of a publisher that I assigned to the games entry in the admin CP.

{% extends "_layout" %}
{% set title = "Games" %}
{% set entries = craft.entries.section('games').limit(10).order('title') %}
{% block content %}

    {% for entry in entries %}

            {% for category in entry.GamesGenre %}{{ category.title }}{% endfor %}: {{ entry.title }} (***Put Title of Publisher Here***, {{ entry.GamesReleaseYear.format('Y') }})

    {% endfor %}

{% endblock %}

The place I want to insert the publisher's title is shown as:
Put Title of Publisher Here

Thanks all. I just started using Craft about 3 hours ago for the first time!


texts: error when trying to loop through grouped entries according to dropdown field

texts:
I was trying to follow this example from stack overflow to loop through a list of entries and output them by a custom dropdown field

{% set allEntries = craft.entries.section('resource').find() %}
{% set allEntriesByCat = allEntries|group('entry.resourceType') %}
{% for cat, entriesInCat in allEntriesByCat %}

{{cat}}

    {% for entry in entriesInCat %}

{{entry.title}}

{{entry.resourceContent}}

    {% endfor %}
{% endfor %}

But if I do that, I get the error: Internal Server Error
Craft\EntryModel and its behaviors do not have a method or closure named "entry".


texts: Trouble with submitting Contact Form plugin contact via AJAX

texts:
I’m having trouble getting Contact Form to work when posting through AJAX.

Form:

{% macro errorList(errors) %}
    {% if errors %}

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

{% from _self import errorList %}

    <form method="post" action="" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="contactForm/sendMessage">
    <input type="hidden" name="redirect" value="contact/thanks">

Your Email

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

Message

                <textarea rows="10" cols="40" id="message" name="message">{% if message is defined %}{{ message.message }}{% endif %}</textarea>
                {{ message is defined and message ? errorList(message.getErrors('message')) }}

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

THANKS

    </form>

jQuery:

$('#my-form').submit(function(ev) {
    // Prevent the form from actually submitting
    ev.preventDefault();

    // Get the post data
    var data = $(this).serialize();

    // Send it to the server
    $.post('/', data, function(response) {
        if (response.success) {
            $('#thanks').fadeIn();
        } else {
            // response.error will be an object containing any validation errors that occurred, indexed by field name
            // e.g. response.error.fromName => ['From Name is required']
            alert('An error occurred. Please try again.');
        }
    });
});

In this case the response is not a success so the alert is triggered.

Out of interest I console logged the response in the else block and it’s all the HTML on the page. And then I thought, why don’t I console log the data variable right after it’s declared and - same thing - it’s all the HTML on the page.

Anybody got any tips?


texts: What is the best practice in Craft 3 to sync schema between environments?

texts:
How can sync the schema (fields + categories + tags + sections) from development to staging and live? Or should I do it manually?
Is there any support to make migration script instead of do it from the webpage


texts: How to set a URL for the top level of a Structure section?

texts:
I have entries in a structure section. I'd like the users to view the list of entries without the entries themselves being assigned URLs.

How can I set a URL for the top level of a Structure section without enabling "Entry URL Format"?


texts: How do I display the Image of an Author in a post?

texts:
This might be a stupid question... but I can't seem to figure it out.

I'd like to show the photo of an author beside their entry. I thought the proper variable was...

{{user.photoUrl}}

...until I logged out and my photo disappeared.


texts:
I'm working on a plugin to do subscription billing with paypal. I have the following controller

class PaypalSubscription_SubscriptionController extends BaseController {

    public function actionSubscriptions() {
        // This renders a form that collects some info on subscription options
    }

    public function actionSubscribe() {
        $this->requirePostRequest();
        // This takes data and starts a paypal transaction
    }
}

I can get to the form by going to /actions/paypalSubscription/subscription/subscriptions

I've tried hard coding the url /actions/paypalSubscription/subscription/subscribe as well as using actionUrl('/paypalSubscription/subscription/subscribe'). The actionUrl call prepends index.php/actions to the string which is just incorrect, and either way both approaches 404. What am I missing here?

I know that i'm logged in and that works correctly since I can reach the original form and anonymous access shouldn't be turned on, so I don't believe that's the issue.


texts: How do I tell Craft not to automatically crop user profile images?

texts: When uploading user profile images, Craft forces you to crop it to a square. Is there a way to keep the images untouched instead?


texts: Twig 'starts with' not evaluating variables properly

texts:
This evaluates to false

{% if block.imageWidth starts with block.imageWidth %}

But this evaluates to true

{% if '{{ block.imageWidth }}' starts with '{{ block.imageWidth }}' %}

Some sort of issue with Craft's Twig integration?


texts:
I've got a plugin which is defaulting to English during AJAX calls, but I need it to stick to whatever the current language is. I can send the current locale through via AJAX data, but I'm not sure how to change the locale in PHP.

It's possible to get the current locale like this...

craft()->getLanguage()

Is there a way to set the current locale in PHP?


texts:
I'm not a plugin developer, nor is my knowledge of PHP sufficient to handle this issue.

I need a simple method or plugin, to be able to generate this PHP code in a template.

<?
$params="";

foreach($_POST as $name=>$value)
{
    if ($name!="controllerPage")
    {
        $params=$params.$name."=".$value."&";
    }
}
?>

In the same template I need this code to retrieve the above

<? echo $params; ?>

Who can show me the way?

This is the POST data that is attached to the URL

$_POST=array (
'view' => 'SearchResult',
'controllerPage' => 'https://navigantes.eu/yachts-search',
'customCssPath' => 'https://navigantes.eu/css/booking-manager-small.css',
'setlang' => 'en',
'target' => '_blank',
'companyid' => '1234',
'filter_country' => 'HR',
'filter_region' => '',
'filter_base' => '',
'filter_year' => '2016',
'filter_month' => '11',
'filter_date' => '10',
'filter_duration' => '7',
'filter_flexibility' => 'on_day',
)

Which needs to be translated to this:

view=SearchResult&amp;customCssPath=https://navigantes.eu/css/booking-manager-small.css&amp;setlang=en&amp;target=_blank&amp;companyid=1234&amp;filter_country=HR&amp;filter_region=&amp;filter_base=&amp;filter_year=2016&amp;filter_month=11&amp;filter_date=10&amp;filter_duration=7&amp;filter_flexibility=on_day&

Solved the issue by using {{ craft.request.getPost('') }} method:

            <iframe name="" width="100%" height="800" frameborder="0" scrolling="auto"
            src="https://www.booking-manager.com/wbm2/page.html?
                view={{ craft.request.getPost( 'view' ) }}&
                customCssPath={{ craft.config.environmentVariables.rootUrl }}/css/booking-manager-small.css&
                setlang={{ craft.request.getPost( 'setlang' ) }}&
                companyid={{ craft.request.getPost( 'companyid' ) }}&
                filter_country={{ craft.request.getPost( 'filter_country' ) }}&
                filter_region={{ craft.request.getPost( 'filter_region' ) }}&
                filter_base={{ craft.request.getPost( 'filter_base' ) }}&
                filter_year={{ craft.request.getPost( 'filter_year' ) }}&
                filter_month={{ craft.request.getPost( 'filter_month' ) }}&
                filter_date={{ craft.request.getPost( 'filter_date' ) }}&
                filter_duration={{ craft.request.getPost( 'filter_duration' ) }}&
                filter_flexibility={{ craft.request.getPost( 'filter_flexibility' ) }}&
            ">
        </iframe>

And finally Brad's suggested method worked by changing craft.request.getSegments() into craft.request.getPost():

{% set segments = craft.request.getPost() %}
{% set stringParams = '' %}

{% for name, segment in segments %}
{% if name != 'controllerPage' %}
    {% set stringParams = stringParams ~ name ~ '=' ~ segment ~ '&' %}
{% endif %}
{% endfor %}

<iframe name="" width="100%" height="800" frameborder="0" scrolling="auto" src="https://www.booking-manager.com/wbm2/page.html?{{ stringParams }}">


texts:
My question is more conceptual than technical;

I have a website who have two big topics, on is purely editorial (pages, articles, faq, ...), the other is basically a comparator based on user input with account, sending contracts by mail and by post, reminders, signatures, etc etc. The business logic is quite complex.

I started doing everything in laravel + nova admin but I quickly felt frustrated for the cms part, as I'm used to Craft, and everything where Craft is good at is a pain and takes time to recreate in nova (the tool is an admin that has some cms capabilities, but is really far form Craft).
So I ended up with two applications, Craft for content editing, and Laravel + nova for the custom part.

Is it a good idea ? Or should I put custom parts in custom craft plugins ? Can I do eveything, I guess like yii apps ?

In my current situation, I fear that I will end up with more complexity, making the two applications communicate seamlessly will take time, maybe mix authentifications,...
In the other hand, I have the impression to really own the codebase and database with a barebone laravel app, than putting everything into Craft, as good as he is. But it's maybe a noob assumption.

What in your experience is the best way to go ?

Thanks for your inputs !


texts: Is there a way to serve my CSS files from the templates folder? I am wanting to be able to use TWIG tags, etc to build some of this. And even if the TWIG tag idea does not work out, I would prefer this sort of an organizational structure.


texts:
I am using the Enupal Stripe Payments plugin to pass line items to Stripe. The line items get passed in an array. I want to use a javascript cart to hold the items in local storage, reformat that and then send them to the twig array that will eventually be sent to Stripe.
I have reformatted the JSON from local storage using javascript and can see the output in my console. How can I include that javascript inside the twig array? I have read some vague feedback about using AJAX for this but I do not fully understand how to accomplish that or if it is the correct solution for this use case.
Stripe TWIG array example:
{% set options = {
    lineItems : MY JAVASCRIPT GOES HERE
} %}


texts: How to attach an order PDF in an order confirmation email?

texts: I am currently adding a link to download the order PDF in the confirmation email with {{ order.getPdfUrl() }} but also want this to be an attachment.


texts: Preserve Structure while searching for entries?

texts:
I have Structure type section and each of the entry contain at least 10 level 1 entries.

Is there a way to preserve the structure of the entries while filtering/searching entries? What I mean by this is that, I want to search the parent entries only (Ignoring the level 1 child entries).


texts: Macro for entry loop causing 'null' variable template error

texts:
I am new to the concept of Twig templates and I can’t get it right from the documentation … What I am trying to achieve is to have a reusable Blogroll snippet that outputs entries in different contexts: ALL entries on the homepage and then according to the entry’s category in other areas of the site.

I created a file blogroll.html in templates/macros containing my blogroll code which works fine if used directly in a template (simplified the HTML here):

{% macro blogroll(entry) %}

{{ entry.title }}

{% endmacro %}

In my index.html for the homepage I try inserting it with this code:

{% for entry in craft.entries.section('blog').limit(15).find() %}
{% for entry in entries %}
  {% import "macros/blogroll" as blogroll %}
  {{ blogroll.blogroll }}
{% endfor %}

In my category related templates I filter for the category first and try to insert it this way:

{% set entries = craft.entries.relatedTo(category) %}
{% for entry in entries %}
  {% import "macros/blogroll" as blogroll %}
{{ blogroll.blogroll }}
{% endfor %}

In both cases I get a Impossible to access an attribute ("url") on a null variable. error though.

Any hints where I am not getting the concept right or screw something up while passing the variable?


texts: Setting system email address and sender name in multi config

texts:
Is there a way to set the system email address and sender name from within the config file?

This would be useful when using multi environment configurations. For instance, during development or on my staging server I wish emails to be sent to me (the developer). While for production they would go to the site owner.

I can see the values in serialised data within the database but was hoping I could override them within the config file. I've tried the  keys "emailAddress" and "senderName" to no avail.


texts: Get Entries That Match ALL of the tags specified

texts:
I have a search page where a user can check about 20 different checkboxes, where these checkboxes all relate to tags I have set up inside of Craft. I would like to perform the following search query:

For all of the tags selected, I would like to return a list of entries that have ALL of these tags. For example:

The user clicks the checkboxes, "SCC" and "HVT"

A query should be performed that returns only the entries that have the tags, "SCC" AND "HVT". I have been reading Craft docs for the past 3 hours, and am not grasping this concept at all.

I know this is hardcoded, but I was just experimenting, and it does not work at all:

{% set entries = craft.entries.section('journalArticles').relatedTo('and', { targetElement: 'SCC' }, { targetElement: 'HPV' }) %}

I do not want to use a plugin if I don't have to.


texts: Error updating programmatically a plugin's setting

texts:
I want to update programatically a plugin's setting:

public function init()
{
     craft()->on('commerce_orders.onBeforeOrderComplete', function($event){
        // Set InvoiceNumber
        $newInvoiceNumber = $this->getSettings()->currentInvoiceNumber + 1;
        $myPlugin = craft()->plugins->getPlugin( 'Ultraschall' );
        craft()->plugins->savePluginSettings( $myPlugin,
                                              array('currentInvoiceNumber', $newInvoiceNumber ));
    });
}

But I get this error:

PHP warning
array_key_exists() expects parameter 2 to be array, null given
/mnt/web209/c2/98/5363898/htdocs/dev.ultraschall-leinwand.de/craft/app/models/BaseModel.php(418)

417  // Is this the first time this extra attribute has been set?
418  else if (!array_key_exists($name, $this->_extraAttributeNames))
419  {
420     $this->_extraAttributeNames[] = $name;
421  }
422
423  $this->_attributes[$name] = $value;
424  return true;

I have added defineSettings() and getSettingsHtml() to the Plugin and can change values via CP without problems.

Why do I get this error?


texts: Make entry in nav not clickable and reroute

texts:
I have an entry that acts as a parent to several children pages. Trying to make so that particular parent isn't clickable AND reroutes to homepage if address url is accessed.

Not sure if I can work something into existing nav code or if this needs to be done somewhere else, but here's the code, nonetheless. Thanks in advance.

    {% set pages = craft.entries.section('page') %}
    {% nav page in pages %}

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

                    {% children %}

            {% endifchildren %}

    {% endnav %}


texts: How to get corresponding Post in Craft request?

texts:
I'm working on a Craft CMS plugin. I'm making a form that consists of multiple themes and questions. The structure is supposed to be as follows:

• Form
  • Theme
    • Question
    • Question
    • Question
  • Theme
    • Question
    • Question

Questions should be “attached” to the form with the formId, but also to their respective themeId. This kinda works when there’s just one theme, but as soon as I save a question in a second or third theme, all questions get the last theme id.

I’ve added a hidden field to each question which looks like this:

<input type="hidden" class="questionThemeId" name="questionThemeId" value="{{ themeId }}">

Then in my Service I do the following request and add the themeId to the question.

$themeIdForQuestion = craft()->request->getPost("questionThemeId");
$question->themeId = $themeIdForQuestion;

This does add the themeId to the question, but once there is a question in the second theme, all questions get the themeId of the last theme. That makes sense, because getPost always gets the last post (I think). How would I get post of the questionThemeId depending on the question?

I'm open to other solutions too, because this does feel slightly hacky.

Thanks!


texts: How to output the matrix block type name in Craft? Possible feature request

texts:
Is it possible to output the block type name in Craft for each matrix block in your field?

Currently Craft just lists the name of each field within the block, but we are using generic field names (Width, depth etc), so in those instances there is no clear context for which block type is being used.

See the attached screenshot to see what I mean. I have just shown the 'Footprint' block type, but with the list of generic fields there is no way of clearly seeing this is actually 'Footprint', which can make things difficult for our client when they are managing content.

The second screenshot shows what I am trying to achieve, so it simply adds "Type: Footprint" to the start of the field list. Thanks!


texts: Pagination base URL - any way to have pagination links go to URLs other than current one?

texts:
TL;DR: Looking for something like paginate_base parameter in EE, but for Craft.

My site's homepage has content in tabs for different sections (news, products, etc.) and in each tab I would like to have pagination links that would go to 2nd, 3rd, etc page in each section.

So in News tab I display news entries and would like to link to /news/p2, /news/p3 etc, on Products tab I would have links to /products/p2, /products/p3 etc. All that on same page, with URL different from /news or /products

Is there any way to achieve that in Craft?


texts:
How does one get the sale price of a product in Craft Commerce on a product page? I'm new to Craft and Twig and the sale section of the Commerce docs is.. well, not really there (page under construction). I have a product that has a sale set on it. I pull the single product without problem:

{% set product = craft.commerce.products({
    relatedTo: category,
    slug: craft.request.getSegment(3),
    status: 'live',
}).first() %}

Product Title - {{ product.title }}
Product Price - {{ product.defaultPrice|commerceCurrency(cart.currency) }}

But a {{ dump(product) }} doesn't show any discount or sale values at all. I know the sale exists and is up; this returns my sale name:

{% for sale in craft.commerce.sales %}
    {{ sale.name }}
{% endfor %}

And I know my product is a part of that sale, it shows it as a related sale on the product entry page. The sale is wide open (no expiry or start, just one product picked (the one that populates the page I'm testing)). All attempts at sales price result in a templating error: {{ product.price }},{{ product.salePrice }},etc.

The only thing I can think is a nested loop and then conditionals... something like (pseudo code):

<span class="price">
{% for sale in sales %}
    {% for sale_product in sale.products %}
        {% if sale_product.sku == product.sku %}
            ... do some weird math?
            Check if % off or $ off and math it up with
            {{ product.defaultPrice }}?
        {% endif %}
    {% endfor %}
{% endfor %}

And that is clearly not how this is supposed to be done. Thanks!

Edit

And for that matter, how do I check if it is on sale at all, regardless of the sale value? The client design involves slightly different coloring/styles for a sale price versus a default price.


texts: EntryModel::populateModels throws a 500 error

texts:
I am retrieving a data set with about 5000 records and I am using the EntryModel::populateModels($results) to populate the model, this is causing a 500 error. When I limit the number of records returned to 100, it is working fine but when i set the limit to null it throws the error.

There isnt any error logged in the logs, and nor can it be a timeout because it only takes about 5 secs to return the error.


texts: Difference between {% includeCssFile %} or including it with

texts:
I go a simple question. I wanted to start with building my craft template from html and changed all css  and  tags to to equivalent {% includeCssFile %} or {% includeJsFile %}.

The page was working but my live preview was broken. It could not load the CSS, JS and other files. So I searched this forum and found out i should use {{ siteUrl }} on my links. I changed all back to   and now live preview is working.

So I'm wondering: why or when should we use this kind of include file tags?


texts: Is it possible to hide certain entries in the Content SEO section of SEO Matic?

texts: I would like to "hide" Certain Pages or entries from the Content SEO Section as they are never seen by the end user and are not used in the XML sitemap. Is there a way to do this ?


texts: Craft Commerce: ordering products like a structure

texts:
Is it possible to change the order of products in Craft Commerce (3) by drag & drop? Just like it is done with the entries of a structure?
If not, how am I supposed to change the order of products?
Of course I can create a number field and type in a number and then sort after this number. But that's super inconvinient.
Another way would be to create single-pages for each product category and then have an entries-field. Than, at least, I can use drag and drop. But still, this would just be a work-around.


texts: Show only and merge the entries from multiple categories related to that entry

texts:
I want to show the entries which have same category of that entry. The entry might have multiple categories, so I want to merge the result. If there is a result, then only the whole structure will be shown. The title 'Recommended Product' should only show one time. Currently, the issue is if there are three categories, the whole structure will show three times.

{% set subcategories = craft.categories.group('prodCat').descendantOf(prodCat).level(2).relatedto(entry) %}
    {% if subcategories | length %}
        {% for subcategory in subcategories %}
            {% set relatedentry = craft.entries.section('products').relatedTo(subcategories).id('not '~entry.id).all() %}
            {% set relatedentry_count = relatedentry|length %}
            {% if relatedentry_count > 0 %}

Recommended Product

                    {% for entry in relatedentry %}

{{entry.title}}

                    {% endfor %}

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

Update based on the answer:

I manage to solve the issue after making some tweak of the answer given, just merge the subcategory.

{% set subcategory = craft.categories.group('prodCat').level(2).relatedto(entry) %}
{% set subcategories = subcategory|merge(subcategory) %}
    {% if subcategories | length %}
        {% set relatedentry = craft.entries.section('products').relatedTo(subcategories).id('not '~entry.id).all() %}
        {% set relatedentry_count = relatedentry|length %}
        {% if relatedentry_count > 0 %}

Recommended Product

                    {% for entry in relatedentry %}

{{entry.title}}

                    {% endfor %}

        {% endif %}
    {% endif %}


texts:
I'd like to add an ordinal suffix to the loop.index variable within a for loop.

For example:

1st
2nd
3rd


texts: This is a super high level question but it would be good to get a couple of summary answers.  What are the main pros and cons of Craft versus WordPress?


texts: Craft CMS Backing React FE using the element API

texts:
I am hoping to create a React Site that uses Craft CMS and the Element API as a backend.  However, I know I will need to authenticate users and be posting data back into Craft which I believe the Element API doesn't support.

I was hoping someone might be able to talk me through if authenticating users is possible using a plugin and craft session service and if so what would be the general strategy given that this would be (at least in development) across two origins.

stage.project.com // craft cms w/ element api
localhost:3000 // react development

I haven't found any plugins out there that do just this, but it seems like it would be possible with a craft plugin.  Just wanted to confirm that this is possible and get a sense of how before investing the time.


texts:
We're about to launch a Craft Commerce 2 site. I'm wondering how involved the Commerce 3 upgrade is as far as template changes? And if we decide to upgrade now what's the best practice for making those changes? Start with the new templates and add our customizations?

Will the Stripe for Craft Commerce work with Commerce 3? I notice it just lists Commerce 2 right now.


texts: Grouping entries by days in matrix field

texts:
So this is proving a lot harder than I thought.

I have a 'tours' section containing tours, which all have several departure dates. Those dates are in a matrix field, entry.data. So there's only one type for that matrix field, and one date picker, so that several dates can be added per entry.

I'm trying to list entries sorted by the day they depart, so it should look like this:

07-oct-2015
tour x
tour y

11-oct-2015
tour x
tour z

13-oct-2015
tour x
tour y
tour z

Since there isn't a tour departing every day, or on a set schedule, I can't just pull out entries that match a given day..

Any help would be awesome! I saw a similar post that was resolved with the low blocks plugin, but I'm hoping this can be solved natively with grouping and sorting.. :)

Thx!


texts:
Unsure how to go about doing this. I'm looking to open a related entry in a modal on the same page. In an area, I have a list of houses. On click, I would like the user to open a modal and load the corresponding entry inside it.
Is there an easier way to do this other than AJAX loading it in?


texts: active state macro how to check if segment 2 is empty

texts:
I'm using a macro to check segment 1 to set an active state on my navigation and all is working correctly. However I would like to change it so that if segment_2 is not empty it doesn't display the active state, with the exception of being pagination in segment-2

so domain.com/photography and domain.com/photography/p2 would get active but domain.com/photography/slug would not be active

my current code is:

macro:

{% macro is_active(segment) %}{% if craft.request.firstSegment == segment %}active{% endif %}{% endmacro %}

and nav:

Home

All Photography

Archives


texts: Craft 3 multi-lingual multi-sites setup with shared assets

texts:
I have 2 almost identical websites. Both have almost the same layout but different colors (so different CSS file). They share most of the same templates and assets (images, css, js, videos, etc.).

Site A has two languages NL and FR.
Site B has only one language FR.

Both sites have their own TLD.

How do I set this up in Craft 3? I have tried various ways, but I don't seem to be able to find the right solution.

I was thinking about creating two separate web folders, one for site A and one for site B. With subfolders for nl and fr in the webfolder for site A.
That works, but than I have the problem that I cannot share my assets because they belong to different webfolders.
And if I want to share a product channel for example, when I upload a product image, I want to use that same image in both sites. How will that work?

Also the baseUrl is a mystery to me. If I use @web/nl and @web/fr for site A and @web for site B, the @web gives the correct TLD as output, but the template from site B (which uses @web) are always loaded.

If I try to forgo to separate web folders, it totaly goes wrong...

Can someone please give a working example?


texts: Upload assets to location based on category if entry isn't saved yet?

texts:
I'm building a gallery system and on the entry page I have fields for gallery category (category field) as well as gallery photos (assets field). When creating this entry, I would like to upload the assets field to something like:

images/galleries/category/slug

However, because the category is still being defined in the same entry as the assets are being uploaded, my images aren't put into a folder based on the category.

Is what I'm trying to do possible? What's the best way to approach it? I'm currently using this for my assets file path:

images/galleries/{galleryCategory.first.slug}/{slug}


texts:
I am using Craft only for the blog section of my HTML site. I have integrated my existing breadcrumbs to the blog, but there is a problem.

When I am on the home page of the blog, the word "Blog" in the breadcrumb is linked, and I would rather it not be linked.

I would like the word "Blog" in the breadcrumb to be a link only after going to an article on the blog. Please see attached.

The code I am using right now is

Home

Blog

            {% for crumb in entry.getAncestors() %}

{{ crumb.getLink() }}

            {% endfor %}

{{ entry.title() }}

I am new to Craft - thanks for your help!


texts: Check what methods were used on element query

texts:
I am creating plugin that provides helper methods for constructing search forms, filtering entry lists
by various params etc. And for that plugin, I need to be able to tell which methods were alredy used on element query object - because if you use same method twice, only second one will be taken into account.
So, it is possible to check if for example relatedTo was used on specific element query object already?


texts:
I'm trying to pass an entry field type "Formfield" into a template. I have it working without passing any custom values through but when I do it outside of the render tag, No matter what I do I am getting an error saying null variable cannot render.  Thoughts?
ie: (Below works)
{{ entry.contactFormHandle.render() }}

But: (Does Not) in many variables and difference does not...
{{ craft.freeform.form("{entry.contactFormHandle}", {
                        labelClass: "my-label-class",
                        inputClass: "my-input-class",
                        submitClass: "my-button-class",
                        instructionsBelowField: true,
                        overrideValues: {}
                    }).render() }}

I'm sure it's something stupid. Any help would be appreciated!


texts: How do I create a simple module for one website in Craft?. I don't have much experience in Craft CMS.  I have tried from 3 days but I cannot get an answer. I'm following all the tutorials that I can find, but none I feel are clear. Any recommendations on the simplest of examples, even if it's just outputting a variable.


texts: Display a list of categories excluding the current one

texts:
In a template for a category page, I'm trying to output a list of links through to all categories within a category group but exclude the category that the user is on.

Does that make sense? What I'm trying doesn't work, but I'm new to Craft and Twig!


texts:
This is my first time using the Feed Me import plugin (craft 3.5.15.1). I'm pointing the feed URL to a file in the  public root, e.g. http://dev.mydomain.com/import.csv. When executing the import, I get this error:

Unable to reach http://dev.mydomain.com/import.csv. Message: cURL
error 60: SSL certificate problem: unable to get local issuer
certificate

I don't understand why. The site is a subdomain of a site that uses an SSL, but the dev subdomain does not and I've not had any other issues with craft or the browser expecting an SSL.
Any ideas why or more information I can provide?


texts:
I've just installed Craft on a new Laravel Homestead environment and all seems to be running fine, with the exception of being able to upload a logo in the General settings.

The logo uploads and displays in the popup for cropping, but when I save it, I get this error flashed up:

  Something went wrong when processing the logo.

I've checked the permissions and everything seems fine - the storage dir is set to 777 on my local box just to be doubly sure and I can see Craft is creating files and folders in there.

The $imagePath variable in the RebrandController::RebrandController() method is as follows:

  /home/vagrant/sites/craft-base/craft/storage/runtime/temp/uploads/Rally-Digital-Logo.png&d=1420216657

Aside from permissions, what could cause this?


texts:
Im working on a school website where the client would like a global date that is the start and finish of all the classes. This part is easy as I have made a Global where you enter the Start and End dates for the semester. At the moment this is just a text field.

The next challenge is to make it add days onto the start and end date depending on what day a class starts on.
So for example:
If I say the week starts on a Monday and set the starting date to the 20/10/2015. If the class is also on a Monday it will not change the date. But if the class is a Tuesday it will add +1 to the date making the starting date the 21st. (Wednesday +2, Thursday +3, Friday +4, Saturday, +5, Sunday +6) This would be easy except that if the day goes above how many days there are in a month. for example if the starting date is 28/10/2015 on Friday it would list as 32/10/2015 but would need to be changed to the 01/11/2015.

Does anyone know of a way that I can write this? Would using the date field make this easier?


texts: Charge Plugin - Stripe payments occasionally not being received in craft

texts:
I have some Charge payments on my website, and I have registered the onCharge event in my plugin, like so:

public function init()
{
    parent::init();
    craft()->on('charge.onCharge', function(Event $event) {
        // Function logic here
    }
}

And 95% of the time it works, but sometimes it doesn't trigger. The transaction goes through, and I can see in my Stripe account that it has been successful, but the payment does not appear in my Charge Logs in Craft, and the onCharge event never triggers.

Can anyone help? Any suggestions?

Thanks, Jai


texts: Redactor upload image and file does not work

texts:
I succeeded to add the image and file upload buttons to my rich text redactor field with the fileupload param in the json config file.

{
    buttons: ['html','formatting','bold','italic','unorderedlist','orderedlist','link','image','video','table','file'],
    plugins: ['fullscreen','video','table',''],
    toolbarFixed: true,
    fileUpload: 'fichiers/'
}

But it does not work : when I drap and drop a file or an image it shows the top bar indicating upload in progress but it finish without anything inserted in my field.


texts: Local and Staging Environments allow for updates, Live doesn't (and doesn't recognise the license.key)

texts:
I'm just in the process of migrating a site from staging to live. I've pushed everything over and have copied/moved a license.key file from a site that we're no longer using to this one. However, when I log into the backend, I'm stll getting the You’re running Craft Pro with a Craft Personal license. message at the top. If I click on 'Resolve' - I get a spinner modal and nothing else happens, until eventually I get An unknown error occurred.

Running version Craft CMS 2.6.2952

I'm presuming it's not able to phone home for some reason to validate the license key - but I'm unsure what could be stopping it? Anyone?


texts:
I'm trying to use a macro to output a list of entries (and the title of a section), this is my code:

{% macro sections(sectionName)%}

    {% set index = craft.entries.section('{{ sectionName }}Index').first %}

{{ index.getLink() }}

    {% for entry in craft.entries.section('{{ sectionName }}').order('title') %}

        {{ loop.first ? '
'}}

{{ entry.title }} {{ sectionName }}

        {{ loop.last ? '
'}}

    {% endfor %}
{% endmacro %}

{{ _self.sections('about') }}
{{ _self.sections('information') }}
{{ _self.sections('galleries') }}

But this displays ALL entries. However, if I hardcode the section names (for each loop) it works, though not DRY.

This is my first attempt at using a macro, seemed like a good place to use one?


texts: Assign a number 1-N for each entry that is returned

texts:
I need to assign a # 1-N for each entry that is returned -- i.e., 1, 2, 3, 4, ....   (This is for a sort plugin.)

How do I template for that?


texts:
Is it possible to apply a shipping cost to the cart before a customer enters their shipping address?

The site I am working on has a fixed shipping rate of £3.50 for UK orders under £22. If the order value is over £22 then the shipping is free.

Anyone based in and shipping to, Europe has a set rate based on weight of the order.

Is it possible to set the initial base shipping cost to the cart screen before checkout and then change the shipping cost and method when the customer adds a shipping address during checkout?

What is the best approach for setting these shipping rates in the Control Panel, and how to apply these in the cart?


texts: Using variable references to fields in a template

texts:
I have a situation where Matrix within Matrix would be ideal, but instead we've ended up with a Matrix row that has pairs of fields up to a maximum of 6:

quote1
attribution1
…
quoteN
attributionN
…
quote6
attribution6

Rather than work through each pair…

{% if matrixBlock.quote1|length %} {# quote 1 stuff #} {% endif %}
…
{% if matrixBlock.quote6|length %} {# quote 6 stuff #} {% endif %}

…I thought I might be able to use a variable reference to numbers 1 to 6:

{% set quotes = [1, 2, 3, 4, 5, 6] %}

{% for n in quotes %}
    {% set nText = 'quote' ~ n %}
    {% set nCite = 'attribution' ~ n %}

        {{ matrixBlock.nText|md }}
        {{ matrixBlock.nCite }}

{% endfor %}

…but although {{ dump(nText) }} confirms the reference string is being parsed correctly, the string is clearly invalid as a field reference.

Is there a way to get this done to achieve a nice terse template (not the end of the world if I can't)?

I have a sense that Twig's attribute function might help, but I can't join the dots.


texts:
I have tried to find the new way get the total in a user group in php (plugin), but not having much luck... Please help
Assume it starts with Craft::$app->users ?


texts:
I'm having a problem with navigation that seems to get cached.
If the page is loaded by someone who is not logged in, it shows the login button in the navigation (and it should).
Once the user is logged in and returns to that specific page (by clicking a link on the site), the page still shows the login button.
Only when the user manually refreshes the page, the login button gets replaced by the users name.

The template code uses the currentUser variable, which is never overwritten anywhere else.
There's no cache blocks used on the website, and the cache-control header is set to no-store, no-cache, must-revalidate
{% if currentUser %}
    {% if currentUser.firstName != '' and currentUser.lastName != '' %}
        {{ currentUser.firstName }} {{ currentUser.lastName }}
    {% else %}
        {{ currentUser.email }}
    {% endif %}
{% else %}
    {{ loginPage.title }}
{% endif %}


texts:
Folks:

I am having issue getting Twig to extend the template. The details:

Craft installed fine.
This is on a live server.
The default Craft welcome page appears as normal so Twig must be
working.
When I try to pull up an entry with one of my own templates, Twig does
not pull the content from the main Twig template. You should see the
header info and have the css pulled and all the rest. If I strip
everything out the template and leave some plain text I still see
this in the browser:

{ % extends "_layouttest" % } { % block main % } This is the correct template alright! { % endblock % }

I have done the following:

Checked that I am not pulling the template directly. I am not. This
is a proper URL for an entry I created in Craft.
Dumped the cache.
Checked the template locations from within the CP. All seems to be
pointing in the correct direction. The fact that the right template
is being pulled confirms this.
Read through this thread and this one. No joy.

Any assistance would be appreciated.


texts: Redirect Manager 301 results in "Entry DNE" error

texts:
This is my old URL. No entry exists here:

/post/234234234234/happy-fourth-of-july

This entry exists:

/news/happy-fourth-of-july

I have the Redirect Manager plugin setup as follows:

However when I visit the old URL (above) the URL remains unchanged and I receive a Variable "entry" does not exist template error.

I must be missing something really obvious, so if I can provide more infomation, let me know.


texts: How to output a structure sub-navigation of current page

texts:
I've got a single structure menu for my entire site which consists of a title and a single related entry. I use that to output the main menu, which uses this code:

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

 {# Checks if              the page link is the same as the slug of current page #}
            {{link.title}}
            {% ifchildren %}

                {% children %}

            {% endifchildren %}

        {% endnav %}

On the top level pages, in their template they have a sidebar which should output the menu items in that main section - all singles. Is there a way to do this or do I need to create separate Structures for each section?


texts: No template found when accessing action method per route

texts:
I want to render a (non-CP) template from an action method in my plugin controller over a route I defined in the plugin base class:

function registerSiteRoutes() {
  return array(
    'myservice' => array('action' => 'pluginhandle/controller/method')
  );
}

The action itself basically just sets some things up and renders the template:

public function actionMethod()
{
    // irrelevant code here...

    $variables = array('info' => 'success');
    $this->renderTemplate('pluginhandle/template', $variables);
}

But when trying to access the rendered template via it's routed url '/myservice', an error message is shown telling the template can't be found.

Strangely, it seems to work if I use the full action url actions/pluginhandle/controller/method instead. But, I want to have nice URLs if I can have them, right?

I tried it using craft()->templates->render('pluginhandle/template') and $this->renderPluginTemplate('pluginhandle/template') even temporarily setting a new templates path but none of them seems to change that.

Can someone please help me out?


texts: Best way to access getPrev and getNext asset fields

texts:
I am trying to access the previous and the next blog entries from my current post. Here is what I am doing

{% set params = craft.entries.section('blog').order('postDate asc') %}

    {% set prevEntry = entry.getPrev(params) %}
    {% set nextEntry = entry.getNext(params) %}
    {# to access url, I use #}
    {{ prevEntry.url }}
    {# to access title, I use #}
    {{ prevEntry.title }}

The above works. However, I have an asset under the field handle "featuredImage". I need to access the image URL as well as I need to apply a transform. I am not sure the code below is the most efficient way to do this. Also the image transform is giving me an error (server returns 500 error)

{% for asset in prevEntry.featuredImage %}
    {% do asset.setTransform({ mode:crop, width: 200, height: 200 }) %}

{% endfor %}

Is looping the best way to access the data considering that there is only one image? Is there a better way? Image transform is also not working (not sure why).


texts: Error reporting Freeform submission jumps to top of page

texts:
When submitting a form with required fields and getting an error, the page jumps to the top, where it should jump to the top of the form.

In the standard Craft contact form I can add

<form method="post" action="#errortag">

To define a div or name anchor where the page should go to. How can I do this in freeform (without having to go completely manual)

Right now I'm using the standard tags:

{{ craft.freeform.form("proefles", {
    instructionsBelowField: true,
}).render() }}


texts:
I really like grabcad's 3D viewer feature where the user can rotate, zoom, explode the 3d model.

I am wondering about adding similar feature to showcase my 3d models on my website and use asset field for project entry to load store file address on the html and have the js framework that is capable to rendering interactive primitive 3D model to hook up the file to the engine to display 3d model.

My question for folks out there, is there js framework similiar to grabcad's viewer feature?


texts: Export database table as .sql before deleting/removing a plugin

texts:
When you delete/remove a plugin all the database tables related to it will be deleted and I would like to know if there is a way to keep them or store them into a file and force the user to download it.

I made some kind of forum and saved many relevant information in a custom table but if someone deletes/removes the plugin accidentally or to include another row nothing will work anymore.

Is there I function I can use in public function onBeforeUninstall() to save my table?

I know you can go to phpmyadmin/adminer an use the export function by hand but we are all people and we can forget that.

Thank you very much


texts:
I am making a simple call to entries near a zip code using this url format:

example.com/locations-zip-ajax?near=93003

My template includes this code:

{% set target = craft.request.getParam('near') %}
{% set params = {
  target: target|length ? target : 37212,
  range: target|length ? 30 : 7000,
} %}
{% set locations = craft.entries.section('locationsFeed').address(params).order('distance').find() %}

{% for location in locations %}
      //do some stuff

{% else %}

No results found

{% endfor %}

But no matter what zip code is entered, the results are always in the same order and the nearest entry is always 5,828.2 miles away even if the result entry's zip code is identical to the 'near' param.

I have ensured that my target param is being populated correctly and that my range param is working as well.


texts: import store items from Magento to Craft Commerce

texts:
is there a plugin or script to import products, accounts, categories from Magento to Craft Commerce?
Or is this something to be written from scratch with FeedMe?


texts: Plugin license key is lost every time I update Craft CMS

texts: I have licensed the Verbb Navigation plugin, but every time I update Craft I get a notice that the license needs attention. The key field on the Plugins page is empty after the update. Is this a bug, or is there another way to store the key so it will be saved after an update?


texts: Disabling caches in Safari results in server errors while developing Craft 3 site

texts:
I'm running into a vexing issue while developing a personal site in Craft. I have a new Craft 3 site, installed manually. I'm developing live on the server in a dev subdomain. My .env sets the site to "dev" mode.

It's been awhile since I've worked on a front-end; one thing that's been an issue is either Safari or Craft caches the CSS while I'm coding. To prevent the cache from loading I've used the "ignore the resource cache while loading resources" button in the Network pane of the Webkit inspector. A few times after reloading the page, I begin to get server errors. The server errors are yii exceptions for a missing template of internal_error.html, which suggests a server error and not a Craft error specifically.

I've searched through the logs and although I can see where Craft throws the exception, I can't see what is causing this. The headers on my network simply say that the main site URL is throwing a 404. My server log says:

  [Thu Mar 12 11:29:11.886937 2020] [core:error] [pid 28286] [client
  xx.xxx.xx.xxx:xxxxx] End of script output before headers: index.php

Thinking this might be a permissions issue I started from scratch with a Composer-installed Craft. All was fine until I used the cache button on the Network pane again, and the errors returned.

If I change the mode to "production" from "dev," the errors go away, and as far as I can see no new error is created in the server or Craft log. So I can develop in production mode but I do find the dev mode useful.

I've manually cleared the cache from storage/runtime and cleared the generated files in cpresources. I've also cleared the cache from the backend admin when logged in via production mode. This doesn't have any effect.

I should add the only thing I haven't tried is to disable Safari's caches while running the site in production mode; if it's related I don't want to break the only method I have on working on the site.

Any help here is greatly appreciated!


texts: How to list entries related to a category + related to a section?

texts:
Sorry if this has been asked before. I've searched for other relatedTo questions but could not find anything similar.

I have 2 sections (each having 1 entry type):

games
reviews

Games are linked to 1 or more categories using a Categories field.
Reviews are linked to 1 or more games using an Entries field.

On a category page I can list all related games using:

craft.entries({section: 'games'}).relatedTo(category)

I do however want to list all games inside a category that have at least 1 review. I tried something like

craft.entries({section: 'games'}).relatedTo(category).relatedTo(craft.entries.section('reviews'))

but that lists all games having a review regardless of the category. How to solve this?


texts: Receiving duplicate Sprout Form submissions

texts:
We're seeing duplicate submissions.  It's between 2 - 15 of the same submissions, usually 7. They come in irregularly over the next couple minutes after the first one. And only sometimes. They are all distinct in the database, and seem like copies of a legitimate user submission.

Does this sound like a known issue? What's the best way to approach troubleshooting this?

--- Update 19/11/2019 ---

Duplicate form submission protection through Invisible Captcha is enabled.

I'm using custom form templates with:

  {{ getCsrfInput() }}
  {{ craft.sproutInvisibleCaptcha.protect() }}

But not

  {% hook 'sproutForms.modifyForm' %}

--- Update 25/11/2019 ---

Setting the required time on form to 15 seconds, disabling the Enable Sprout Forms Protection option which automatically adds Invisible Captcha support for all Sprout Forms using the craft.sproutForms.displayForm() tag, removing {% hook 'sproutForms.modifyForm' %}, and keeping {{ getCsrfInput() }}{{ craft.sproutInvisibleCaptcha.protect() }}, allowed a submission to be recorded 13 times over the course of 2 minutes.

--- Update 27/11/2019 ---

The duplicate submissions came from from another, unprotected, instance of the form with it's own template. It submits without loading the redirect URL, clearing the form, or presenting any messages, leaving the user to click the button multiple times.


texts: How can I dynamically remove some unwanted formatting tags inside rich text fields?

texts:
I set up a Redactor config to add h3 headings only. If I copy-paste texts from a text edition software like Microsoft Word and uses h1 or h2 for example in his document, these un-wanted headings will be pasted in the rich text field. In another way, if I add an heading tag like <h1> in the source code mode of Redactor, this unwanted heading will also be added.

How can I prevent this and set a list of unwanted tags that could be dynamically deleted or converted in <p> ?

There are pasteBlockTags and pasteInlineTags options in the Redactor doc (https://imperavi.com/redactor/docs/settings/paste/#setting-pasteBlockTags), but it doesn't seems possible to add these options inside the JSON file stored in craft/config/redactor.

I also tried to add a new formattingAdd option, which I called Remove format, and replace unwanted tags by <p>, but this is an annoying solution because it needs to review each pieces of texts.


texts: Can Control Panel Settings page become very slow with some plugins?

texts:
Despite my best intentions to build sites with minimal use of plugins (in any CMS) I have resorted to a dozen or so on one Craft site with about 25 sections and 1000 entries, to help with both CP and front-end things. Since the v2.5 upgrade (I think) I noticed that the Settings page had become impossibly slow to load (about 30 seconds, and this often within the Settings area too) which stretches my tolerance when I am working. I disabled all loaded plugins and suddenly everything was good again. I then added plugins one by one and tested the Settings page loading time. It eventually came down to two (Cache Warmer and Sitemap) that slowed loading time, and the effect seemed to be cumulative (i.e. one plugin was only half as slow). Is it a reasonable assumption that some plugins may affect Settings page loading time, and has anyone else noticed this? What can I do about it?

I guess someone will mention the L-word (logs) but I always have a hard time understanding which log files to look at and what to look for.


texts: Filtering entries by multiple categories with multiple filters

texts:
I'm trying to build a category filter on a page that lists houses that are for sale. The idea of the filter is to make it possible to select houses which, for example, are for sale or rent, have a certain amount of rooms, a minimum/maximum price and eventually a search option to search at location, postal code or street address.

I first built one filter, which filters if a house is for sale or for rent. This filter works with two anchor buttons in a list. I now want to add the next filter, which is the amount of rooms. This filter should be a dropdown (a select tag with options in it).

I got both filters to work, but I want them to stack upon each other. So when the houses that are for sale are being shown and the user clicks on houses with 4+ rooms, it shows the houses that are for sale AND have 4+ rooms.

What I came up with so far

The filter for sale/rent houses

 {% for offerCategory in craft.categories.group('offerTypes').find() %}

   {{ offerCategory.title }}

 {% endfor %}

The filter for the amount of rooms

<select onChange="window.location.href=this.value">
 {% for offerRooms in craft.categories.group('offerRoomTypes').find() %}
  <option value="{{craft.request.url}}/?category={{ offerRooms.slug }}" name>{{ offerRooms.title }}</option>
 {% endfor %}
</select>

And the rest

{% if craft.request.getParam('category') is not null %}

 {% set offerCategory = craft.categories.slug(craft.request.getParam('category')) %}
 {% set offerRooms = craft.categories.slug(craft.request.getParam('category')) %}

 {% set offers = craft.entries({
    section: 'offers',
    relatedTo: [
        'and',
        { targetElement: offerCategory },
        { targetElement: offerRooms }
    ]
 }) %}

{% else %}

 {% set offers = craft.entries.section('offers').find() %}

{% endif %}

The URL that's being fetched is now: .../?category=forsale and when selecting rooms .../?category=4rooms. What I want to achieve is something like .../?category=forsale,4rooms (I'm nog sure if that's the right way).
If someone also can tell me directly how the search should be implemented that's welcome as well ;). Thanks in advance!


texts: Prevent Asset Transforms from scaling Image past 100%

texts: There is almost never a reason why I would want an image to be scaled past 100% by a transform. This usually results in an image being looking worse than it would if scaled by the browser. Is there a way to tell Craft not to scale an image past 100% of its original size, even if the transform width is larger?


texts:
I'd like to add my site's favicon to the admin part of the site.

I tried to do this using the "Site icon" option under general settings. That adds the icon to the sidebar but not as a favicon.

The only way I've found that works so far is by editing the CP's base layout template and adding it there, but that's obviously a bad idea, as that will get overwritten on update.

Anyone found another way to fix this?


texts: Does Google Analytics track Live Preview 'page views'?

texts:
Will Google Analytics be recording page views / events from within a Live Preview? And if so, is there a way to prevent this from happening?

My understanding is that with Google Analytics you can set the domain for which it should track (e.g. to prevent it trying to track any local build events etc), but I am presuming that the domain used for Live Preview views will be the same as as if a user was viewing the front end of the site?

If it would track Live Preview views, I understand that an option for some people would be to wrap their GA code block in a conditional:

{% if not craft.request.isLivePreview %}{# ga code here #}{% endif %}

but because we have custom event tracking built into the JS, which therefore uses the global ga object, it would not be as simple in our case (though is still an option with a few checks for whether ga is defined).


texts:
I'm trying to access a custom variant dropdown field in a plugin inside the commerce_lineItems.onPopulateLineItem event. How would I access the value of the dropdown, in order to do a comparison on it?

Thanks!


texts: How do I retain form input values after submitting error-ridden form containing matrix field inputs

texts:
I'm looking for a way to keep matrix inputs populated with their original value after submitting a form containing errors. I'm already aware of the method of doing this for general inputs as shown here but I can't find an example of doing the same thing with a matrix field input. Here is my form currently without such functionality.

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="entries/saveEntry">
    <input type="hidden" name="redirect" value="/">
    <input type="hidden" name="sectionId" value="5">
    <input type="hidden" name="enabled" value="1">

    // First goal
    <input type="hidden" name="fields[year][new1][type]" value="goal">
    <input type="hidden" name="fields[year][new1][enabled]" value="1">
    <input type="text" id="descriptionMeasurement" rows="4" name="fields[year][new1][fields][descriptionMeasurement]">
    <input class="dueDate" name="fields[year][new1][fields][dueDate][date]" type="text" placeholder="mm/dd/yyyy">
    <input id="weight" type="number" min="1" max="100" name="fields[year][new1][fields][weight]">

    // Second Goal
    <input type="hidden" name="fields[year][new2][type]" value="goal">
    <input type="hidden" name="fields[year][new2][enabled]" value="1">
    <input type="text" id="descriptionMeasurement" rows="4" name="fields[year][new2][fields][descriptionMeasurement]">
    <input class="dueDate" name="fields[year][new2][fields][dueDate][date]" type="text" placeholder="mm/dd/yyyy">
    <input id="weight" type="number" min="1" max="100" name="fields[year][new2][fields][weight]">

    <input type="submit" value="Save Goals">
</form>


texts:
I’m new at Craft CMS and I hope someone of you could help me a little.
At the moment I get all entries from my blog by

{% paginate craft.entries.section('blogItem').limit(globalSettings.postsPerPage) as pageActive, pageEntrys %}

Actually I have 5 categories (catA, catB, catC, catD, catE) at one level, but now I have another category Nr. 6. (catF)
All 5 categories are shown at the blogpage, but catF sound just shown at an separate page (pageF).

I did not find a way to hide all entries from catF at the blogpage and just show these entries at pageF.

Thy four your help.
smueller


texts: Where do I run validation before database insert?

texts:
I'm trying to wrap my head around when to use a Model and when to use a Record (or both?).

I have both my Model and my Record. In my Controller I call my Service that creates my new Record instance before running the ->save(); command to save my new entry into the database.

Since my Record can run the validation process from my specified rules() array I'm wondering what I have my Model for?

Also since I'm running the actual database command from within my Service and dont have access to the Record in my Controller, how do I return the validation errors to my Controller for later use in my template variables?

Or do I run the validation on my Model in my Controller as well? Seems like I'll be doing the same thing twice if so.... or what am I not getting here? :P


texts: How can I append a structure entry and set its order?

texts:
I'd like to attach children to a specific Structure entry in a specific order...

  Entry A
  Entry B

  Imported Entry 2
  Imported Entry 1
  Imported Entry 3

  Entry C

I've got a $records array to turn into imported entries:

array(
    'name'      => 'Whatever',
    'updated_at' => '2014-02-27T04:14:29Z',
    'position'   => 1, // int representing the sort order
    [...]
)

As I'm looping through my array to create new Craft Structure Entries, I need to be able to define the parent (Entry B), I'm just not sure how. I've figured out how to attach new children to Entry B, I just don't know how to programmatically set their order. My imagination writes code that looks like this:

$parentCriteria = craft()->elements->getCriteria(ElementType::Entry);

$parentCriteria->search  = 'slug:entry-b';
$parentCriteria->section = 'sectionName';
$parentCriteria->type    = 'sectionType';

$entries = $parentCriteria->find();
$parent = $entries[0];

foreach ($records as $row)
{
    $entry = new EntryModel();

    $entry->sectionId = 4;
    $entry->typeId    = 4;
    $entry->parentId  = $parent->id;
    $entry->authorId  = 1;
    $entry->postDate  = $row->updated_at;
    $entry->title     = $row->name;
    $entry->sortOrder = $row->position; // ← quite impossible!

    $success = craft()->entries->saveEntry($entry);
}

It's $entry->sortOrder that's completely made up—how do you attach an entry to a specific parent in a specific order?


texts: Search for non-existing tags shows all entries

texts:
I have 3 groups of tags that redirect to the same template. tags/index.html. All the routing and linking those tags to their group page works well.

<a href="{{ siteUrl }}taggroup/{{ tag.slug }}"

The problem I have is that when I try to enter a tag that doesn't exist on the address bar (e.g., http://sitename/taggroup/unknowntag) I get all entries displayed.

Here's my tags/index.html code:

{% if not tag %}
    {% exit 404 %}
{% endif %}

{% set tag = craft.tags.slug(tag).first %}

{% set entries = craft.entries.relatedTo(tag).order('title').limit(null) %}

 {% if entries | length %}

  {% for entry in entries %}

    <!-- Code Here -->

  {% endfor %}

  {% else %}

   <!-- No Tag Code Here -->

 {% endif %}

What Am I doing wrong? Thanks in advance.


texts:
At the moment use of Tags seems to be case insensitive.
So, for example, it is possible to tag an article as both 'IT Support' and 'it support'.

Is it at all possible to make the Tags case sensitive?


texts: Assets not uploading but will update manually on local server

texts:
Site is running on MAMP PRO locally.
PHP settings:
max_execution_time = 60
memory_limit = 128M
upload_max_filesize = 32M
post_max_size = 32M
I have an Asset source set-up as:

File system Path: "{basePath}images/main-content/"
URL: "{baseUrl}images/main-content/"

In my craft/config/general I have Environment-Specific Variables as per the Craft docs http://buildwithcraft.com/docs/multi-environment-configs
When I upload an image the progress bar goes across but then stays on screen with the spinner constantly spinning. The files never upload.
If I manually drop an image in the images/main-content folder then do "Update Asset Indexes" in Settings the image appears in Assets OK.
"Images" and "main-content" are set to 777
The files aren't particularly big.
No errors in PHP logs.
Where else should I look


texts:
I am trying to redirect a bunch of uploads from our old website that no longer exist. I have one specific section I wanted to route to a resources page, but the rest will simply redirect to the home page.

/uploads*: redirects to homepage

/uploads/resources*: redirects to resources

The first redirect is overruling the second, and everything in /uploads is redirecting to the home page. Is there a way to make a special exception for this one folder? Through using a regex or something else?


texts:
I'm trying to install craft, but I have 4 errors like this on the screen:

Utime failed: Operation not permitted in craft/app/helpers/IOHelper.php on line 1540

What are possible causes, and how can I fix it and install properly craft?


texts: How to determine if a user's email has changed

texts:
I'm trying to determine if a user has changed their email address via a front-end form. From what I've gleaned, the best way to do this would be by checking the existing record during users.beforeSaveUser, store the old email, then compare to the new email during users.onSaveUser.

However, when I get a user's record during users.beforeSaveUser, the newly-submitted email address has already overwritten their record.

craft()->on('users.beforeSaveUser', function(Event $event)
{
    if(!$event->params['isNewUser'])
    {
        $currentUser = craft()->users->getUserById($user->id);
        exit($currentUser->email);
    }
}

This code shows the new email, not the old one.

Is this expected behaviour? Any other way to accomplish what I need to?


texts: Is it possible to show a successful logout message?

texts:
When site members click logout they are taken back to the homepage.

I'd like to redirect the user back to the login page but with a "You're logged out" type of message.

Is something like this possible yet?


texts: Using the coupon code from Craft Commerce site

texts:
I got this code off of Craft Commerce, I had caught an error on the site previously so I'm thinking there might be an error here? I've put it in my file but when I input anything in the form I don't have any response of any kind. I don't get an error message or success message, it just redirects back to the cart and the pricing also remains exactly the same. Thanks!

<form method="POST">
     <input type="hidden" name="action" value="commerce/cart/updateCart">
     <input type="hidden" name="redirect" value="store/cart">
     {{ getCsrfInput() }}
     <span class="{% if cart.getError('couponCode') %}has-error{% endif %}">
     <input type="text" name="couponCode" class="{% if cart.getError('couponCode') %}has-error{% endif %}" value="{{ cart.couponCode }}" placeholder="{{ "Coupon Code"|t }}">
     </span>
     <input type="submit" value="{% if cart.couponCode %}Change{% else %}Apply{% endif %} Coupon"/>
</form>


texts: Show entry on certain date, regardless of year

texts:
A project I'm working on needs to show a daily reading depending on the date you access the page. I plan to create entries for each day of the year, and each year it will show the post for that day.

For example, I'll create an entry with a post date of May 1, 2015. That entry should show on May 1, 2016/2017/2018, etc.

I've tried only putting in MM-DD in the postDate parameter, but no luck; that throws a PHP error. Any ideas?


texts: Multiple Entries fields, show empty ones?

texts:
I am using Entries Field to display related content. I have several Entries Field in an article and i also want to display the fields that are empty, but with their section name.... Is this even possible? I am quite new to Craft, so don't know if I am even in a right direction... Help will be highly appriciated!

{% set assets = craft.entries({
  relatedTo: {
    sourceElement: entry,
      field: ['entry','entry2','entry3']
    },
    order:     "sortOrder",
    limit:     null
  })
%}

{% if assets %}
  {% for asset in assets %}
      {% if asset|title %}
        {{ asset.section.name }}: {{ asset.title }}
      {% else }
        {{ asset.section.name }}: Empty
      {% endif }
  {% endfor %}
{% endif %}


texts: How do I omit a page with just a catagory

texts:
I have a channel with content and I want to only display content from a certain category.

Should I use a slug? Just trying to wrap my head around this.

This is what I have now:

    {% for product in craft.entries.find({section: 'Product', limit:'4',}) %}

    {% for image in product.photo %}

Link to pants!

{{ product.title }}

{{ product.price }}

{{ category.title }}

    {% endfor %}

    {% endfor %}


texts: Detect currently selected source of custom elements

texts:
I have a split-style + New Element button for my custom element type. Thanks to this previous thread, the right-side dropdown menu is working perfectly!

My question now is, how do I get the + New Element side of it working?

I keep studying the entries templates, to see how it's done over there. But I've noticed that when you navigate between entry sources, the page URL actually changes. When navigating between my custom element sources, the page URL does not change.

How can I help the + New Element button detect what source is currently being viewed?


texts: Issue on new craft (craftcms3) setups: vendor Twig can't read system variable

texts:
After installing craft through composer, setting up the database and running craft setup, I have a craft application ready to go.
When I go to settings/general, I always get a crash with following information:
1. in /vendor/craftcms/cms/src/templates/settings/general/_index.html at line 30
    {{ actionInput('system-settings/save-general-settings') }}
    {{ redirectInput('settings') }}

    {{ forms.autosuggestField({
        first: true,
        label: "System Name"|t('app'),
        id: 'name',
        suggestEnvVars: true,
        name: 'name',
        value: system.name
    }) }}

    {{ forms.lightswitchField({
        label: "System Status"|t('app'),
        warning: (craft.app.config.general.isSystemLive is same as(true) or craft.app.config.general.isSystemLive is same as(false) ? configWarning('isSystemLive')),
        id: 'live',
        name: 'live',
        onLabel: 'Online'|t('app'),
        offLabel: 'Offline'|t('app'),
2. in /vendor/craftcms/cms/src/helpers/Template.php at line 106– twig_get_attribute(craft\web\twig\Environment, Twig\Source, null, 'name', ...)
        // Add deprecated support for the old DateTime methods
        if ($object instanceof \DateTime && ($value = self::_dateTimeAttribute($object, $item, $type)) !== false) {
            return $value;
        }

        try {
            return \twig_get_attribute($env, $source, $object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck);
        } catch (UnknownMethodException $e) {
            // Copy twig_get_attribute()'s BadMethodCallException handling
            if ($ignoreStrictCheck || !$env->isStrictVariables()) {
                return null;
            }
            throw new RuntimeError($e->getMessage(), -1, $source);
3. in /vendor/craftcms/cms/src/templates/settings/general/_index.html at line 30– craft\helpers\Template::attribute(craft\web\twig\Environment, Twig\Source, null, 'name', ...)
    {{ forms.autosuggestField({
        first: true,
        label: "System Name"|t('app'),
        id: 'name',
        suggestEnvVars: true,
        name: 'name',
        value: system.name
    }) }}

    {{ forms.lightswitchField({
        label: "System Status"|t('app'),
        warning: (craft.app.config.general.isSystemLive is same as(true) or craft.app.config.general.isSystemLive is same as(false) ? configWarning('isSystemLive')),
        id: 'live',

The errors on the lines correspond to:
line 30: value: system.name
line 106: return \twig_get_attribute($env, $source, $object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck);
line 30: value: system.name
As you can see, all is happening in /vendor, so I guess it must be some setup that I have missed or incorrectly executed. Why is the system variable null? Is it because of my local machine is missing some configuration? (Macbook Pro with macOs Big Sur)


texts:
For anyone installing install Craft on WSL (Windows Services for Linux)...

WSL has enough traction with developers that I decided to take the dive, but I'm having trouble getting permissions straight with my Craft install.

Apparently, PHP doesn't have permission to chmod inside the project folders, which generates this error on login to Craft.

  Failed to change permissions for directory
  "/mnt/c/Users/jimme/sites/mywebsite/craft/web/cpresources/6d799f01":
  chmod(): Operation not permitted

  Caused by: yii\base\ErrorException
  chmod(): Operation not permitted
  in /mnt/c/Users/jimme/sites/jm/vendor/yiisoft/yii2/helpers/BaseFileHelper.php >at line 646

UPDATE:

I've modified my /etc/wsl.conf file to add support for linux metadata, which allows permissions to be set granularly for files in the windows filesystem. I've also changed changed the ownership to myuser:www-data and added group write perms. After making this change it fixed the above error but now I'm getting this on login...

  HTTP 400 – Bad Request – yii\web\BadRequestHttpException Unable to
  verify your data submission.

  in /mnt/c/Users/jimme/sites/jm/vendor/yiisoft/yii2/web/Controller.php

any ideas?


texts: Fetching Unique Categories related to Entries via GraphQL

texts:
Suppose I have some entries in a section called 'product' that are related to a category call 'brand' - I know I can get the brands that are related to each product that match a search term using GraphQL like so:
query Query($searchTerm: String) {
  entries(search: $searchTerm, section: "product") {
    ... on product_product_Entry {
      brand {
        id
      }
    }
  }
}

Which returns something like this:
{
  "data": {
    "entries": [
      {
        "brand": [
          {
            "id": "3"
          }
        ]
      },
      {
        "brand": [
          {
            "id": "5"
          }
        ]
      },
      {
        "brand": [
          {
            "id": "3"
          }
        ]
      },
      ...

What I'm looking to do is get all the brands that are related to the products matching the search, but obviously if I use the above query then the response will get very big very quick. Is it possible to get just the distinct brand id values returned from the above GraphQL query? Or am I better off making a module with a controller action and querying the database that way?


texts: Using Yii CDbCriteria to query a table in a plugin

texts:
First question I guess is "should I be using CDbCriteria at all, or am I overcomplicating things"?

Secondly if I'm ok using it, how do I achieve the following SQL query:

SELECT * FROM myTable
WHERE cottage=3
AND (fromDate BETWEEN '2015-01-01' AND '2015-01-11'
OR toDate BETWEEN '2015-01-01' AND '2015-01-11');

So far I've got this:

$criteria = new \CDbCriteria();
$criteria->addCondition('cottage=' . $booking->cottage);
$criteria->addBetweenCondition('fromDate', $booking->fromDate, $booking->toDate);
$criteria->addBetweenCondition('toDate', $booking->fromDate, $booking->toDate, 'OR');
$previousBookings = BookingEngine_BookingsRecord::model()->findAll($criteria);

Which nearly gets me there, the only issue is when I dump the $criteria->condition, the brackets are in the wrong place. So I get this:

((cottage=3) AND (fromDate BETWEEN :ycp2 AND :ycp3)) OR (toDate BETWEEN :ycp4 AND :ycp5)

The cottage and fromDate are bracketed together, whereas I want the fromDate and toDate bracketed together instead.

Other than manually writing the SQL, is there a more straightforward way of doing this, I feel I'm really overdoing a seemingly easy query!

UPDATE: I did rearrange the addCondition and addBetweenCondition calls as such:

$criteria = new \CDbCriteria();
$criteria->addBetweenCondition('fromDate', $booking->fromDate, $booking->toDate);
$criteria->addBetweenCondition('toDate', $booking->fromDate, $booking->toDate, 'OR');
$criteria->addCondition('cottage=' . $booking->cottage);
$previousBookings = BookingEngine_BookingsRecord::model()->findAll($criteria);

and that did in fact solve the problem. However it does feel like it's working by accident rather than by design. I think Jørgen's answer below  is a bit more straightforward, so I went with that instead.


texts: Disable activation link email for a specific user group

texts: I am developing a website which is having two user groups. The users of first user group will have self activation email with account activation link while second user group will be activated by admin after registration. As there is Users Setting for "Verify email addresses?" but we can't do it for specific user group. Is there any solution for it? Please suggest if possible with plugin.