texts: Getting database error when calling CateogoryService method

texts:
I have a PHP file in the public_html titled categories.php with the following code:

namespace Craft;
$craft = require '../craft/app/bootstrap.php';
$categories = $craft->categories->allGroupIds();

Running this script results in the following message:

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

My craft/config/db.php file looks like this.

return array(
    '*' => array(
        'tablePrefix' => 'craft',
    ),
    'live' => array(
        'server' => 'localhost',
        'user' => '',
        'password' => '',
        'database' => '',
    ),
    'staging' => array(
        'server' => 'localhost',
        'user' => 'DB_USER',
        'password' => 'DB_PASSWORD',
        'database' => 'DB_NAME',
    ),
    'dev' => array(
        'server' => 'localhost',
        'user' => 'root',
        'password' => 'root',
        'database' => 'DB_NAME',
    ),
);

I'm not having database trouble anywhere else, only when I try to call any CategoriesService methods. Is there something that I'm failing to understand here?

Solution:

The CRAFT_ENVIRONMENT constant was being set in public_html/index.php, so my craft/config/db.php file could not choose the correct database credentials. The issue was resolved by setting the constant to 'dev' in my categories.php file, like below.

namespace Craft;
define('CRAFT_ENVIRONMENT', 'dev');
$craft = require '../craft/app/bootstrap.php';
$categories = $craft->categories->allGroupIds();


texts:
im developing a forms plugin and i'm having some trouble getting my plugin model class autoloaded.

To make development easier i'm implementing the Yii way of rendering forms(http://www.yiiframework.com/doc/api/1.1/CActiveForm). The widget basicly takes a model and attribute name to render the form control in HTML. I'm rewriting this for Craft so i can easily hook ajax validation and template macro's to it while still being super flexible and i can easily develop more forms on the same code base later on. This is the setup (as per Craft plugin design);

plugins

forms

models

Forms_BaseModel.php
Forms_ContactModel.php

services

Forms_BaseService.php

FormsPlugin.php

The problem is my model classes aren't getting autoloaded. After snooping around in Craft\PluginsService it seems plugin subclasses are autoloaded per request if their suffix is in the autoloadClasses array found in app\etc\config\common.php on line 661. In this case the suffix is Model so it should get autoloaded.

Since the model class isn't autoloaded nor reachable in the FormsVariable->model() method using Craft::import('path/to/class'), i'm beginning to think this might be a bug or something. I checked for possible typos in the naming but these are all correct.

Does anybody have a clue on what's going on?


texts:
I'm having a weird issue with the Rich Text Editor (Redactor -> simple.json, only "bold" and "italic") on newly added fields and only ONE (that i know of) older field.
Every time i add a "bold" format and then save the entry, it goes back to its previous state and never actually saves it.

If there is a bold word in that block and i try to add / modify other blocks, nothing saves either.

If i don't use "bold" in THAT specific field or newly created ones, it all works perfectly. Even the "italic" option works. If i use "bold" in an other older field, it works perfectly.

It used to work like a charm, no updates has been done since (i did it afterwards to try and solve it: nothing changed).

No trace about that in the craft logs.

Any idea what's the problem? Or how to debug further?

PS: That one is on Craft 2.7.2!


texts:
I've had a potential job come through that I want to run on Craft, but I'm a bit sketchy about one particularly bit. The site is going to include educational modules and tests for each. Test results will be stored in their profile which can be reviewed the admins. I know how to create a new entry for each test submission, but the thing I'm not sure about is this:

How can I store whether a question was answered correctly or not?
Is there a way to display a score based on the test result?

As always, I'm not a plugin developer... if this can be done with template logic that would be perfect.


texts: Make dump() available when devMode is disabled

texts: Is there a way to make the dump() function available in my plugin templates when devMode is disabled?


texts:
I'm having trouble getting the redactorStyles plugin to work. I am running Craft 2.3.2627

Redactor Styles v. 0.2

Here's the json in the json field:

 {
"btnName":"Drop Cap",
"className":"redactorDropCap",
"spanClass":"dropCap",
"forceBlock": "-1"
}

I have an external stylesheet, the field is set to: /assets/css/redactorStyles.css

I am not getting any errors in the CP but I also don't get the styles nor do I see the want icon for the plugin dropdown.

Here's the content from the redactor config file:

{
buttons: ['html','formatting','bold','italic','unorderedlist','orderedlist','link','image','video'],
plugins: ['fullscreen','video','styles'],
toolbarFixed: true,
stylesJson: RedactorStyles.stylesJson

}

Can anyone tell me if I am doing something wrong here or if there is a bigger issue? I'm new to Craft.

Thanks,

Brian


texts: Set Default Entry Types for elements in a Structure Section

texts:
I have a Structure Section controlling my Nav and page contents
So I have

Home

About Us

History
List item
List item

Services

Service 1
Service 2
Service 3

In the Control Panel when I add items to this structure I have 3 different Entry Types.
Is it possible to set it so that when I add a Child to the Services structure item a specific entry type can be set as default as opposed to the first one?

Or should create a different structure section for each one and have its own entry type?


texts: Control Panel or admin dashboard not found

texts:
I have installed craftcms 3 on my localhost. It got installed and the following screen appeared:

If I click on Control Panel I see the following screen


texts: Unable to update slug in Craft 3 for single enteries

texts: I have created some entries for type single but now I am not able to update their slug even I have updated the title


texts: Matrix Error - "Field Limit is too big for your chosen Column Type"

texts:
I have a matrix field which is used a my main Body content field.
The site has just been updated to the latest version of Craft and I tried to add a block to the matrix field but when i try to save it I get the error on a plain text field:

Field Limit is too big for your chosen Column Type.

Even if i open the field and don't make any changes and jut save it I get the same error. The matrix field has 11 Block Types.

I have the same field in another website which actually has another couple of blocks in it and it can save without any issues.

I have found this thread: https://github.com/craftcms/cms/issues/2009
and possibly related to a MySQL issue.

But is the issue related to the size of the Matrix Field? Or overall the number of fields in the database?


texts:
Trying to get my head around plugin development. Sorry if this is a super basic question. How do you add a method to an existing element? I’m trying to get any active Commerce 2 subscriptions for a user. I figured out how to add it as a variable to my plugin.

public function getActiveSubscriptions(int $userId): array
{
    return Subscription::find()
        ->userId($userId)
        ->status(Subscription::STATUS_ACTIVE)
        ->all();
}

It’s called by {% set subscriptions = craft.myPlugin.getActiveSubscriptions(currentUser.id) %}

That works, but I feel like the “right” way is to be able to do this {% set subscriptions = currentUser.getActiveSubscriptions() %} How do I do that?


texts: Retrieving featured entry from a given category

texts:
This piece of code used to work to retrieve 1 featured (lightswitch) entry per category.

{% for category in craft.categories %}
    {% set entries = craft.entries.find({
      section:    'news',
      limit:      '1',
      featured : '1',
      search :"category:" ~ category.title,
      order :'postDate desc'
    }) %}

Somehow I have to save a entry twice now before it appears. Any ideas whats wrong? Is this a craft bug?


texts:
I have a Craft 2 install that's been working fine until recently when the admin page is giving an error:

file_put_contents(): Exclusive locks are not supported for this stream

The front end is fine.

It seems (according to https://docs.craftcms.com/v3/config/config-settings.html) that NFS filesystems do not like Exclusive Locks, and the host uses NFS (the webserver the site is on connects to a backend filer via NFS to read the actual webfiles)

so I have tried changing

/config/general.php

so that useFileLock is set to 'false' but this hasn't changed anything.

Thanks in advance!


texts: Craft Commerce 1 - Stripe payment intents SCA ready

texts:
I am using Craft CMS 2 with Commerce 1.
I want to update to the new SCA ready (3d secure) Stripe integration.
Has anyone made this already?


texts:
Is it possible to get an idiots guide to this:

Error on Craft 3 install

I'm just not following the context of the answer/commands, a detailed step by step would be invaluable for fear of trying something, not really understanding what's going on and possibly doing it wrong and affecting dependent tech, just a thought, thanks.


texts: How can I use images from my live Craft Site when developing locally

texts:
I'd like to sync the database of a live site to my local site for development, but don't want to download all the images and files. Is there an .htaccess that could look for the files locally, and on 404 look to the live site? What are the implications for image transforms etc?

There seem to be some solutions available for WordPress and Drupal, but has anyone had any experience with this with Craft?

Thanks


texts: How to prevent non-image files being uploaded through frontend form?

texts:
Is this possible? At the point of upload, the entry field isn't checked so anything can be uploaded, which is a bit worrying.

Then again, if it's an Amazon S3 bucket, does it even matter? It won't be sitting on the server.


texts:
Bit of a generalist question but in case someone has anything to share... I am thinking of building a campaign site in Craft that will register 15,000+ users. Is there anything I should be aware of or pay particular attention to?

The users will have a front end registration and a dozen custom fields.


texts: How to return entries based on Checkboxes field criteria?

texts:
Ok I'm building a plugin that needs to check for an id in an array and return only users that have the id in the checkbox array.

So this is what I have:

$user_criteria = craft()->elements->getCriteria(ElementType::User);
$user_criteria->interests = $interestId;
$users = $user_criteria->find();

interests is a dynamically created checkbox array which sits under the users profile. $interestId is the id I wish to look for in that array and return all users that have it.

Any help much appreciated.


texts: Search results by closest match to query

texts:
I currently have a search box which returns results, but only seems to return results if the search term is an exact match. For example, if i search hospital I will get 5 results back with the name hospital in the title, but if i search hospitals i will get no matches found. I would like the search to return results that are close to the search term as well. This is how i have it set up.

This is my search box. It returns to the same page as my index page has an {% include "components/search" %} to display on the homepage.

   <form class="navbar-search" action="{{ url('') }}">

        <input class="form-control" placeholder="Search" name="q" id="srch-term" type="search">

        <button class="btn btn-default" type="submit"></button>

  </form>

Then my search component is this:

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

{% paginate craft.entries.section('Organizations').search('title:' ~ query).order('score').limit(10) as entries %}
    {% if entries|length < 1 %}
        {% paginate craft.entries.section('Organizations').search('organizationSummary:' ~ query).order('score').limit(10) as entries %}

If the title returns no search results I wanted it to search through a summary section instead. Currently it works very well except for only returning exact terms. I'm a bit stuck as I'm ordering by score as shown in the Craft documentation so not sure what I am missing here. Any ideas?

Thanks


texts:
I'd like to get an output of Spring 2015 from a post entry that was written in March. Here is a JavaScript solution

http://jsfiddle.net/RtC58/3/

But I'm hoping I can do something in the template instead. Thanks!


texts: Re-populate additional fields on Contact Form on failure of form validation

texts:
I'm using additional fields on my contact form. I want to re-populate the additional fields if/when the form fails validation, but it's not working so far.

To re-populate a standard field, the code uses an attribute of message using dot syntax…

<input name="fromName" id="fromName" value="{% if message is defined %}{{ message.fromName }}{% endif %}" type="text">

But for additional fields the value is stored as an attribute of message.message using the subscript syntax (the use of square brackets below)…

<input name="message[Phone]" id="phone" type="text" value="">

I'm having trouble accessing the substring value on message.message. In my specific example, I have several radio buttons that need their selections remembered in case anything goes wrong. Here's what I expected to work…

{% for course in courses %}
    <input id={{ course.slug }}" name="message[Course]" type="radio" value="{{ course }}"
         {% if message is defined and message.message[Course] == course %}
             checked="checked"
         {% endif%}>
{% endfor %}

However, this code outputs the template error:

Variable "Course" does not exist.

How can I re-populate the additional fields for the contact form plugin?


texts: Is it possible to let customers enter their email on individual product pages if the stock is 0, and then automatically send them an email when the stock goes above 0 again?


texts: Does a plugin runs it's migrations on install?

texts:
I'm developing a plugin, bumping the version number to run the migrations I'm creating but then, for sanity, checked they run when the plugin is installed for the first time, which doesn't seem to be the case.

Could someone clarify how to get the migrations to run on install?


texts:
When writing a plugin is there a Craft request to grab the entire url? I want to grab everything including http://domain.com/uri preferably without writing my own function.

I see getUrl but craft()->request->url only returns 'uri' of http://domain.com/uri.


texts: Attempting to create a complicated grid layout with batch

texts:
I'm trying to create the following layout using batch, but I can't quite get it right...

This is how far I've gotten:

{% for entry in items|batch(3) %}

     {% if loop.index is divisible by(5) or loop.index == 1 %}

        {% for batch in entry[0:3]   %}
          {% if loop.index == 1 %}

{{batch}}

          {% elseif loop.index == 2 %}

{{batch}}

          {% else %}

{{batch}}

          {% endif %}
        {% endfor %}

      {% elseif loop.index is divisible by(2) %}

        {% for batch in entry[0:2] %}
          {% if loop.index == 1 %}

{{batch}}

          {% else %}

{{batch}}

          {% endif %}
        {% endfor %}

      {% elseif loop.index is divisible by(3) %}

        {% for batch in entry[0:3] %}
          {% if loop.index == 1 %}

{{batch}}

          {% elseif loop.index == 2 %}

{{batch}}

          {% else %}

{{batch}}

          {% endif %}
        {% endfor %}

    {% endif %}

{% endfor %}

Json used:

{ "items": ["1" , "2", "3", "4", "5" , "6", "7", "8","9" , "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22" ] }

Any help will be much appreciated.


texts: Complete working example for adding Craft Commerce items to the cart using AJAX and jQuery?

texts:
I'm using Craft Commerce and every time I click the Add to Cart button for a product, I'm redirected to the Cart page. This works okay, but I'd like to use AJAX (with jQuery v1.12.4) for this to save being redirected to the Cart page.

I'm not great with JS though, so I was trying to find a complete working example for this in the demo templates get me started but I couldn't find one. I did find a similar question on here, but I don't think that's a complete working example as when I tried putting the JS from that example in my own functions.js file, I was getting a syntax error, so this is why I'm asking my own question. Thanks in advance for any help.

Here's what I'm using to show how many items have been added to the cart in the header:

{% set cart = craft.commerce.cart %}
({{ cart.lineItems|length }}) Items

Here's the markup I'm using for the current non-AJAX add to cart form:

{% for product in products %}

  {% for purchasable in product.variants %}

    <form method="POST" id="addToCartForm">

      <input type="hidden" name="action" value="commerce/cart/updateCart">
      <input type="hidden" name="redirect" value="basket">
      <input type="hidden" name="purchasableId" value="{{ purchasable.purchasableId }}">
      {{ getCsrfInput() }}

{{ product.title }}

{{ purchasable.price|commerceCurrency(cart.currency) }}

      <input name="qty" type="number" min="1" value="1">

      <input type="submit" value="Add to Cart" />

    </form>

  {% endfor %}

{% endfor %}

Here's my functions.JS file (i.e. empty after getting nowhere with other examples that I was trying to cobble together):

$(function() {

});


texts: Echo locale title in controller (craft cms 2)

texts: I want to echo the translated title of an entry in the controller of a plugin. How can i acces the locale data?


texts: Overriding BaseFrontEndController in Craft Commerce

texts:
Is there a clean way to alter the cartArray that is returned when updating the cart through ajax? Which is defined in the BaseFrontEndController Craft Commerce.

For example by using a module? In this question Override a model method via plugin, Yii 2 dependency injection support is mentioned, but I feel like I need someone to point me into the right direction.

Thank you!


texts: Check if a Relationship field has a relationship without extra query

texts:
Is there any way to check if a relationship field has a value/is assigned to other elements (assets/entries) without having to add an extra query?

I have a Channel with an Asset field assigned to it. Now let's say I have a list of 100 entries. This list should show a thumbnail and the entry title. I only want to "fetch" the related image thumbnail if the user has choosen to select any image to reduce the amount of queries used.

The "standard" way which results in ~100 queries

{% set image = entry.image.first() %}
{% if image %}

{% endif %}

The way I tried it, but |length adds (1) query making it ~100 queries + the queries for each found thumbnail

{% if entry.image|length > 0 %}
    {% set image = entry.image.first() %}

{% endif %}

Is there a third option I can use to check (without a query) is the entry.image has any related content assigned to it?

Thank you


texts: How to do multi-environment app config (config/app.php)?

texts:
I'm trying to setup different mail settings per environment. Here is my mail component that I'm defining in config/app.php:

'components' => [
    'mailer' => function() {
        // Get the stored email settings
        $settings = Craft::$app->systemSettings->getEmailSettings();

        // Override the transport adapter class
        $settings->transportType = craft\mail\transportadapters\Smtp::class;

        // Override the transport adapter settings
        $settings->transportSettings = [
            'host'              => 'localhost',
            'port'              => '1025',
            'useAuthentication' => false,
            'encryptionMethod'  => null,
            'timeout'           => '10',
        ];

        return craft\helpers\MailerHelper::createMailer($settings);
    },
],

How do I ensure this only applies to development environments? Multi-environment doesn't seem to work like it does for config/general.php and there's no multi-environment example in the relevant documentation. Brandon's Github comment here suggests that this is possible. Thanks.


texts: Filter out part of _layout on a specific template

texts:
I have a site consisting of 15 templates, all of which extend _layout.html.  There is just one page (homepage) which needs to omit a chunk of the _layout.html.  Is there something I can add to _layout which says "if I'm on the homepage leave this chunk of code out"?

Many thanks

Martin


texts: Craft 3 Multi-site with no “default” site AND where control panel login route remains intact and additional directories not necessary

texts: Maybe one of you can help me out? I've tried setting up a multi-language site with no "default site" as per Craft 3 Multi-site with no "default" site. So far so good, except the control panel is not reachable via domain.com/admin. It's only reachable with the language ending, for example: domain.com/en/admin. I would prefer it would be reachable without the language ending. And is there any way to accomplish this without the additional language directories? It seems like a lot of repeated code. Anyone have any ideas? TIA!


texts: Channel Section with individual entry template and index templates?

texts:
I am looking for suggestion on how to setup a resource section on a site I'm building. Here is the structure.

Resources - Index

Entry type of resources
Webinars
-Webinar Entry (template for a single webinar)
-Webinar Index (all webinars)
Whitepapers
-Whitepaper Entry (template for a single whitepaper)
-Whitepaper Index (all whitepapers)
Ebooks
-Ebook Entry (template for a single ebook)
-Ebook Index (all ebooks)

I was originally thinking to this as a channel, but how to I create indexes for the entry types: webinars, whitepapers, and ebooks?


texts:
I have a local craft.dev server running MAMP, and a public server (mysite.com), that both access the same database (on the public server). I then have some environmentvariables in general.php that makes this work smoothly (setting siteUrl and basePath for the different environments).

However, this doesnt seem to work if I access my public servers Craft CP, and add a new user. The activation link won't work on the users end. If I check Craft CPs General Settings it says the siteurl is craft.dev (even when I'm on mysite.com/admin), so that might be the problem, I guess.

This is how I have setup my general.php:

'.dev' => array(
    'devMode' => true,
    'environmentVariables' => array(
        'siteUrl' => 'http://craft.dev/',
        'basePath' => '/Users/foo/'
    )
),

'mysite.com' => array(
    'cooldownDuration' => 0,
    'environmentVariables' => array(
        'siteUrl' => 'http://mysite.com/',
        'basePath' => '/home/mysite_ftp/www/'
    )
)

Would it make sense if I visit mysite.com/admin, change the CPs general settings siteurl to mysite.com/, add the user, and then change siteurl back to craft.dev? Would the activation link work on the users end then?  And, can I do any harm by changing this siteurl-setting (just to give it a try)?


texts: Craft CMS plugin route redirects to login when not logged into Craft

texts:
I created a simple Craft plugin to allow for custom action URLs. Specifically, I have a path "actions/api/sendEmail" that hits a method in my plugin's controller. It sends an email from a contact form via Ajax.

This works perfectly when I'm logged into Craft in the browser. But if I am not logged in, Ajax hits the "actions/api/sendEmail" URL and then gets redirected to "/login". Is my plugin not set to be a public-facing, front-end plugin? I'm pretty new to Craft. I've read through a lot of the docs about plugins and routes but can't seem to find the answer.

Thanks in advance for any help!

Here's my plugin controller class file:

<?php
namespace Craft;

class apiController extends BaseController {

  function actionSendEmail() {

    $name = $_POST['first_name'] . ' ' . $_POST['last_name'];
    $email_address = $_POST['email'];
    $phone = $_POST['phone'];
    $company = $_POST['company'];
    $title = $_POST['title'];

    $email = new EmailModel();

    $email->toEmail = 'luke@graftonstudio.com';
    $email->subject = 'Contact Form Submission';
    $email->htmlBody = '

Contact Form Submission

                                                Name:
' . $name . '

                                                Email:
' . $email_address . '

                                                Phone Number:
' . $phone . '

                                                Company:
' . $company . '

                                                Job Title:
' . $title . '

';

    craft()->email->sendEmail($email);

    // not returning anything at the moment
    echo json_encode(array());
  }

}


texts: How to remove domain from paginate.nextUrl?

texts: What makes a site's domain appear within the output of paginate.nextUrl? I am experiencing a situation where it is not there in my local dev environment, but IS there on production server. I'm sure it's related to some more global configuration, but the answer is so far not obvious. Thanks!


texts: Can Garnish be extended to allow plugins to use custom keyboard shortcuts?

texts: For example, when editing an entry cmd + s saves the entry. Is there an easy way to extend Garnish to allow for my plugin to listen for custom keyboard shortcuts?


texts: Plugin I created is asking for a license key

texts: I created a plugin for a client website and I keep getting license issues popping up in the admin panel for it. Not sure what I am doing wrong here. Obviously I have no intention of putting it into the store, I just want to remove this license key issue.


texts: Craft Commerce 2 - extend Order details page

texts:
Let's say we're on the order details page with the 3 tabs - Order Details, Transactions, Status History

How do I add an extra tab with content?

Craft V3 / Commerce V2

Thanks


texts: How to find number of assets inside a matrix block?

texts: I have a matrix block which has an asset field inside of it. I want to know how many assets are inside the block, is there a way to do so?


texts: Is it possible to totally reskin the admin panel with a new template?

texts: Can the control panel have a skin or theme applied without it affecting automatic updates?


texts:
I disabled translation for Spanish and it returned 404 page.

I set all my fields to translatable and By default craft translations are empty.

How can I return English by default? Using Spanish locale

Thanks! :)


texts:
I am trying to create a carousel where each slide will have a title, subtitle, and maybe a summary.

I know I can create a carousel like this with a set number of slides.
I would like to create one where if an image is added the subsequent fields(title, subtitle, and summary) would be made available for that slide. This way I could have as many slides as possible.

I believe this may be accomplishable with Neo since it allows me to go three layers deep into a matrix. Sadly due to the project constraints, we cannot use any Matrix plugins like Neo or Supertables.

Is there any other way to accomplish this without the use of a plugin.

Right now we are using Craft 2. If this is not possible in Craft 2 I would be interested to know if it would be possible in Craft 3.

Is this possible with the limitations set forth
How would this be accomplished


texts: ActiveRecord Primary Key - Auto increment

texts:
With Craft Active Record, using the definedAttributes Method how do I set my Primary Key Field to auto increment?

Or does it just calculate another number for the field that has not been used when the record gets saved?

Thanks for your help.


texts:
I'm trying to adjust a google maps so have pins that correspond with my posts. I'm nearly there but I'm trying to load info into the info window. I can set it's content already by hand. And I have turned the info i want in the bubble into a html result. All I need to do is alter this so that the twig commands create a string I can pass on in the function that will add the pin.

So I'm trying to create a string result from the code below, which has all the results in it.

Here's what I got (and this works to produce the HTML I want to put in the info window of the pin:

—

{% set resultsNum = 0 %}

{{ block.location }}

{% set searchString = block.location %}
{% for entry in craft.entries.section('journal').find() %}
{% for block in entry.locations %}
    {% if block.type == "location" %}
        {% if block.location == searchString %}
            {% set resultsNum = resultsNum+1 %}

{{ entry.title }}

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

—

The resulting string would go here (this code works already if i set my own string of html:

    {% set marker = {
    lat: result.geometry.location.lat,
    lng: result.geometry.location.lng,
    content: infoHTML
    } %}

Thanks in advance for any help!


texts: Is it possible to output message on successful save with Guest Entries?

texts:
I'm currently using the Guest Entries plugin with a front-end form to accept contact form submissions.

I'm just wondering if it's possible to output a message on a successful form being saved?

In an ideal world this might include the name of the submitter but failing that just a plain message informing the user that the form has been submitted.

(Previously I've been able to access the craft.request.getPost('name') but I don't think this works when using this plugin?

Thanks!


texts: UrlHelper::getUrl() doesn't appear to take the current locale ID into account when generating a URL. Absolute URLs are fine as it handles that but is there a best practice way to localize relative Urls such as /foo/bar or foo/bar?


texts: How to add a non-breaking space to a rich text field?

texts: Seems like a basic question but I can’t figure out a way to do this out of the box, or reference to it in the Redactor docs. ‘&nbsp;’ always gets stripped out.


texts: No live preview available when entry status is set to disabled?

texts:
I have a few entries which are set to disabled. It seems that the live preview is not working then. It only works when the entry status is enabled.

This seems more like a bug than a feature, right?

Update

I have checked everything again and all conditions stated by Brandon below are met, but now I see that I actually don't use the "entries own url" setting. It's enabled, so I get the live preview button, but I use dynamic routing to create my own url's (because I need to add a category as a segment in the URL).

So that's probably where it goes wrong. I check the last segment of the URI as the slug of the specific entry and set my entry manually by it.

So how do I make live preview work than?


texts: How do I query data using the Element API Plugin based on a custom field?

texts:
I have a channel called "offers".

My Offers channel contains a field called "Users".

The Users field is the "users" field type. It allows me to select 1 or more users that the Offer is for.

I want to get JSON output for this data based on the "Users" name.

'users/<username:{handle}>/offers.json' => function($username) {
            return [
                'elementType' => 'Entry',
                'criteria' => ['section' => 'specialOffers', 'relatedTo' => $username],
            'transformer' => function(EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'category' => $entry->category->label,

                ];
              },
            ];
        },


texts: Moved from dev to prod server, admin page blank

texts:
I have a dev server (sandbox.site.com) and a prod server (www.site.com). I copied over the contents from sandbox to dev using cp -r. Loading up my website on the production site looks fine. Everything is where it should be, the few entries I have in place loaded, images are there, etc.

The problem comes when trying to load the admin panel; I get a white screen. I enabled devMode and that gave me the login fields with no styling. I am unable to login (99% certain I have the user/pw right) and there are no error messages.

I searched for "error" in my craft.log, but nothing really stood out at me. I have a lot of the following errors:

[exception.Craft\HttpException.404] exception 'Craft\HttpException' in /home/user/craft/app/controllers/TemplatesController.php:59

but the timestamp isn't the same time as trying to login to the control panel.

Any thoughts?


texts: Get a brand list of products for Javascript filter

texts:
I´m working on a website of veterinary products. Some of the product fields are "category" and "brand".

I have a product list page that shows a list of products of certain category, and I have a JS list to filter by "brand". So, what I need is to get a list of the brands from the products of this specific category ( without repeating ), so I can create the JS filter.

Any ideas? :)


texts: How Do I Restart an Entries Loop Once It Hits the Last Entry

texts:
So I've got a Matrix block that is pulling in some entries and I'm looping through the entries in that block in a template. I'm then pulling a text field from each entry and putting it onto a page. Currently, there are three total entries in that block (though that will likely expand over time). Once I hit the third and final entry, I would like the loop to start over again at the first, loop through the entries again until it gets to the last entry and start over again. I'd like to do that continuously up to a point - say 15 loops.

I'm struggling with how to get the entry loop to start over once it reaches the last entry.

This is the current basic code that loops through the entries and then loops through the matrix blocks within the entries to output the text to pull into the page.

{% for entry in block.homeClientQuote %}
    <div>
        {% for block in entry.clientQuote %}
            {{ block.actualClientQuote }}
        {% endfor %}
    </div>
{% endfor %}


texts: How to output siblings including the current entry?

texts:
I'm trying to output all the siblings of the current entry in a multi level structure like this:

{% for sibling in entry.siblings() %}

{{ sibling.link }}

{% endfor %}

This works well, but how can I make this output all the siblings and the current entry?

I know I could add:

{{ entry.link }}

before or after the sibling.link, but that would mess up the sort order.

If this can't be done this way, maybe I could somehow output the current branch/depth using a different approach? Any suggestions?


texts:
I just deployed a site (still under work) on a sandbox subdomain (https://sandbox.site-name.org/) and I am getting license problems alerts. Also, the site is user/password protected (Apache basic auth, htpasswd).
The complaining plugins are verbb\comments and craft\commerce. Is this normal? Should I worry? How can I get rid of those alerts?


texts: Monthly subscription with Stripe using iDEAL

texts: Does anybody know if I can use Stripe to facilitate subscription payments using iDEAL (Dutch payment method). For instance using the Charge plugin or Sprout Commerce? Thanks in advance.


texts: What the best strategy to test Craft template?

texts: I would like to know if there is a way unit test templates using Craft 2.5? For example trying to prevent null pointers happening in production when an image is remove from the entry


texts: "Giving your Plugin its own CP Section" What about the CSS?

texts: I'm working on a plugin with it's own CP section as described in the docs here. What is the appropriate way to include CSS styling for that page?


texts: Installing Craft without installer screens

texts:
Is it possible to install Craft from the command line or without going through the installer screens?

is it as simple as using bootstrap.php and then calling craft()->install->run($inputs); with valid inputs?


texts:
I'm building a site for a soccer school, where parents will register their children into classes. Aside from a standard registration page, I want to assign photos to children so parents can quickly see photos with their child, and allow parents to RSVP to events.

I'm thinking the registration flow should go:

the parent enters their details in a standard form (creates a user)
redirected to the 'next page' which is another standard form to enter child details (creates an entry)
the age group they select for their child is the class they will join (a category)

Parents as users can then see the entries belonging to them (their children) and those entries are assigned to a category (the class). I can then upload assets to the entries (children) which the parents will see as 'author' of the entry.

Does anyone have any other potential ways of doing this? If I go for this method, I'm trying to find a way to pass the author ID to step 2 where they enter their child's details, so that entry is automatically assigned to them. Does anyone have any ideas on that?


texts: Database driver & version after server upgrade

texts:
The server I'm running Craft installations on just got an upgrade to Ubuntu 20 with MariaDB 10.5 Before MySql 5.7 was used.
When I look at the System Report in the Craft CP, it says: Database driver & version    MySQL 5.5.5
When I look at phpMyAdmin it says: "Server-Version: 10.5.6-MariaDB-1:10.5.6+maria~focal-log - mariadb.org binary distribution"
Why is it showing MySQL 5.5.5 in the System Report?


texts: Pages for each entry from an entry type?

texts:
Let's say I have an entry type named "Designers", and I have:

A title field "Full Name"
A categories field "Specialty"
Another categories field "Location"

Now I want each designer (that is, each entry) from the "Designers" entry type to link to a another page showing blog entries on which this designer's work is featured.

I'm sorry if I'm not being clear enough... Basically, it's a basic directory what I want to build. People can find designers by specialty and location (not sure if categories is the right way to do it...any suggestions?).

My question is how can I create that page showing the entries. Maybe this can't be done with entry types and I need a separated channel?!


texts: Add custom element criteria attribute without a field type?

texts:
Is a custom field type and making use of modifyElementsQuery the only way to add my own craft.entries element criteria model attribute to modify the elements query?

What if I do not want to add a new field to each entry type I want to use my  attribute with? The field would be a hidden pseudo field anyways, as I'm only working with other fields' data.

My current solution is passing the element criteria model with all other params set to craft()->elements->buildElementsQuery() using a template variable. It works, yes, but I would really like to avoid this (pagination not possible and some other disadvantages).


texts: Questions prior using Craft for the first time

texts:
Hi Craft CMS community

Short background: I am working for over 10 years with CMS and lately was using ProcessWire (and sometimes WordPress). Both are fine and especially ProcessWire is a really cool CMS for all sorts of things. I've built small to large websites, shops, blogs etc. with it.

However, sometimes I feel like the last 10% of awesomeness are missing :-) and some parts doesn't match my needs. That's the only reason looking for something else and Craft looks quite good (knowing there is nothing fitting 100%).

I read the templating docs and those for plugin development. But there are some questions left.

There is no MVC like system, right? Where do I put (separate) code that is not for frontend output? Like on a calendar where a user can filter what needs to be displayed (aka the controller).
I really couldn't figure out how to create an entry (I think this is something like a page in Craft) from the API not the CP?
Do I need to use plugins for all kind of interaction (like gather user data from a form and save it as an entry or somewhere else in the Craft DB)? Or implementing PayPal or using PHPMailer or creating PDF files etc.

I consider using it for first time on my next project. Not a simple corporate website, but with a lot of different challenges how to convert clients ideas into a web-project :-) Do you think Craft has a rather steep learning curve like Magento or is something simple to use as WordPress? Maybe here are ProcessWire user with experience on both CMS.

Thanks for reading :-)


texts: Setup different shipping costs per product category

texts:
I have multiple to products in two different categories; shirts and mugs. I want different shippings costs for these categories.

Currently I have a shipping method (default) which is (apparently) applied on all products, no matter which category.

How can I setup a second shipping method and apply them as soon as somebody adds a product to their cart which has this category (mugs in my case, different shipping price than shirts)?


texts:
I have your standard contact form. (Name, email etc.)

When the user clicks "save" I want to capture what was entered via a plugin & have a CP page to show the people who have filled out the form. I'll get there eventually, but for now I am stuck actually inserting the record.

I am able to insert a record, but it's completely empty. So I know I'm getting close, just not passing off the right information to the right spot.

Model:

public function defineAttributes()
{
    return[
        'firstName' => [
          'type' => AttributeType::String,
          'required' => TRUE
        ]
     ....
    ];
}

Controller:

public function actionSaveContact() {
    $this->requirePostRequest();

    $model = new Model();

    $model->firstName = craft()->request->getPost('firstName');
    ....

    if ($model->validate())
    {
        craft->service->saveContact($model);
    }
}

Service:

public function saveContact(Model, $contact) {
    error_log(print_r($contact, true));

   // I know the data is showing, I can see it in the log
   // [_attributes:Craft\BaseModel:private] => Array(
   //     [firstName] => Bob
   // )

   // Here is where I am hung up. I don't know what to do next.
   // $record = new Record();
   // $record->save($contact); This creates an empty record in my db
}

I feel really silly asking for help on what seems like such an elementary task. I'm close - just need a little shove in the right direction I think.

Thank you!

EDIT

Thank you to Mats Mikkel Rummelhoff for your suggestion. It pointed me in the right direction. It seems what I am encountering now has been found in the past? Now it seems I am only saving one field? Using this post I was able to "manually" collect all data and save to my DB. I'm not sure why though - all of the data seemed to be available.

Service

....
$attributes = array(
    'firstName' => $model->getAttribute( 'firstName' )
    ....
);

foreach($attributes as $k => $v) {
    $record->setAttribute($k,$v);
}

if ( $record->save() )
{
    error_log('SUCCESS');
}
else
{
    ....
}

EDIT

Thank you so much for everyone's contribution(s). I'm going to keep updating this in the event that someone else comes across this same problem.

Going along with @Stuart Whitehead comments, right here is proof:
"AttributeType::String does not apply any validation rules." Which is why that field was not getting populated.

Which is what I was setting as my firstName, lastName and so on.

I have also found this article: The Definitive Guide to Validation in Craft Which, is making more and more sense each time I go though it.

The tricky part (for me) is that there isn't a direct corolation between craft and Yii. Meaning that Yii doesn't have a defineAttributes() method where the rules are defined. Craft uses this method, and translates it (for lack of better words) into the Yii equivalent. Pretty cool, just increases the learning curve a bit.

Light bulbs are coming on!

EDIT

This is probably pretty elementry, but I have also discovered that the attribute type that you define in your model, must match the same attribute type in your record. For example:

Record

public function defineAttributes() {
    'firstName' => AttributeType::Name,
    'lastName' => AttributeType::Name,
    ....
}

Model

public function defineAttributes() {
    return [
        'firstName' => [
             'type' => AttributeType::Name,
             'required' => TRUE
         ],
         'lastName' => [
             'type' => AttributeType::Name,
             'required' => TRUE
         ],
         ....
    ];
}

Now with things starting to get in the correct way of doing things, gasp stuff is working. Now using @Mats Mikkel Rummelhoff's comment (having all fields validate now) I am able to use:

$record->setAttributes( $model->getAttributes() );


texts: How to skip the first X entries using ElementAPI

texts:
I'm looking how to use the .offset(x) parameters of craft.entries inside the ElementAPI.

I tried to add 'offset' => 1 before, after and inside the criteria array, but the x first entries are still added to the JSON.

How can I skip the first X entries of ElementAPI?


texts: Supertable or Neo for nested Matrices and compatibility with Craft 4

texts:
I typically avoid using Supertable or Neo because I don't want the extra dependency going forward. However I'm in a project where I needed nested matrices.

I know that in C4 nested matrices will be possible and that there is likely to be a migration script for that (according to what I remember from dotall2019). That being the case which plugin is recommended Supertable or Neo?

Will they both have a migration path to Native?


texts: Display text field from Matrix of an Entry Field in Matrix

texts:
Question is similar to some others I've looked through but their solutions don't work as there are some differences.

Currently this doesn't output any of the fields I try to access within the internal matrix.

{% for entry in craft.entries.section('sectionHandle').find() %}
    {% for block in entry.matrixHandle.limit(1) %}
        {% for entry in block.entryFieldMatrixHandle.first() %}
            {% for block in entry.entrysMatrixHandle.limit(1) %}
                {{ block.fieldHandle }}
            {% endfor %}
        {% endfor %}
    {% endfor %}
{% endfor %}


texts: Error 'form[fieldName] :  is invalid' while submitting multiple checkboxes

texts:
I have a form with multiple checkboxes in it. However, when submitting the form it returns an error like this:

{"success":false,"errors":{"formDate":["Date is invalid."]}}

template:

<input type="hidden" name="fields[formDate]" value="">

{{ 'Select your date(s):' | t }}
{% for date in dateList.options %}
    <input :class="{ error: error['formDate'] }" type="checkbox" name="fields[formDate] []" value="{{ date.value }}">{{ date.label | t }}
{% endfor %}

I'm using Vue component to serialise the form. Checkbox field is posted as the array of checked values.

While searching the documentation I found only how to display the checkbox on the template. Probably the error is connected with the format of values passed through the AJAX call. Does anyone know the acceptable value format for the checkbox with multiple values?


texts: How to enable changing the status of my own Element Type

texts:
So i have created my own Element Type and enabled statuses with the hasStatuses() method.

In the ControlPanel its shown that each element has its own status, but it cant be changed. See image below:

The checkboxes are missing to select the desired entry and then disable or enable it. Im crawling through the source code but i am not able to find a clue on how to enable this feature.


texts: Search only by Field instead of entire content

texts:
I have a vacancy's website which has a couple of search forms spread around the website. The craft standard search form works great, the only problem is I need to search only by the title field instead of all the content in the entries.

So my question is..

Is it possible to search only by title field?


texts: Do servers in a multi-server Craft setup need to share a storage directory?

texts:
We have a multi-server Craft setup, for redundancy and scaling.

We've been using an shared NFS drive to to host Craft's storage directory, by setting CRAFT_STORAGE_PATH to a mounted /craft-data/ directory on each machine.

in public/index.php:

define('CRAFT_STORAGE_PATH', '/craft-data/');

One reason it was important to do this was to let Craft share sessions across machines, because they were stored on the filesystem.

Recently, we transitioned from saving our sessions in the filesystem to saving them in redis.

If we can, I'd like to abandon the NFS drive altogether and let each machine have its own /craft-data/ directory, since we no longer need to maintain this shared filesystem for session sharing.

Looking at the contents of the craft /runtime/ directory, we see several subdirectories that seem like they could contain important shared state, such as cache and state:

$ pwd && ls -l
/craft-data/runtime
total 16
drwxrwxr-x   5 craft_user users   45 Jan 19 16:12 assets
drwxrwxr-x   2 craft_user users   49 Jan 26 09:34 cache
drwxrwxr-x 100 craft_user users 4096 Jan 26 09:37 compiled_templates
drwxr-xr-x   2 craft_user users   65 Jan 25 12:12 CSS
drwxr-xr-x   2 craft_user users   65 Jan 25 12:00 HTML
drwxrwxr-x   2 craft_user users 4096 Jan 19 16:12 logs
drwxrwxr-x   2 craft_user users 4096 Jan 26 08:52 sessions
drwxrwxr-x   2 craft_user users   22 Nov 16 14:55 state
drwxrwxr-x   2 craft_user users 4096 Jan 25 15:17 temp
drwxr-xr-x   2 craft_user users   65 Dec 14 11:27 URI

Do any of these directories need to be shared, in a multi-server setup? Is it safe for us to stop using a networked filesystem, for the CRAFT_STORAGE_PATH?


texts: Craft Commerce 2: Adding subscriptions to cart

texts:
I am porting a Shopify "multi-site" to CraftCMS using Commerce and I need to be able to add subscriptions to the shopping cart (customers can subscribe to a monthly box), together with other products.
Ideally I would have the subscription as a payment variant of a given product, so I can offer the same product for a reduced price if a customer subscribes to it.
(Single box vs. Monthly box)

Has anyone implemented something similar? Any hint or advise on how you'd go for this?

Edit, just for this question viewers's information:


texts: Show only products in stock - one variant only

texts:
In Craft Commerce, how can I show only products that are in stock when not using variants?

For example, this query, but only show products with a stock with 1 or more:

{% set productQuery = craft.products()
        .relatedTo(block.relation)
        .availableForPurchase()
        .order('postDate desc')
        .limit(4) %}

    {% set products = productQuery.all() %}

    {% for product in products %}
      {% include "_components/product-blurb.html" %}
    {% endfor %}


texts:
With Sprout Forms is it possible to return an error message if a form submission is bouncing back because unique values are expected?

For example, if I have a custom HTML form called signup I would expect it to throw back an object called signup but signup is not defined. Also tried form.getErrors() but this also returns empty.

Sample form code:

<form class="form form--signup" method="post">

    {{ getCsrfInput() }}
    {% set form = craft.sproutForms.form('signup') %}

    <input type="hidden" name="action" value="sproutForms/entries/saveEntry">
    <input type="hidden" name="handle" value="{{ form.handle }}">
    <input type="hidden" name="redirect" value="{{ craft.request.url }}#newsletter">

    <input type="email" name="fields[email]" id="ft_email" placeholder="Email address" class="form__input" required>
    <button type="submit" class="button btn btn--box btn--send">Send </button>
</form>


texts: Entry Pagination - Group by Current Category and Order by Post Date

texts:
I'm new to Craft and am trying to have our entry pagination (next/prev) links go to the next entry within that same category, ordering by date.

So the order part is working as I want it to, it's just remaining in the current category I need help with. Thanks!

Here's what I have so far...

{% set title = entry.title %}
{% set description = entry.body | striptags %}

{% extends "_layout" %}

{% block content %}

{% set entryCategories = entry.newsCategories %}

{% set thisCategory = '' %}

{% for category in entryCategories %}

{% set thisCategory = category.url %}

{% endfor %}

{{ newsHeader.header }}

All
{% nav category in     craft.categories.group('newsCategories') %}{% if category.url == thisCategory %}
{{ category.title }}
{% else %}
{{ category.title }}
{% endif %}{% endnav %}

            All

All

                {% nav category in craft.categories.group('newsCategories') %}

{{ category.title }}

                {% endnav %}

{{ entry.title }}

{{ entry.postDate|date("F j, Y") }} &nbsp;|&nbsp;

              {% if entryCategories | length %}

              {% for category in entryCategories %}

                {{ category.title }}

              {% endfor %}
              {% endif %}

{{ entry.body }}

                {# Set parameters for prev/next elements list #}
                {% set params = {section: 'news', category: category.title, order: 'postDate'} %}

                {# Get the prev/next elements #}
                {% set prevEntry = entry.getPrev(params) %}
                {% set nextEntry = entry.getNext(params) %}

                {# And make sure to only output the links if the element exists #}
                {% if prevEntry %}Previous{% endif %}
                {% if nextEntry %}Next{% endif %}

{% endblock %}


texts: How can you retrieve entries with a specific locale in a plugin?

texts:
I have this:

$this->requireAjaxRequest();

$segments = craft()->request->getActionSegments();

$lang = $segments[2];

$entryId = $segments[3];

$entry = craft()->entries->getEntryById( $entryId );

$response = array(
    'titre' => $entry->typeChambre,
    'etage' => $entry->etage->label,
    'surface' => $entry->surface,
    'loyer' => $entry->loyer,
    'charges' => $entry->charges,
    'description' => $entry->description,
    'photos' => $entry->photosChambre
);

$this->returnJson($response);

Thanks


texts: entry.getAuthor().getGroups() always return empty array

texts:
I'm trying to output users groups for every entries in a for loop, but it returns an empty array:

{%for entry in craft.entries.section('news') %}
    ...
    {{ dump(entry.getAuthor().getGroups()) }}
{% endfor %}

But it's working correctly in the entry page itself.

Any idea how I can return the groups in a for loop?


texts: Fetch entries with special characters in title

texts:
When trying to fetch an entry with special characters in the title, it doesn't seem to match.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->title = "Title,with,commas";
$entry = $criteria->first();

I've also tried a few other characters such as #, %, and $ with the same result - $entry is empty.


texts: Adding Product Variant and Related Product to the cart together on Craft Commerce 2

texts:
I want to add a product variant as well as a related product (chosen from a select list) together when the user clicks the add to cart button.

I can see you can add multiple products together with Commerce 2.
But I am stuck as to where to start with this. Can anyone point me in the right direction. here is some of my starting code:

<form method="POST">
  <input type="hidden" name="action" value="commerce/cart/update-cart">
  {{ redirectInput('shop/cart') }}
  <input type="hidden" name="qty" value="1">
  {{ csrfInput() }}

    <select name="purchasableId">
      {% for purchasable in product.variants %}
        <option {% if purchasable.stock
                  <= 0 and purchasable.hasUnlimitedStock == false %}disabled {% endif %}
                value="{{ purchasable.id }}"
        >{{ purchasable.sku }} {{ purchasable.description }} {{ purchasable.price|commerceCurrency(cart.currency) }}</option>
      {% endfor %}
    </select>

    <select name="purchasableId">
      <option value="">No Bolts</option>
      {% for product in product.fixingAddOn %}
        {% for purchasable in product.variants %}
          <option
            value="{{ purchasable.id }}"
          >
            {{ purchasable.id }} - {{ purchasable.price|commerceCurrency(cart.currency) }}
            {{ product.title }}
          </option>
        {% endfor %}
      {% endfor %}
    </select>

  {% for variant in product.variants %}
    <input type="hidden" name="purchasables[{{ loop.index }}][id]" value="{{ variant.id }}">
    <input type="hidden" name="purchasables[{{ loop.index }}][qty]" value="1">
    <input type="hidden" name="purchasables[{{ loop.index }}][note]" value="1">
  {% endfor %}

    Qty
    <input type="number" id="qty" name="qty" min="1" class="qty" placeholder="Qty" value="1" />

    <input type="submit" value="{{ " Add to cart"|t }}" class="button" />

</form>

EDIT
I have the following now working but would there be a better approach to this?

<form method="POST">
  <input type="hidden" name="action" value="commerce/cart/update-cart">
  {{ redirectInput('shop/cart') }}
  <input type="hidden" name="qty" value="1">
  {{ csrfInput() }}

    <select name="purchasables[1][id]">
      {% for purchasable in product.variants %}
        <option {% if purchasable.stock
                  <= 0 and purchasable.hasUnlimitedStock == false %}disabled {% endif %}
                value="{{ purchasable.id }}"
        >{{ purchasable.sku }} {{ purchasable.description }} {{ purchasable.price|commerceCurrency(cart.currency) }}</option>
      {% endfor %}
    </select>

    <select name="purchasables[2][id]">
      <option value="">No Bolts</option>
      {% for product in addOns %}
        {% for purchasable in product.variants %}
          <option
            value="{{ purchasable.id }}"
          >
            {{ purchasable.id }} - {{ purchasable.price|commerceCurrency(cart.currency) }}
            {{ product.title }}
          </option>
        {% endfor %}
      {% endfor %}
    </select>

    Qty
    <input type="number" id="qty" name="qty" min="1" class="qty" placeholder="Qty" value="1" />

    <input type="submit" value="{{ " Add to cart"|t }}" class="button" />

</form>


texts:
I'm trying to update from 2.3.2640 to 2.3.2644, but I get a 500 error

Internal Server Error
The server encountered an internal error or
misconfiguration and was unable to complete
your request.
Please contact the server administrator,
you@example.com and inform them of the time the error occurred,
and anything you might have done that may have
caused the error.
More information about this error may be available
in the server error log.

When I look a the logs I can see that the backup was successful

2015/05/20 13:23:15 [info] [application] [Forced] Finished backing up database.
in /xxx/craft/app/services/UpdatesService.php (399)
in /xxx/craft/app/controllers/UpdateController.php (317)
in /xxx/craft/app/etc/web/WebApp.php (869)

And the sql file is in the backup folder.

Any idea where I might look to fix this error?

EDIT: I see that it's timing out at 30 seconds. I've set my php file to have max_execution_time = 60, but it's still timing out at 30 seconds...


texts: Hooking into event when record deleted from custom plugin

texts:
We are using a plugin that has created its own record for storing private messages. When deleting a message, it's calling the delete() method on an instance of the record, which appears to be using the CActiveRecord's implementation of delete.

In CActiveRecord::delete(), it has a $this->afterDelete() method, which looks like it should be raising an onAfterDelete event, but I haven't had any luck hooking into it.

I've tried craft()->on('pluginhandle_messageRecord.onAfterDelete', ...) and craft()->on('cActiveRecord.onAfterDelete', ...), but neither gets triggered.

Does anyone know the correct syntax for hooking into this event for this specific custom record?

Thanks!


texts:
I am trying to create a site that offers courses.  Each course will be broken up into sections with each sections containing a number of lessons.  Viewers will then be able to progress through the course one lesson at a time - at their own pace (like Lynda.com).

  Note: the sections are merely there for organizational purposes - they don't actually house any content.  All the actual content is
  limited to the Course page and the individual Lessons.

I am trying to figure out the best way to organize this. This is my current thinking (but I'm not sure this is the best way to do it).

Section & Entry Types

I have created a Structure Section called Courses with two Entry Types:

Course
Lesson

I have then set up a matrix field for the Course entry type with two field types:

Section Name:  Plain Text field type for the name of the section
Section Lessons: Entries field type set to Courses (for the list of lessons  in each section)

The idea being that on the course page I could quickly and easily create a number of sections and then add the relevant lessons to each section.  I can then set up the template to progress through each section and it's lessons in order.

With that said, I had two other ideas.

Set up three entry types - Course, Section & Lesson

I would then have the Course be the parents of the various Sections and the Sections be the parents of the various Lessons.

This also seems fairly easy to do (the only problem is creating an entry for each section given that the Sections don't actually house any content).

Set up categories for each course

I could then assign each lesson to a category (I would then have to figure out how to order the content).

Any suggestions as to which is the best way to proceed?

Thanks.


texts:
I moved my website from local to an online test server via git.

Everything works fine, except that I can


texts: Entry Form: Populate checkbox list from another entry and save options in entry

texts:
I am trying to load some options in to a checkbox list from another entry so that a user and save select them form a checkbox list but I am unable to save the Entry Form with their selection.

I have created the registeredOccurances checkbox field in the Section, it has no options set as I want to set them on the entry form.

<input type="hidden" name="fields[registeredOccurances]" value="">
    {# Load rows from SuperTable in to checkbox list #}
    {% for block in entry[dateFieldHandle] %}
        <input type="checkbox" value="{{ loop.index }}" name="fields[registeredOccurances][]"> {{ block.date }}
    {% endfor %}

    {% if entry is defined %}

{{ dump(entry.getErrors()) }}

    {% endif %}

The dump is outputting the below, can someone help to interpret it?

array(1) { ["registeredOccurances"]=> array(1) { [0]=> string(33) "Registered Occurances is invalid." } }

Thanks for your help :)


texts: Path issue when developing locally - /web/ folder

texts:
I'm building a Craft site locally and I'm unsure how to handle a path issue that will occur when the site goes live.
My understanding is that in a live implementation, the /web/ folder will become the root folder.  In twig templates, I can exclude /web/ from paths by using {{ siteURL }}, i.e. {{ siteURL }}images/.
However, you can't use Twig when adding page content through Redactor.  So if I want to include an image with the page text, I have to use "/web/" in the path.  When the site goes live, those paths will be broken since the /web/ folder will become the root.
How can I resolve this without having to change all the links to remove /web/ once the site is live? I feel like there must be a configuration file or setting somewhere I can change, but I haven't been able to find one.


texts: Flexible content requirements for Matrix

texts:
I’m attempting to setup a site with only a couple of templates and having a LOT of Matrix fields so the client can build content out of component based content, making it super flexible (hopefully).

I'm using Matrix Table Field Types for various items but what I really need to do is have the ability to have other types of content within the Table, other than just 'single-line text', 'multi-line text', 'number' or 'checkbox'.

Does anyone know any way to do this or of there are maybe any plugins which would solve this issue?


texts:
I'm following the documentation to create a thank-you page when the user submits the form.

I have a single created for /contact-us/ and I want the user to be redirected to /contact-us/thank-you/ when they submit the form.

I have created the route so contact-us/thank-you shows the contact-us template, but when I go to that URL I get a template error saying Variable "entry" does not exist.

So it looks like it's showing the template correctly, but not loading the data from the single.


texts: What is the easiest way to include bootstrap in Craft?

texts: How is the easiest way to include bootstrap to Craft? I've seen there's already a bootstrap.php in the "app" folder... what can I do with this guy?


texts:
I'm trying to conditionally display a Sprout Forms field based on multiple drop downs. The first sets the category and displays one of the other three drop downs with it's sub-categories.
The field should be displayed when the selected category, and it's sub-category are set, except when one specific sub-category is selected.
The problem is that when that sub-category is selected, then the parent category is changed, the hidden field's value still hides the field. If the and/or operators could be changed I think I could pull it off with a display condition for each sub-category. Something like (a1 and a2 and a3) or (b1 and b2) or (c1 and c2) conditions.
I've tried breaking it up into separate rules, but I haven't figured out how to set the precedence of the conflicting rules. They seem to enforce their failure criteria as well as success.


texts: Cannot go to site URL while logged in without index in URL

texts:
For some reason I can no longer go to my default site URL while I am logged in.

Going to http://localhost:3001/craft-site/web/ gives me the following message in Chrome:

  ERR_TOO_MANY_REDIRECTS

Trying to refresh the site gives me this strange error message from Craft:

  HTTP 404 – Not Found – yii\web\NotFoundHttpException

  Template not found: $DEFAULT_SITE_URL/$DEFAULT_SITE_URL

I can still go to http://localhost:3001/craft-site/web/index while logged in and it works fine. The most interesting thing is that the file index.twig is completely empty.


texts: Craft Commerce price lists with discounts

texts:
I have configured several discounts based on usergroup conditions in Craft Commerce. Now i would like to create a price list for the shop owner, that contains the prices for the several usergroups. Below is a (try...) code example on how it should work. Is such a price list possible with Craft Commerce? How can i get this?

    {% set products = craft.commerce.products.type('normal').find() %}

    {% for product in products %}
      {% for variant in product.variants %}
        {{ variant.sku }} - {{ variant.salePrice|forUsergroup("normal") }} -  {{ variant.salePrice|forUsergroup("silver") }} - {{ variant.salePrice|forUsergroup("gold") }} <br>
      {% endfor %}
    {% endfor %}


texts: Rendering a template from a controller - unable to find template

texts:
Once again going out of my mind trying to figure something out...
I have a custom controller which I want to return a rendered template. The template should, ideally, reside in my front end templates directory.
But I can't for the life of me figure out the path to use.
The template I want is at ./templates/how-to-book/holidays-for-destination-options.twig but my controller is unable to find it seemingly regardless of how I try to write the path.
This is a sketchy version of the controller (I'm not getting any data yet, just want to render the correct template)
public function actionLoadHolidays()
    {
        $request = Craft::$app->request;
        $destination = $request->post('destination');

        $holidays = [];

        $oldMode = Craft::$app->view->getTemplateMode();
        Craft::$app->getView()->setTemplateMode(View::TEMPLATE_MODE_SITE);

        $this->renderTemplate('how-to-book/holidays-for-destination-options.twig', array(
            'destination' => $destination,
            'holidays' => $holidays
        ));
        Craft::$app->view->setTemplateMode($oldMode);

    }

Using the path as shown, I get the response Not Found: Template not found: actions/my-module/holidays/load-holidays
I'm hitting this controller via an Ajax request if that has any bearing.
Can someone please help me figure this out - I'm feeling dumb!


texts: Whitespace created when using if statements

texts:
I am using the following block of code in a template:

{% if entry.features | length %}

Features

        {% for block in entry.features %}

 {{ block.feature }}

        {% endfor %}

{% endif %}

The if statement is adding whitespace to the markup which causes styling issues.

How can I correct this? Do I need to format the code block differently?


texts: Is it Possible to Use Live Preview with Global Settings

texts: I know that out of the box one cannot use Live Preview with Global Settings.  I am wondering if it is possible to write a plugin or in some other manner get Live Preview to work with Global Settings.


texts: What's the right way to create a simple blog in Craft?

texts:
Should I create a Single for the blog home page content (/blog) and then a Channel to hold the entries (/blog/{slug})?

The blog index page also needs to have non blog entries on, i.e. intro text describing what the blog is about.


texts: Render styled output using Printmaker plugin

texts:
I have managed to get Printmaker up & running, spitting out images, entry data, tags etc. However I cannot style the output.

I have built up a template which has a html structure and links to an internal (same domain) CSS file. However the outputted style is browser-default sans serif text and no styling whatsoever.

Here is my template code:

        <link rel="stylesheet" href="/css/templates.css">

              // Page content here...

I have tried the .pdfFromTemplate method:

{% set vars = {
    entry: entry
} %}
{% set settings = {
    orientation : 'portrait',
    filename: entry.slug,
    cacheDirectory: 'pdf/' ~ craft.request.getSegment(1) ~ '/' ~ craft.request.getSegment(2)
} %}
{% set pdfUrl = craft.printmaker.pdfFromTemplate('technical-information/_pdf', vars, settings).url %}

And also the .pdfFromHtml way, too:

{% set html %}
    {{ include('technical-information/_pdf') }}
{% endset %}
{% set settings = {
    orientation : 'portrait',
    filename: entry.slug,
    cacheDirectory: 'pdf/' ~ craft.request.getSegment(1) ~ '/' ~ craft.request.getSegment(2)
} %}
{% set pdfUrl = craft.printmaker.pdfFromHtml(html, settings).url %}


texts:
I am using Craft Commerce v2 plugin with Craft CMS v3 with one of my site which basically sells kid products.

It's a subscription website and ones some parent subscribe for any kids package, they will charge for a month ( recurring every month ) and then we will send kids package every week for that month.

I am not sure if Craft Commerce is able to handle recurring payments and subscription / membership thing.

Can anyone help me out, what's the possible and best solution for this.


texts: What is the best approach for multi categories filtering

texts:
I need a solution for a good filter approach in Craft.

I used 3 Categories related to an entry (Project). The 3 Categories are
(Type / State / Location)
How do I have to set up the routes for the multiple slugs?

Example:

example.com/project/office/finished/germany.

I already fetch projects with AJAX for one category, but it should also work with a combination of categories.


texts: How do I set a class if entry is a child of a particular parent?

texts:
I have a structure section which is three levels deep and I want to add a class when the entry has a parent id of X. I am trying something like:

{% for entry in craft.entries.section('brand').descendantOf(entry.id).level(3) %}

  ...

{% endfor %}

This gives me a "Recoverable error":

  Argument 1 passed to Craft\BaseElementModel::isAncestorOf() must be an
  instance of Craft\BaseElementModel, string given

What am I doing wrong?

Updated code:

{% for entry in craft.entries.section('brand').descendantOf(entry.id).level(3) %}
{% set entryWithId13 = craft.entries.id(13).first() %}
{% set entryWithId23 = craft.entries.id(23).first() %}
{% set entryWithId23 = craft.entries.id(29).first() %}

...

{% endfor %}


texts: List products related to currently active category (url)

texts:
My URL:
http://localhost/product-family/compressors

How can I list the related products?
I don't understand how to get access to the compressors (a category entry of the product-family category type). The product-family is a structure - so there may be many levels.

(I thought I'd have access to the currently selected category via entry but I get error when I try to access it.)


texts: Restict admin user permissions to only editing users he/she has created.

texts:
I'm thinking about building an app with Craft that requires users from a specific user group (Business User Usergroup) to be able to log in on the frontend and add users from another user group (Client Usergroup) from the frontend, these users would be their clients and they would be able to view information set by the admin aswell as upload certain documents that they admin can then view.

// If anyone is interested the application will be a portal where coaches/therapists can register, log in and become a user( of the business user Usergroup) and can then add their clients as users (Client Usergroup) and then they can communicate digitally before meeting. Obviously, i don't want therapists to be able to see clients that don't belong to them. For this, i need to restrict user permissions as to make sure that the therapist can only see and edit users/clients that belong to him.

What i cant seem to figure out is if there is a way either with Craft or a plugin that makes sure that the admin cannot edit/see users added by other users in their user group. This means that if a user/coach from the Business Usergroup logs in and adds a client/user (from the Client Usergroup) only he/she, all super users and the client he added can login, view and edit these account details.

Has anyone come across a plugin or have experience with this type of "user-specific" bound user permission? If the explanation is too vague or unclear then i would be happy to explain in more detail. Hope someone can help with this and thanks in advance!


texts: Is caching the layout wrapper template a viable option?

texts:
I've been thinking about creating the simplest possible cache solution and would like to know if this is a worthwhile option.

Using the outstanding cacheflag plugin, I place the entire layout wrapper template inside these tags:

{% cacheflag flagged "content" globally using key craft.request.path %}
 ... lots o code....
{% endcacheflag %}

In the back end, I flag each of the section with a "content" flag.

I think by doing this, each url should have it's own cache file. And all caches are cleared whenever a new entry is posted.

Granted it may a bit of a sledgehammer style solution, but if traffic is average it could perhaps be effective?

Is my understanding correct or is this a bad idea?


texts: {% requireLogin %} not working on extended (layout template) files?

texts:
Is there a reason {% requireLogin %} is not firing when using in a parent include?
if I place {% requireLogin %} inside the main template file and then use this like so:
homework.twig
{% extends "_layouts/members-page-layout.twig" %}
It is not firing? But if I put it inside the homework.twig file directly it fires....
Was hoping t avoid having to add it to multiple templates and just add it to a 'members' parent layout template.
EDIT 18 July 2020
Editing the post to include more information
Here is the parent template I am trying to include the {% requireLogin %} that is not firing.
{# -- Layout template for HTML pages -- #}
{% extends "_boilerplate/_layouts/base-html-layout.twig" %}

{# -- Any <meta> tags that should be included in the  #}
{% block headMeta %}
{% endblock headMeta %}

{# -- Any <link> tags that should be included in the  #}
{% block headLinks %}
{% endblock headLinks %}

{# -- Any CSS that should be included before  -- #}
{% block headCss %}
  {# Google fonts #}
  <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700&display=swap" rel="stylesheet">

  {% include "_inline-css/site-fonts.css" %}
{% endblock headCss %}

{% requireLogin %}

{# -- Page body -- #}
{% block bodyHtml %}
  {% set primarySectionColor      = 'navy' %}
  {% set secondarySectionColor    = 'pink' %}

  {% if currentUser.admin %}
    {#    TODO: Make this hide#}

          {{ svg('@icons/bx/bx-info-circle.svg', class="w-5 h-5 flex-shrink-0 fill-current mr-1") }}
          You are currently logged in as an admin role so you have unrestricted access and therefore you will not see the filtering of content and homework like a member user
          (parent) would see.

        <button class="bg-green-500 text-white p-2">
          {{ svg('@icons/bx/bx-info-circle.svg', class="w-8 h-8 flex-shrink-0 fill-current") }}
        </button>

  {% endif %}

    {# -- Info header, including _navbar.twig -- #}
    {% include "_globals/header.twig" %}

    {# - IE notice for Old browsers - #}
    {% include '_globals/ie-notice.twig' %}

      {# -- Primary content block -- #}
      {% block content %}
      {% endblock %}

    {# -- Content that appears below the primary content block -- #}
    {% block subcontent %}
    {% endblock %}

    {# -- Info footer -- #}
    {% include "_globals/footer.twig" %}

{% endblock bodyHtml %}


texts: Bizarre admin menu problem after upgrading craft to latest version

texts:
Hi not sure if anyone has come across this issue before? I upgraded craft to the latest version on my test site. I have a few custom plugins that I have created on this site. The front-end seems to be working Ok. However I have a strange thing happening in the admin. The settings menu item is re-directing to one of my plugins?? So I can't access the settings at all. The menu link is showing as admin/settings and there are no routes set in either the routes.php config file or anything in the .htaccess.

Anyone any thoughts?


texts: Get entries based on custom field lightswitch in custom plugin in Craft 2

texts:
I am trying to get the entries in my custom plugin template ( CP )

Each entry has a lightswitch I want to fetch only those where lightswitch is enabled.

In controller file:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section('articles');
$criteria->relatedTo(array(
    'field' => 'lightswitchFieldHandle'
));
$criteria->limit = 20;
$products['entries'] = $criteria->find();
$this->renderTemplate('sponsoredentries/_index', $products);

But I am getting 20 entries (as per limit but not as per field)


texts: How to query with relatedTo of a Relationship Field in a Matrix Field block

texts:
I have structures called Instrument and Person. On the person structure, I have a Matrix field called Roles. Roles has a block called Musician. And That block type has a Relationship Field called Instrument.

This allows someone to be a musician and to be assigned an instrument.

In my template I need to output each Instrument as a section, and all of the musicians that play that instrument.

I think this issue has something to do with the relationship being added in a Matrix block rather than on the entry itself.

Unfortunately there are many roles (block types) that a person can have, each with different fields. I tried to solve this by swapping to Instruments as categories but that doesn't seem to be working either. Here's some sample code I've been playing with:

        {% for instrument in craft.entries.section('instrument') %}

{{ instrument.instrumentName }}

          {% for person in craft.entries.section('person').relatedTo( instrument ) %}

{{ person.personName }}

          {% endfor %}
        {% endfor %}


texts: Entries related to an entry in a list of entries

texts:
I try go get entries (of channel B) related to an entry (of channel A) within a list of entries (of channel A). All entries of channel B have a relationship field and at least one relation to an entry in channel A. But I get no results from channel B.

{% set entries = craft.entries.section('candidates').order('postDate asc') %}
{% for entry in entries %}
    {% set feedbacks = craft.entries.section('candidates_feedbacks').relatedTo(entry.id) %}
    {{ entry.title }}
    {% for feedback in feedbacks %}
        {{ feedback.title }}
    {% endfor %}
{% endfor %}

What am I doing wrong?

Thank you very much for your feedback.


texts: How to Check All Users against UserGroup

texts: How can i check if ANY users exist in a particular User Group? I know how to check the current user but not ALL users.


texts: Creating entries loop with nth loops across unordered lists

texts:
I'm looking for some help with the most efficient and performant way to generate this loop.

| COL 1 | COL 2 | COL 3 |
|   1   |   2   |   3   |
|   4   |   5   |   6   |
|   7   |   8   |   9   |
|   10  |   11  |   12  |

Columns here are unordered lists and I want to ordered by postDate going across each column. It needs to be done this way as specific to the design of the page.

I've tried batch, slice , loop indexes and experimented with range. Tried 3 different craft.entries loops to generate the columns.

What I would really need if it existed was offset and nth if nth didn't terminate.

I'm guessing answer will be something like creating these arrays outside of final entries loop and passing in IDs?


texts:
How to do image processing & transformations when not using templates?

I'm using react-static for the frontend.

Is it possible to have CraftCMS process the images upon upload?


texts: Is it possible to set a list of asset (images) based on their width? So i just want a list of images that are wider than 1000px for example... Without having to check in a for loop. So on the end of - craft.assets for example.


texts: entry edit no other content area unless title?

texts:
I am a newbie of Craft CMS. I installed it on my localhost.

I added a few sections and fields to test it when I go to Entries, create and edit the entry, there is just a title input area?

Is that normal?

Or I need to add code in the backend files? I did not find a way to add it from the online documents.

thanks.


texts: Pathed URL creation from templated files

texts:
I've encounterd a problem with URL creation.

In my plugin I have the following.

public function registerSiteRoutes() {
    return [
        'korting/zoeken' => array('action' => '/discount/discount/index'),
        'korting/(?P<id\d+>)-(?P<slug>[a-zA-Z0-9-]+)' => array('action' => 'discount/discount/view',),
    ];
}

Now when I'm at the frontend, I use the following to create the URL :

{{ url('/discount/discount/view',{id:entry.id,slug:entry.slug}) }}

My plugin gets its data from a solarium document, so its no entry.

I would expect that my URL would become neat like :

/korting/124-test-1

but instead I get :

/korting?id=124&slug=test-1

This feature is build in by default in the Yii URL manager, but Craft doesn't make use of it. This is resulting in my problem that Craft doesn't have the abbility to make pathed URLs.

Is there any other way for me to do this?


texts: Search for related entries via AJAX given multiple parameters

texts:
I am attempting to create a relationship between products.
I have a section named "product" which is a Structure. Each "product" entry has a category field called "species" and a category field called "category".

My "species" category is a nested category. For example:

Dogs
  |-- Dachshund
  |-- Chiwawa
Cats
  |-- Long Hair
  |-- Short Hair

My "category" category is a single list. For example:

Yellow
Green
Blue

I have a form that I am trying to filter back my entries based on which "species" and/or "category" is chosen from the drop-down menu(s).

I have the ajax part down - no problem. I am sending a request to a twig .json template, and I am always getting into my "No Results" condition.

Here is the twig syntax I'm using. I have to be close (hopefully)...

{% set species = craft.request.getParam('species') %} // returns "Dachshund"
{% set category = craft.request.getParam('category')  // returns "Yellow"

{% set products = craft.entries.section('product').relatedTo('or',
{ sourceElement: category, field: 'category' },
{ targetElement: species, field: 'species' }
) %}

{
    "results": [{
        {% if products|length %}
            "status": "OK",
            "products": [
                {% for product in products %}
                    {
                        "name": "{{ product.title }}"
                    } {% if not loop.last %},{% endif %}
                {% endfor %}
            ]
        {% else %}
            "status": "NO_RESULTS"
        {% endif %}
    }]
}

I have also been trying to follow this thread in SO to search for entries.

I know I need a conditional (this or that) since a user could choose a "species" but not a "category" so this article from the docs is where I need to be.

I have gotten results back, but then run into an error that a class can't be converted to a string. I assume that's because I don't have the syntax correct to dig down into the category group correctly.

Within my "product" entry, the "species" category field looks like this:

Dogs
  |--Dachshund

I am also 100% confident the ElementAPI would be extremely helpful, I just haven't figured out how to incorporate it.

EDIT

Here is my updated products.json file that I am submitting the form to. I still fall into the NO_RESULTS condition.

{% if craft.request.isAjax %}
{% set species = craft.request.getParam('species').first() %}
{% set category = craft.request.getParam('category').first() %}

{% set foo = craft.entries.section('product').species(species) %}
{% set bar = craft.entries.section('product').category(category) %}

{% set products = craft.entries.section('product').relatedTo('or',
    { sourceElement: foo, field: 'species' },
    { targetElement: bar, field: 'category' }
) %}

{
    "results": [{
        {% if products|length %}
            "status": "OK",
            "products": [
                {% for product in products %}
                  {
                    "name": "{{ product.title }}"
                  } {% if not loop.last %},{% endif %}
                {% endfor %}
            ]
        {% else %}
            "status": "NO_RESULTS"
        {% endif %}
    }]
}
{% endif %}


texts: How can I reference images in a rich text field?

texts:
I need to reference an image in a rich text field separately to the text.

So I can't just use {{entry.body}} I need to be able to do {{entry.body.image}} or something comparable.

How can I do something like this?

Hopefully my question makes sense, I am new to Craft.

Thanks!


texts: Searching multiple Super Table columns against an established value

texts:
I currently have three global Super Table fields, global.berkeleyDeliveryMatrix, global.oaklandDeliveryMatrix and global.sanFranciscoDeliveryMatrix, all of which have a plaintext column in them titled zipCode.

The user has a profile address saved, which I'm looking to check against on the userZip field.

How could I search against all three of the global fields and return either a true or false statement if the set zip code was matched against any of the rows in the globals?


texts: How to check an entry is in a section within a for loop

texts:
I need to display different information depending on the section the entry comes under when I'm displaying all entries within a loop.
Use case - I have a feed which will pull in all entries such as 'Projects' and 'Events' both are sections set up as channels.
I need to display different information relating to each Entry on the front end as they have different fields.
So I need to check if the entry belongs to 'projects' or 'events' within the loop. I can't seem to achieve it.
Current code:
{% for entry in craft.entries.authorId(authorIds).orderBy('dateCreated desc') %}

      {% if entry in craft.entries.section('projects') %}

      Do something

      {% elseif entry in craft.entries.section('events') %}

      Do something different

      {% endif %}

{% endfor %}

This displays nothing? Any help?
Thanks


texts: Add Tags to a Newly Created Entry With PHP in Craft 3

texts:
I am able to successfully create new entries with PHP when I am using basic field values that are Rich Text or Plain Text fields, but am unsure how to add Tags to an entry.

So my entry already has a field called 'tags' on it, and I thought that maybe it wanted an array of strings like so:

$entry->setFieldValues([
   'tags' => array('someCoolTag', 'tagasaurus rex')
]);

I admit I do not really understand how tags work behind the scenes, and would like to correct that. Any help is great.


texts: Showing Entries based on an Entries Field but also showing a slug in the url

texts:
I have a Channel 'Articles' with an Entries field which is linked to entries in 'Staff Members' channel.  This is so that articles can be assigned to different members of staff.

I have the generic listing (all articles) page working fine I just need to show the same page but filtered by a selected staff memeber. E.g. When viewing an individual article by a member of staff I would like to link to a page which only lists the articles assigned to that particular staff member.  This far would be ok but if possible I would also like to get the staff member name into the url... http://mysite/staff/joe-bloggs/articles

Any suggestions?

Many thanks


texts:
I need a simple plugin for approve access to an entry for specific users. Like this:

array with approved entries ids for the currentUser

  GetApprovedEntries(currentUser.id)

Approve entry for a user (from pending entry ids array)  and add to approvedEntries array and remove from pending array

  ApproveUserForEntry(user.id, entry.id)

get all approved users for a specific entry

  getApprovedUsers(entry.id)

Ask for entry access and add to pending array of the user

  AskEntryAccess(currentUser.id, entry.id)

How I do this (add an array to a user), i am not a plugin developer.


texts:
I'm experiencing weird cookie/redirect issues after logging in the admin/cp. Keeps redirecting to / (even on /) untill I've deleted my cookies.

Clean download/install, no errors occured. I have no idea what to check:

clean download of latest version 2.4.2700, no changes
different domain/hosting tested, still redirect occurs
different browsers tested, same results

Pulling my hair out here, any suggestions/ideas?

-- edit
It has to be a cookie/session related issue, but all paths are 'normal'. Using CentOS with cPanel, all up to date


texts:
I'm working on a site that has logins for members, but I'd like to have a page that shows all members with a name and picture.
To do this, we had to import an existing database that doesn't have a lot of profile pics. Now I want to hide all users that have no picture uploaded.

This is the code I'm trying, but with no luck...

{% if geslacht_param_string !=''  %}

{% set queryParams = {
    search: {
        query: geslacht_param_string,
        attribute: 'geslacht'
    },
    geboortedatum : dateRange,
    order :'lastName',
    photo : ':notempty:'
} %}

{% else %}
    {% set queryParams = {
        geboortedatum : dateRange,
        order :'lastName',
        photo : ":notempty:"
    } %}
{% endif %}

{% set leden = craft.users(queryParams) %}

I can't find the decent syntax for :notempty:, can anyone help me out here? Thanks a lot!


texts: Is it possible in a front end entry form to pass the URL of a file to an assets field and have it upload that way?  Specifically, I'm trying to move an image from one assets field & upload folder to another in an edit entry form.


texts:
I have an article called Main Article and I am rolling out the chapters each week (8x). So, each chapter will have the MAIN Article Title AND Chapter Title.
eg: Stories from the top of the World; The Journey of the arborists

Stories from the top of the World; The way to the top
etc, etc...

I could create the MAIN Article as a single entry (with an excerpt) but this is not the brief from the client and use a relationship field to add the chapters to the Main Article Title.

I could add the Main Article title as a category and select this at each chapter entry, but how do I create the URL format to do this? This might also be tough to explain as a workflow for the client....

articles/{category}/{slug}

What else are the options?


texts:
I have a section called stories and a section called news.

stories needs to have Russian translations

So i set up multisite and Russian language and fields as translation method - for each language

Great - I can view story entry in Russian with the URL prefixed as domain/ru/story

My problem is that I only want that content translated not the rest of the site URLs which by default seem to all inherit 'ru'.

I can for the purposes of this particular project just setup a Russian section for stories and do away with the whole Craft multi site language setup. But I like to keep things crafty if possible.

Is there a solution to using translations just for a section and leaving the rest of the site in English?


texts: Craft 3 Setup: Testing Database Credentials Failed

texts:
I receive the following error message: Testing database credentials... failed: SQLSTATE[HY000] [2002] No such file or directory and am not entirely too sure what I need to do to connect to this database.  I'm not sure if it's a MAMP error or a Craft setup error as well.

// ♥ ~/development/craft3local/install/craft setup
Which database driver are you using? [mysql,pgsql,?]: mysql
Database server name or IP address: [localhost] localhost
Database port: [3306] 8889
Database username: [root] root
Database password:
Database name: craft3local
Database table prefix:
Testing database credentials... failed: SQLSTATE[HY000] [2002] No such file or directory

I am using MAMP, not the Pro version.  My port is 8889 confirmed from the start page info and checking the ports section of the setup. I have also tried creating a different user for the database and it also did not work.

Many thanks for any assistance.


texts: WYSIWYG removes HTML button all non- tags when view source

texts:
Any code that I previously inserted using the html button on the rich text wysiwyg is removed when I click into edit the html within a post. Only <p> tags remain.

I have turned off the "Clean html" and the "Purify html" in the settings for the body field (rich text field), and have tried to enter iframes (videos).  I can insert them initially, but if I go back to the edit as rich text, and then click to edit the html, any iframes, divs or tags other than <p> tags are stripped out of the code.

I cannot edit html in any posts that have videos else the videos are stripped out.

I have also downloaded a fresh install of Craft to make sure that it wasn't just my install.  I encountered the same issue.

Can someone tell me what is going on?


texts: How can I prevent an account activation email from being sent to an unverified user who registered via a front end registration form?

texts:
I have a front end user registration form, and I want users to receive a set password email after they've been activated manually in the back end by an admin. When they submit the user registration form, their account shouldn't be automatically activated, so I've checked the "verify email addresses" option in the user settings. However, with this setting enabled, a new user automatically receives an email to activate their account. Is there a way to prevent this account activation email from being sent when the user is first created in the system?

If I can prevent the initial account activation email from being sent, I can add a trigger to a custom module that sends the set password email after the user is activated by an admin, like so:

    Event::on(
        Users::class,
        Users::EVENT_AFTER_ACTIVATE_USER,
        function (Event $event) {
            $users = Craft::$app->getUsers();
            $users->sendActivationEmail($event->user);
        }
    );

This would allow me to have the set password email sent at the appropriate time.

In short, how can I have a front end registered user receive a set password email only after their account has been activated manually by an admin?


texts: Suspended users who have never logged in

texts:
This may sound paradoxal but here it is.

Membership based site.

A new user starts as suspended.
An admin unsuspends.

The user uses the system.

If a membership expires, a user gets suspended again (in the cp).

I want (in the cp again, from a plugin) a list of of suspended users who have never logged in. New users basically...

craft.users.status('suspended').lastLoginDate(NULL)
craft.users.status('suspended').lastLoginDate('')

Neither of these work. Any light?

Doing this

craft.users.status('suspended')

Then this in the actual loop works

 {% if user.lastLoginDate is null %}

I just wonder why I can't just fetch it all in one go :)


texts: How can I find entries that link to a given entry?

texts:
I'm retiring a section of my website and want to remove all existing internal links to this section. Is there an existing way to find any links to each entry in that section?

These links are all in Redactor fields (eg. inserted via the toolbar), and these fields may have different names etc across multiple sections.

I've tried running a regex search across a Craft database dump, looking for a pattern of {entry:[0-9]+:url} which shows me all the places that link to other entries, but this alone only gives me the entry IDs so I'll have to write further code to look up those IDs and work out which ones are in the section I'm removing.

Is there an easier way to do this, or is it going to be a semi-manual job?