Szybkie posty

Jeżeli coś jest wartego uwagi a nie jest to materiał na pełnoprawnwgo posta na blogu to będę starać się to umieszczać w tym miejscu.

#ajax #apache #behat #bitbacket #bootstrap #composer #cookies #cqrs #css #css flex #ct8 #curl #docker #doctrine #edukacja #elasticsearch #enet #enp sla #filmy #firma #funkcje php #git #google #htaccess #html #inne #javascript #jedzenie #jquery #js/jquery #kawały #krypto #laravel #linux #oop #pdo #php #php wzorce narzędzia #phpmyadmin #phpspec #phpstan #phpstorm #phpunit #podcast #rabbit #redis #seo #soap #sql #symfony #szukanie po stringach w php #twig #virtual host #visual studio code #vue #wamp #windows #wino-nalewki #wyrazenia regularne #wzorce projektowe #xml #xxx #zdjecia #złote myśli
  • Szukasz po tagu: symfony
  • Ilość rekordów w bazie: 77

Czyste zapytanie

  public function test2(string $keyName, string $keyValue, int $lastStepNumber) {
        $status = ClientStatuses::TYPE_COMPLETED;

        $key = '{"' . $keyName . '" : "' . $keyValue . '"}';

        $createdAtCondition = (new \DateTime('now -30 days'))->format('Y-m-d');
        $sqlQuery = 'SELECT * FROM `multi_step_form_client_data` WHERE createdAt > :createdAt and stepNr = :stepNr and status = :status and JSON_CONTAINS(serializedData, :jsonKey)  order BY createdAt desc limit 1';
        $connection = $this->getEntityManager()->getConnection()->prepare($sqlQuery);
        $connection->bindParam(':stepNr', $lastStepNumber);
        $connection->bindParam(':status', $status);
        $connection->bindParam(':createdAt', $createdAtCondition);
        $connection->bindParam(':jsonKey', $key);
        $connection->execute();

        return $connection->fetch();
    }

Pojedynczy rezultat zapytania

$createdAtCondition = new \DateTime('now -30 days');
        $queryBuilder = $this->createQueryBuilder('cd')
        ->where('cd.createdAt > :createdAt')
        ->andWhere('cd.stepNr = :stepNr')
        ->andWhere("JSON_CONTAINS(cd.serializedData, :pesel, '$.pesel') = 1");

        //$queryBuilder->setParameter('pesel', ".$keyValue.");
        $queryBuilder->setParameter('createdAt', $createdAtCondition);
        $queryBuilder->setParameter('stepNr', $lastStepNumber);
        $queryBuilder->setParameter('pesel', '"'.$keyValue.'"');

        $queryBuilder->orderBy('cd.createdAt', 'DESC')->setMaxResults(1);
        
        return $queryBuilder->getQuery()->getSingleResult();

Symfony walidacja w osobnym obiekcie

https://sarvendev.com/2018/01/encja-byc-zawsze-poprawnym-obiektem/


Symfony join

public function test() {
        $query = $this->getEntityManager()->createQueryBuilder()
                ->select('s','su','rv')
                ->from(Project::class, 's')
                ->leftJoin('s.sub_projects', 'su')
                ->leftJoin('su.reports_validation', 'rv')

                ->getQuery()
        ;
        
        return $query->getResult();
    }

2/

/**
     * get sub projects
     * 
     * @param Project $project
     * 
     * @return array
     */
    public function getSubProjects(Project $project): array {
        $query = $this->getEntityManager()->createQueryBuilder()
                ->select('s.id', 's.name')
                ->from(SubProject::class, 's')
                ->where('s.project = :project')->setParameter('project', $project)
                ->getQuery()
        ;
        try {
            return $query->getResult();
        } catch (\Doctrine\ORM\NoResultException $e) {
            return [];
        }
    }

Absolutny url w twigu

<a href="{{ absolute_url(path('route_name', {'param' : value})) }}">A link</a>

<img src="{{ absolute_url(asset('bundle/myname/img/image.gif')) }}" alt="Title"/>

<img src="{{ absolute_url('my/absolute/path') }}" alt="Title"/>


Symfony 3 regeneracja encji w danym bundlu

php bin/console doctrine:generate:entities App/Recruitment

Symfony form query builder

<?php

namespace App\AccessBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Doctrine\ORM\EntityRepository;
use App\AccessBundle\Entity\Application;
use App\AccessBundle\Entity\Access;
use App\UserBundle\Entity\User;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;

class AccessType extends AbstractType {

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $departmentId = $options['departmentId'];

        $builder
                ->add('application', EntityType::class, ['class' => Application::class, 'choice_label' => 'name', 'required' => true])
                ->add('user', EntityType::class, ['class' => User::class, 'query_builder' => function (EntityRepository $er) use ($departmentId) {
                        return $er->createQueryBuilder('i')
                                ->where('i.department = :Department')->setParameter('Department', $departmentId)
                                ->orderBy('i.name', 'ASC')
                                ->addOrderBy('i.surname', 'ASC');
                    }, 'choice_label' => function (User $user) {
                        return $user->getName() . ' ' . $user->getSurname();
                    },
                    'multiple' => false, 'required' => true])
                ->add('description', TextareaType::class, ['required' => false, 'attr' => ['maxlength' => 255]])
                ->add('datetime_add', DateTimeType::class, ['required' => true, 'widget' => 'single_text'])
                ->add('datetime_block', DateTimeType::class, ['required' => false, 'widget' => 'single_text'])
                ->add('datetime_remove', DateTimeType::class, ['required' => false, 'widget' => 'single_text'])
                ->add('login', TextType::class, ['required' => true, 'attr' => ['maxlength' => 255]])
                ->add('submit', SubmitType::class)
                ->add('submitAndClose', SubmitType::class)
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults([
            'data_class' => Access::class,
            'departmentId' => null,
        ]);
    }

}

Usuwanie symfony

$query = $this->getEntityManager()->createQueryBuilder();
            $query->delete(Ip::class, 'ip')
                    ->where('ip.date BETWEEN :startDate AND :endDate')
                    ->setParameters([
                        'startDate' => $dateStart,
                        'endDate' => $dateEnd,
                    ])
                    ->andWhere('ip.wpisywacz_id = :wpisywacz_id')->setParameter('wpisywacz_id', $userName)
                    ->andWhere('ip.category_id = :category_id')->setParameter('category_id', $categoryId)
                    ->andWhere('ip.ip = :ip ORDER BY ip.id  ')->setParameter('ip', $ip)
                    //->>orderBy('ip.id', 'desc')
               
                    //->addOrderBy('ip.id','DESC')
                    //->addOrderBy('ip.id','desc')
                    ->setMaxResults(1);
            ;
            dump($query->getQuery()->getSQL());
            
            die;
            
            $query->getQuery()->execute();

Sub zapytanie symfony

 /**
    * get oldest client category by date import having clientsource
    * 
    * @param int $clientId
    * @param array $categories (values example ->  [ 159 => 182 , 160 => "182_167"] )
    * @param \DateTime $datetimeBegin
    * @param \DateTime $datetimeEnd
    * 
    * @return array|null
    */
   public function getOldestClientCategoryByDateImportDateOfEntryHavingClientSource(int $clientId, array $categories, \DateTime $datetimeBegin, \DateTime $datetimeEnd) {
        $query = $this->createQueryBuilder('kk')
                ->where('kk.client = :client')->setParameter('client', $clientId)
                ->andWhere('kk.client_source IS not NULL');

        $categoriesWhere = '';

        if (!empty($categories)) {
            foreach ($categories as $category) {
                if (is_integer($category)) {
                    $categoriesWhere .= ($categoriesWhere != '' ? ' or ' : '') . '( kk.kategorie_nadrzedna = \'' . $category . '\') ';
                } else {
                    $categoryPart = explode('_', $category);
                    if (count($categoryPart) == 2) {
                        $categoriesWhere .= ($categoriesWhere != '' ? ' or ' : '') . '( kk.kategorie_nadrzedna = \'' . $categoryPart[0] . '\' and kk.kategorie = \'' . $categoryPart[1] . '\') ';
                    }
                }
            }

            if ($categoriesWhere != '') {
                $query->andWhere($categoriesWhere);
            }
        }
        
        $query->andWhere('kk.data_wpisania >= :DatetimeBegin')->setParameter('DatetimeBegin', $datetimeBegin)
                ->andWhere('kk.data_wpisania <= :DatetimeEnd')->setParameter('DatetimeEnd', $datetimeEnd);

        $query->orderBy('kk.data_importu', 'asc')->setMaxResults(1);

        try {
            return $query->getQuery()->getOneOrNullResult();
        } catch (\Doctrine\ORM\NoResultException $ex) {
            return null;
        }
    }

Crud widoki

{% extends 'DMDashboardBundle::layout.html.twig' %}

{% set title = "Źródło klientów - lista" %}
{% set icon = "menu_sieciafiliacyjne_icon.png" %}
{% block title %}{{ title }} {{ parent() }}{% endblock %}
{% block code_header %}
{% endblock %}
{% block body %}
    <header>
        <div class="icon"><div class="img"><img src="{{ asset('bundles/dmdashboard/images/' ~ icon) }}" alt="{{ title }}"></div></div>
        <h1>{{ title }}</h1>
        <div class="btn-group">
            <a href="{{ path('dm_client_source_add') }}" class="btn btn-primary">Dodaj</a>
        </div>
    </header>
    {% include 'DMDashboardBundle::modules/alerts.html.twig' %}
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-3">
                <div class="row">
                    {{form_start(form)}}
                        <div class="col-md-6">
                            {{ form_label(form.name) }}
                            {{ form_widget(form.name) }}
                        </div>
                        <div class="col-md-6">
                            {{ form_label(form.submit) }}
                            {{ form_widget(form.submit) }}
                        </div>
                    {{form_end(form)}}
                </div>
            </div>
        </div>
    </div>
    {% if items|length == 0 %}
        <big><i>Brak pozycji</i></big>
    {% else %}
        Wyników: <strong>{{ itemsCount }}</strong>
        {% if items|length == 0 %}
            <big><i>Brak pozycji</i></big>
        {% else %}
            <table class="table table-striped table-list" style="width: 98%;">
                <theader>
                    <tr>
                        <th style="width: 5%;">ID</th>
                        <th style="width: 50%;">Nazwa</th>
                        <th style="width: 5%;">Akcje</th>
                    </tr>
                </theader>
                <tbody>
                    {% for item in items%}
                        <tr>
                            <td class="">
                                {{ item.id }}            
                            </td>
                            <td class="">
                                {{ item.name }}            
                            </td>
                            <td>
                                <a href="{{ path('dm_client_source_edit',{'item': item.id}) }}" class="btn btn-primary">Edytuj</a>
                                <a href="{{ path('dm_client_source_remove',{'item':item.id}) }}" class="btn btn-danger" onclick="return confirm('Napewno usunąc?');">Usuń</a>
                            </td>
                        </tr>
                    {% endfor %}

                </tbody>
            </table> 
        {% endif %}

        {% if paginationCount > 1 %}
            <div style="width: 100%; text-align:center; margin-bottom: 20px;">
                {% if paginationPage != 1 %}
                    <a href="javascript:void(0)" onclick="javascript:changePaginationStrona({{ paginationPage - 1}})" class="elem back">{{ '< poprzednia' }}</a>
                {% endif %}

                {% for i in 1..paginationCount %}
                    <a href="javascript:void(0)" onclick="javascript:changePaginationStrona({{ i }})" class="elem" {% if i == paginationPage %}style="color:#000; font-weight:bold; font-size: 16px;"{% endif %}>{{ i }}</a>
                {% endfor %}

                {% if paginationPage != paginationCount %}
                    <a href="javascript:void(0)" onclick="javascript:changePaginationStrona({{ paginationPage + 1}})" class="elem next">{{ 'nastepna >' }}</a>
                {% endif %}
            </div>
        {% endif %}

        <script type="text/javascript">
            function changePaginationStrona(newStr) {
                $('input#client_source_filter_paginationPage').val(newStr);
                $("form[name='client_source_filter']").submit();
            }
        </script>
    {% endif %}

{% endblock body %}

//add edit

{% extends 'DMDashboardBundle::layout.html.twig' %}

{% if mode == 'edit' %}
    {% set title = "Źródło klientów edycja" %}
{% else %}
    {% set title = "Źródło klientów dodaj nową pozycję" %}
{% endif %}

{% set icon = "menu_sieciafiliacyjne_icon.png" %}
{% block title %}{{ title }} {{ parent() }}{% endblock %}

{% block code_header %}
{% endblock %}

{% block body %}

    <header>
        <div class="icon"><div class="img"><img src="{{ asset('bundles/dmdashboard/images/' ~ icon) }}" alt="{{ title }}"></div></div>
        <h1>{{ title }}</h1>
        <div class="btn-group">
            <a href="{{ path('dm_client_source_add') }}" class="btn btn-primary">Dodaj</a>
        </div>
    </header>

    {% include 'DMDashboardBundle::modules/alerts.html.twig' %}

    <div class="container-fluid">
        <div class="row">
            <div class="col-md-6 col-md-offset-2">
                <div class="panel-group">
                    <div class="panel panel-default">
                        <div class="panel-heading"> <h4>{% if mode == 'add' %}Dodaj nowy{% endif %}{% if mode == 'edit' %}Edycja{% endif %}</h4></div>
                        <div class="panel-body body-form">
                            {{form_start(form)}}
                            {{form_end(form)}}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock body %}

//nowy

{% extends 'DMDashboardBundle::layout.html.twig' %}
{% block title %} {{ parent() }} - Automatyczne raporty walidacyjne - konfiguracja {% endblock %}
{% block code_header %}
    <style>
        .checkbox-container > div > label{
            width: 35%
        } 
        
        .checkbox-container .has-switch {
            width: 10%;
            margin-right: 1%;
        }
    </style>
{% endblock %}
{% block body %}
    <header>
        <div class="icon"><div class="img"><img src="{{ asset('bundles/dmdashboard/images/menu_kategorie_icon.png') }}" alt="Group"></div></div>
        <h1>Automatyczne raporty walidacyjne - dodawanie/edycja</h1>
        <a href="{{ path('dm_reportvalidation_auto_report_configuration')}}" class="btn btn-default btn-add">&laquo; Wstecz</a>
    </header>
    {% include 'DMDashboardBundle::modules/alerts.html.twig' %}
    
    {{ form_start(form) }}
    {{ form_errors(form) }}
    <div class="left">
        <div class="panel-group" id="ustawienia">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4 class="panel-title">
                        <a data-toggle="collapse" data-parent="#accordion" href="#Parametry">
                            Parametry
                        </a>
                    </h4>
                </div>
                <div id="Parametry" class="panel-collapse collapse in">
                    <div class="panel-body">
                        <div class="form_row">
                            {{ form_label(form.mailTitle) }}
                            {{ form_widget(form.mailTitle) }}
                        </div>
                        <div class="form_row">
                            {{ form_label(form.mailsToSend) }}
                            {{ form_widget(form.mailsToSend) }}
                        </div>
                        <div class="form_row">
                            {{ form_label(form.mailContent) }}
                            {{ form_widget(form.mailContent) }}
                        </div>
                        <div class="form_row">
                            {{ form_label(form.report_validation_report) }}
                            {{ form_widget(form.report_validation_report) }}
                        </div>
                        <div class="row">
                            <div class="col-sm-6 col-xs-12">
                                <div class="form_row">
                                    {{ form_label(form.dateRange) }}
                                    {{ form_widget(form.dateRange) }}
                                </div>
                            </div>
                            <div class="col-sm-6 col-xs-12">
                                <div class="form_row">
                                    {{ form_label(form.sendDay) }}
                                    {{ form_widget(form.sendDay) }}
                                </div>
                            </div>
                        </div>
                        <div class="form_row checkbox-container">
                            {{ form_label(form.celsToSend) }}
                            {{ form_widget(form.celsToSend) }}
                            <br>
                            <a class="btn btn-primary" id="cell" >Zaznacz wszystkie pola do wyświetlania</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="right">
        <div class="panel-group" id="ustawienia">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4 class="panel-title">
                        <a data-toggle="collapse" data-parent="#accordion" href="#Akcje">
                            Akcje
                        </a>
                    </h4>
                </div>
                <div id="Akcje" class="panel-collapse collapse in">
                    <div class="panel-body">

                        <div class="btn-group" style="float: right; width: 100%;">
                            <a class="btn btn-default btn-lg" style="width:40%;" href = "{{ path('dm_reportvalidation_auto_report_configuration') }}" >Anuluj</a>
                            {{ form_widget(form.submit,{'attr':{'style':'width:60%'}}) }} 
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
                        
    {{ form_end(form) }}
    <script type="text/javascript">
        $('#cell').click(function () {
            $('#auto_report_validation_configuration_celsToSend').find('input[type=checkbox]').trigger('click');
        });
    </script>
{% endblock body %}

Crud symfony

<?php

namespace DM\KlienciBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use DM\KlienciBundle\Entity\ClientSource;
use DM\KlienciBundle\Form\ClientSource\ClientSourceType;
use DM\KlienciBundle\Form\ClientSource\ClientSourceFilterType;

class ClientSourceController extends Controller {

    const TEMPLATE_PREFIX = 'DMKlienciBundle:ClientSource:';
    const ACTIVE_BUNDLE = 'klienci';
    const PAGINATION_PER_PAGE = 100;

    /**
     * Client Source list
     * 
     * @param Request $request
     * 
     * @return Response
     */
    public function indexAction(Request $request) {
        $em = $this->getDoctrine()->getManager();

        $paginationLimitPerPage = self::PAGINATION_PER_PAGE;
        // form data
        $data = [];
        $form = $this->createForm(ClientSourceFilterType::class, $data);
        $resetPaginationPage = false;

        if ($request->isMethod('POST')) {
            $form->bind($request);
            $data = $form->getData();

            if ($form->get('submit')->isClicked()) {
                $resetPaginationPage = true;
            }
        }

        $paginationPage = (!$resetPaginationPage && isset($data['paginationPage']) ? $data['paginationPage'] : 1);
        $itemsCount = $em->getRepository(ClientSource::class)->findByMultiParameters(true, $data, []);
        $items = $em->getRepository(ClientSource::class)->findByMultiParameters(false, $data, ['t.id' => 'DESC'], (($paginationPage - 1) * $paginationLimitPerPage), $paginationLimitPerPage);

        // return view
        return $this->render(self::TEMPLATE_PREFIX . 'list.html.twig', array(
                    'active_bundle' => self::ACTIVE_BUNDLE,
                    'form' => $form->createView(),
                    'items' => $items,
                    'itemsCount' => $itemsCount,
                    'paginationPage' => $paginationPage,
                    'paginationCount' => ceil($itemsCount / $paginationLimitPerPage),
        ));
    }

    /**
     * add new client source
     * 
     * @param Request $request
     * 
     * @return Response
     */
    public function addAction(Request $request) {
        return $this->addeditAction($request, 'add');
    }

    /**
     * edit client source
     * 
     * @param Request $request
     * @param IframeLink|null $item
     * 
     * @return Response
     */
    public function editAction(Request $request, ClientSource $item) {
        return $this->addeditAction($request, 'edit', $item);
    }

    /**
     * crud add/edit
     * 
     * @param Request $request
     * @param string $mode
     * @param IframeLink $clientSource
     * 
     * @return Resposne|Redirect
     */
    public function addeditAction(Request $request, $mode, ClientSource $clientSource = null) {
        $em = $this->getDoctrine()->getManager();
        //edit or add 
        if ($mode == 'add') {
            $clientSource = new ClientSource();
        } elseif ($mode == 'edit' && !$clientSource) {
            $this->addFlash('error', 'Wystąpił błąd, nie można znaleźć wybranej pozycji w systemie. Spróbuj ponownie.');
            return $this->redirectToRoute('dm_client_source_homepage');
        }

        $form = $this->createForm(ClientSourceType::class, $clientSource);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            try {
                $em->persist($clientSource);
                $em->flush();

                if ($mode == 'add') {
                    $this->addFlash('success', 'Klient został pomyślnie dodany.');
                } elseif ($mode == 'edit') {
                    $this->addFlash('success', 'Klient został pomyślnie zapisany.');
                }

                return $this->redirect($this->generateUrl('dm_client_source_homepage'));
            } catch (\Exception $ex) {
                $this->addFlash('error', 'Wystąpił błąd (ex: ' . $ex->getMessage() . ')');
            }
        }

        return $this->render(self::TEMPLATE_PREFIX . 'addEdit.html.twig', [
                    'active_bundle' => self::ACTIVE_BUNDLE,
                    'form' => $form->createView(),
                    'mode' => $mode,
        ]);
    }

    /**
     * remove client source
     * 
     * @param Request $request
     * @param ClientSource $item
     * 
     * @return redirect
     */
    public function removeAction(Request $request, ClientSource $item) {
        $em = $this->getDoctrine()->getManager();
        $session = $this->getRequest()->getSession();

        if (!$item) {
            $session->getFlashBag()->add('error', 'Nie znaleziono pozycji w systemie.');
            return $this->redirect($this->generateUrl('dm_client_source_homepage'));
        }

        $em->remove($item);
        $em->flush();
        $session->getFlashBag()->add('success', 'Klient został pomyślnie usunięty.');

        return $this->redirect($this->generateUrl('dm_client_source_homepage'));
    }

}

//repository

<?php

namespace DM\KlienciBundle\Repository;

use DM\KlienciBundle\Entity\ClientSource;

class ClientSourceRepository extends \Doctrine\ORM\EntityRepository {

    /**
     * find items by mylti parameters with pagination
     *
     * @param boolean $onlyCount - true if return only count
     * @param array $filter - data array with filter parameters
     * @param array $orderBy - order param (key is field, value is direction, defulat id DESC)
     * @param integer $offset - pagination offset
     * @param integer $limit - pagination limit
     * @param string $groupBy
     * 
     * @return array
     */
    public function findByMultiParameters($onlyCount, array $filter = [], array $orderBy = ['t.id' => 'DESC'], $offset = null, $limit = null, $groupBy = null) {
        $select = ($onlyCount ? 'COUNT(t.id)' . ($groupBy ? ', ' . $groupBy : '') : ($groupBy ? $groupBy : 't'));
        $query = $this->getEntityManager()->createQueryBuilder()
                ->from(ClientSource::class, 't')
                ->select($select)
        ;
        
        // name
        if (isset($filter['name']) && $filter['name'] != null) {
            $query->andWhere('t.name LIKE :name')->setParameter('name', '%'.$filter['name'].'%');
        }

        if ($groupBy) {
            $query = $query->groupBy($groupBy);
        }

        if (!empty($orderBy)) {
            foreach ($orderBy as $orderField => $orderDirection) {
                $query->addOrderBy($orderField, $orderDirection);
            }
        }

        if (!$onlyCount) {
            $query = $query->setFirstResult($offset)
                    ->setMaxResults($limit);
        }

        try {
            if ($onlyCount) {
                if ($groupBy) {
                    return $query->getQuery()->getResult();
                } else {
                    return $query->getQuery()->getSingleScalarResult();
                }
            } else {
                return $query->getQuery()->getResult();
            }
        } catch (\Doctrine\ORM\NoResultException $e) {
            if ($onlyCount) {
                return 0;
            } else {
                return array();
            }
        }
    }

}

Domyślna aktualna data dla pola datetime w symfony

//yaml

 two_step_last_auth:
            type: datetime
            nullable: true  
            options:
                default: CURRENT_TIMESTAMP

//adnotacje

@ORM\Column(name="creation_date", type="datetime", options={"default"="CURRENT_TIMESTAMP"})
 

Wyszukiwanie wielu pól w relacji many_to_many

SELECT c0_.id AS id_0, c0_.created AS created_1, c0_.affiliate_network AS affiliate_network_2, c0_.affiliate_account AS affiliate_account_3, c0_.description AS description_4, c0_.full_content AS full_content_5, c0_.tag_product AS tag_product_6 FROM campaign c0_ 
LEFT JOIN campaign_taggeneral c2_ ON c0_.id = c2_.campaign_id 
LEFT JOIN tag_general t1_ ON t1_.id = c2_.tag_general_id
WHERE t1_.id IN (?) 
AND c0_.created >= ? AND c0_.created <= ? ORDER BY c0_.created ASC

//symfony
$query->leftJoin('i.tagsGeneral', 'j')
->where('j.id in (:subCompanyId)')->setParameter("subCompanyId", $filterData->getFilterTagsGeneral());

Dostep do entity menagera w formie

<?php

namespace App\Utils\Campaign;

use App\Lib\CrudManager\Form\FilterDtoType as BaseFilterDtoType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use App\DTO\Campaign\CampaignFilterDTO;
use Symfony\Component\Form\CallbackTransformer;
use App\Repository\TagProduct\TagProductRepository;
use App\Domain\Tags\ProductTagsProvider;

class FilterType extends BaseFilterDtoType{
    const TRANSLATE_PREFIX = 'campaign.filter.';
    
    protected $productTagProvider;

    public function __construct(ProductTagsProvider $productTagProvider)
    {
        $this->productTagProvider = $productTagProvider;
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        parent::buildForm($builder, $options);
        /** @var \Doctrine\ORM\EntityManager $entityManager */
        $entityManager = $options['entity_manager'];
    }

    public function configureOptions(OptionsResolver $resolver) {
        //$resolver->setRequired('entity_manager');
        $resolver->setDefaults(array(
            'data_class' => CampaignFilterDTO::class,
            'csrf_protection' => false,
            'allow_extra_fields' => true,
            'entity_manager' => true,
        ));
    }

    public function getBlockPrefix() {
        return 'campaign_filter';
    }
}

Dodawanie walidacji podczas budowania forma

 ->add('field_name', 'integer', array(
     'label' => 'Your label here', 
     'data' => 0, // default value
     'precision' => 0, // disallow floats
     'constraints' => array(
         new Assert\NotBlank(), 
         new Assert\Type('integer'), 
         new Assert\Regex(array(
             'pattern' => '/^[0-9]\d*$/',
             'message' => 'Please use only positive numbers.'
             )
         ),
         new Assert\Length(array('max' => 2))
     )
 ))

symfony2 dodanie indexu

AdvancedVerifyFieldBundle\Entity\AdvancedVerifyField:
    type:  entity
    repositoryClass: MultiStepFormBundle\Repository\MultiStepFormClientData\MultiStepFormClientDataRepository
    table: advanced_verify_field
    id :
        transaction_id :
            type: uuid
            generator:
                strategy: CUSTOM
            customIdGenerator:
                class: Ramsey\Uuid\Doctrine\UuidGenerator
    fields:
        searchHash:
            type: string
            nullable: false
            length: 32
        code:
            type: string
            nullable: false
            length: 16
        createdAt :
            type: datetime
            nullable: false
        confirmedAt :
            type: datetime
            nullable: true
        type:
            type: smallint
            nullable: false
        value:
            type: string
            nullable: false
            length: 255
    indexes:
        search_index:
          columns: [ searchHash ]

            

Rozbudowany form w symfony

<?php

namespace AdvancedVerifyFieldBundle\Form\AdvancedVerifyFieldConfig;

use Symfony\Component\Form\AbstractType;

class AdvancedVerifyFieldConfigType extends AbstractType {

    // uchwyt do entity managera
    protected $em;

    public function __construct($em = null) {
        $this->em = $em;
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('name', TextType::class, array('label' => 'Nazwa:', 'required' => 'true', 'attr' => array('class' => 'form-control')))
                ->add('description', TextType::class, array('label' => 'Opis:', 'attr' => array('class' => 'form-control')))
                ->add('slug', TextType::class, array('label' => 'Slug:', 'required' => 'true', 'attr' => array('class' => 'form-control', 'id' => 'slug')))
                ->add('status', CheckboxType::class, array('attr' => array('class' => 'checkbox', 'data-toggle' => 'toggle')))
                ->add('defaultHeader', TextareaType::class, array('label' => 'Domyślny Header:', 'required' => false, 'attr' => array('class' => 'form-control')))
                ->add('defaultFooter', TextareaType::class, array('label' => 'Domyślny Footer:', 'required' => false, 'attr' => array('class' => 'form-control')))
                ->add('css', TextareaType::class, array('label' => 'Domyślny CSS:', 'required' => false, 'attr' => array('class' => 'form-control')))
                ->add('scripts', TextareaType::class, array('label' => 'Domyślny JS:', 'required' => false, 'attr' => array('class' => 'form-control')))
                ->add('checkPhone', CheckboxType::class, array('label' => 'Sprawdzanie numeru telefonów:', 'required' => false, 'attr' => array('class' => 'checkbox', 'data-toggle' => 'toggle')))
                ->add('checkPhoneFields', TextType::class, array('label' => 'checkPhoneFields:', 'required' => false, 'attr' => array('class' => 'form-control')))
                ->add('checkMail', CheckboxType::class, array('label' => 'Sprawdzanie numeru telefonów:', 'required' => false, 'attr' => array('class' => 'checkbox', 'data-toggle' => 'toggle')))
                ->add('checkMailFields', TextType::class, array('label' => 'checkMailFields:', 'required' => false, 'attr' => array('class' => 'form-control')))
                ->add('steps', CollectionType::class, [
                    'entry_type' => MultiStepFormStepType::class,
                    'entry_options' => ['label' => false],
                    'allow_add' => true,
                    'allow_delete' => true,
                    'by_reference' => false,
                    'required' => true,
                ])
                ->add('integrations', CollectionType::class, [
                    'entry_type' => MultiStepFormIntegrationType::class,
                    'entry_options' => ['label' => false],
                    'allow_add' => true,
                    'allow_delete' => true,
                    'by_reference' => false,
                    'required' => true,
                ])
                ->add('submit', SubmitType::class, ['label' => 'Zapisz']);
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults([
            'data_class' => MultiStepForm::class,
        ]);
    }

}

Symfony 2 generowanie encji z pliku w danym bandlu

php app/console doctrine:generate:entities MultiStepFormBundle

Pusta pierwsza wartość w formie typu select

->add('status', ChoiceType::class, ['attr' => array('class' => 'form-control'), 'choices' => ClientStatuses::getTypes(), 'required' => false, 'label' => 'Status:', 'placeholder' => '-------'])

Synfony fos user tworzenie nowego usera

php bin/console fos:user:create test test@example.com test

Symfony fosuserbundle zmiana hasla

php bin/console fos:user:change-password

Fos bundle zastąpienie pola swoimi atrybutami

* @ORM\AttributeOverrides({
 *      @ORM\AttributeOverride(name="username",
 *         column=@ORM\Column(
 *             name="username",
 *             type="string",
 *             length=180,
 *             nullable=false
 *         )
 *     ),})

synfony assert

use Doctrine\ORM\Mapping\AttributeOverrides;
 
 * @Assert\Expression(
 *      "this.email() != null ",
 *     message="The price for 2 pax standard is required",
 * )

Crawler symfony

$crawler = $this->client->request('GET', '/awplans/homepage');
         
$errorTag = $crawler->filter('h1')->each(function($node) {
   return $node->html();
});
        
if (in_array(trim('AW Plany'),$errorTag)) {
  echo 'istnieje';
}
/**
    * @param $crawler - Crawler object  
    * @param $errorTag tag name 
    * @param $tagValue tag value 
    * 
    */
    public function checkTagError(object $crawler, string $tagName,string $tagValue){
                
        $errorTag = $crawler->filter($tagName)->each(function($node) {
            return $node->html();
        });
        
        if (in_array(trim($tagValue),$errorTag)) {
           return true;
        }else{
           return false;
        }
    }

//api bundle

https://github.com/uecode/api-key-bundle

https://packagist.org/packages/ma27/api-key-authentication-bundle

https://medium.com/@_Ma27_/authenticate-users-with-api-keys-using-symfony-and-doctrine-b2270752261a

Symfony custom form

->add('firstname', TextType::class, array('attr' => array('class' => 'form-control')))
            ->add('lastname', TextType::class, array('attr' => array('class' => 'form-control')))
            ->add('class', EntityType::class, array(
                'class' => SchoolClass::class,
                'multiple' => false,
                'attr' => array('class' => 'form-control'),
            ));

Symfony przyklady zapytan

https://stackoverflow.com/questions/34640661/doctrine-query-one-to-many-unidirectional-with-join-table-association-from-in

$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('p')
->from('SomeBundle:Post', 'p')
->join('p.categories', 'c')
->where('c.id = :categoryId')
->setParameter('categoryId', $categoryId)->getQuery()->getResult();
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('p')
->from('SomeBundle:Post', 'p')
->join('p.categories', 'c')
->where($qb->expr()->in('c.id', ':categoryIds'))
->setParameter('categoryIds', $categoryIds) // array of ids
->getQuery()->getResult();

//===============================================================================

$tag = $tag->getId();
$conn = $this->get('database_connection');
$res = $conn->prepare('
SELECT p.id,p.title,p.slug,p.shortcontent,p.published_at
FROM post p, blog_post_tag chuj
where p.id=chuj.post_id
AND chuj.tag_id=:tag
ORDER BY p.published_at DESC');
$res->bindParam(':tag', $tag, PDO::PARAM_INT);
$res->execute();
dump($res->fetchAll(PDO::FETCH_ASSOC));
$query = $this->getDoctrine()->getManager()
->createQuery('SELECT p,t FROM App:Post p left JOIN p.tags t ORDER BY p.publishedAt DESC');

Te same zapytnia:

        return $this->getEntityManager()
            ->createQuery(
                'SELECT o FROM EnpOrderBundle:Order o INNER JOIN o.relatedOrders orr WHERE orr.id IN (SELECT o22.id FROM EnpOrderBundle:Order o22 WHERE o22.uniqueHash = :uniqueHash)'
            )
            ->setParameter('uniqueHash', $orderUniqueHash, PDO::PARAM_STR)
            ->getResult();


        return $this->getEntityManager()->createQueryBuilder()
            ->select('o')
            ->from(Order::class, 'o')
            ->leftJoin('o.relatedOrders', 'ro')
            ->where('o.id IN (SELECT ooooo.id FROM EnpOrderBundle:Order ooooo WHERE ooooo.uniqueHash = :uniqueHash)')
            ->where('ro.id IN (SELECT os.id FROM EnpOrderBundle:Order os WHERE os.uniqueHash = :uniqueHash)')
            ->setParameter('uniqueHash', $orderUniqueHash, PDO::PARAM_STR)
            ->getQuery()
            ->getResult();

Symfony komendy

php bin/console make:migration ::dodanie wersji migracji
php bin/console doctrine:migrations:diff::wykrycie zmian w migracjach
php bin/console doctrine:migrations:migrate ::i jak jakies sa
php bin/console doctrine:fixtures:load ::ladowanie fakera
bin/console make:crud SchoolClass ::tworzenie cruda
php bin/console doctrine:database:create ::tworzenie bazy danych
php bin/console fos:user:create testuser test@example.com p@ssword ::tworzenie usera

php bin/console make:entity --regenerate App //regeneracja wszystkich encji

https://stackoverflow.com/questions/10038581/query-builder-join-on-many-to-many-relationship
//defenestracja