kohana bulk insert - kohana

is there a way to add multiple records at a time. usually we call it bulk insert.
currently i doing the following:
foreach ($datalist as $data)
try {
$this->template_id = $data['template_id'];
$this->notifier_id = $data['notifier_id'];
$this->user_id = $data['user_id'];
$this->date_created= date('Y-m-d h:i:s');
$this->save();
return true;
} catch (Kohana_Exception $e) {
return false;
}
}

$query = DB::insert('company_schedule', array('day', 'work_start', 'work_end', 'week_start', 'week_end', 'company_id')); // create sql request
$query->values(array(
$key, $work_start, $work_end, $week_start, $week_end, $this->id
)); // do it in loop
$query->execute(); // execute

Related

Resend specific order state emails e.g. order delivery shipped in shopware 6

I'm wondering if there is any simpler solution in sending specific order state emails.
Currently i use the following code to send e.g. the "order delivery shipped" email again.
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('orderNumber', $orderNumber));
$criteria->addAssociation('orderCustomer.salutation');
$criteria->addAssociation('orderCustomer.customer');
$criteria->addAssociation('stateMachineState');
$criteria->addAssociation('deliveries.shippingMethod');
$criteria->addAssociation('deliveries.shippingOrderAddress.country');
$criteria->addAssociation('deliveries.shippingOrderAddress.countryState');
$criteria->addAssociation('salesChannel');
$criteria->addAssociation('language.locale');
$criteria->addAssociation('transactions.paymentMethod');
$criteria->addAssociation('lineItems');
$criteria->addAssociation('currency');
$criteria->addAssociation('addresses.country');
$criteria->addAssociation('addresses.countryState');
/** #var OrderEntity|null $order */
$order = $this->orderRepository->search($criteria, $context)->first();
$context = new Context(new SystemSource());
$salesChannelContext = $this->orderConverter->assembleSalesChannelContext($order, $context)->getContext();
$salesChannelContext->addExtension(
MailSendSubscriber::MAIL_CONFIG_EXTENSION,
new MailSendSubscriberConfig(false)
);
$event = new OrderStateMachineStateChangeEvent(
'state_enter.order_delivery.state.shipped',
$order,
$salesChannelContext
);
$flowEvent = new FlowEvent('action.mail.send', new FlowState($event), [
'recipient' => [
'data' => [],
'type' => 'default',
],
'mailTemplateId' => $mailTemplateId,
]);
$this->sendMailAction->handle($flowEvent);
Given that you don't actually want to change the state, this looks like a good solution.
If you actually needed to programmatically change the state you could use the StateMachineRegistry service.
$transition = new Transition(OrderDeliveryDefinition::ENTITY_NAME, $orderDeliveryId, StateMachineTransitionActions::ACTION_SHIP, 'stateId');
$this->stateMachineRegistry->transition($transition, Context::createDefaultContext());
However if the current state is equal to the state you want to transition to, then an UnnecessaryTransitionException is expected to be thrown. You'd have to change the state back to a previous one before doing this and at that point your code is probably less trouble, if all you want to do is to repeat sending that mail.
Do you want to resend the mail or regenerate it? If you want to resend the mail you could use this out-of-the-box solution from FriendsOfShopware -> https://store.shopware.com/en/frosh97876597450f/mail-archive.html
You can build and send the mail with the Shopware\Core\Content\Mail\Service\MailService by yourself. But is way more code then just triggering it with a state change.
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('mailTemplateTypeId', self::ORDER_CONFIRMATION_MAIL_TYPE_ID));
$criteria->addAssociation('media.media');
$criteria->setLimit(1);
if ($order->getSalesChannelId()) {
$criteria->addFilter(new EqualsFilter('mail_template.salesChannels.salesChannel.id', $order->getSalesChannelId()));
/** #var MailTemplateEntity|null $mailTemplate */
$mailTemplate = $this->mailTemplateRepository->search($criteria, $this->context)->first();
// Fallback if no template for the saleschannel is found
if (null === $mailTemplate) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('mailTemplateTypeId', self::ORDER_CONFIRMATION_MAIL_TYPE_ID));
$criteria->addAssociation('media.media');
$criteria->setLimit(1);
/** #var MailTemplateEntity|null $mailTemplate */
$mailTemplate = $this->mailTemplateRepository->search($criteria, $this->context)->first();
}
} else {
/** #var MailTemplateEntity|null $mailTemplate */
$mailTemplate = $this->mailTemplateRepository->search($criteria, $this->context)->first();
}
if (null === $mailTemplate) {
return;
}
$data = new DataBag();
$data->set('recipients', [
$order->getOrderCustomer()->getEmail() => $order->getOrderCustomer()->getFirstName() . ' ' . $order->getOrderCustomer()->getLastName(),
]);
$data->set('senderName', $mailTemplate->getTranslation('senderName'));
$data->set('salesChannelId', $order->getSalesChannelId());
$data->set('templateId', $mailTemplate->getId());
$data->set('customFields', $mailTemplate->getCustomFields());
$data->set('contentHtml', $mailTemplate->getTranslation('contentHtml'));
$data->set('contentPlain', $mailTemplate->getTranslation('contentPlain'));
$data->set('subject', $mailTemplate->getTranslation('subject'));
$data->set('mediaIds', []);
$attachments = [];
if (null !== $mailTemplate->getMedia()) {
foreach ($mailTemplate->getMedia() as $mailTemplateMedia) {
if (null === $mailTemplateMedia->getMedia()) {
continue;
}
if (null !== $mailTemplateMedia->getLanguageId() && $mailTemplateMedia->getLanguageId() !== $order->getLanguageId()) {
continue;
}
$attachments[] = $this->mediaService->getAttachment(
$mailTemplateMedia->getMedia(),
$this->context
);
}
}
if (!empty($attachments)) {
$data->set('binAttachments', $attachments);
}
try {
if (
null === $this->mailService->send(
$data->all(),
$this->context,
$this->getTemplateData($order)
)
) {
throw new \Exception('Could not render mail template');
}
$this->orderMailRepository->upsert([[
'orderId' => $order->getId(),
'confirmationSend' => true,
]], $this->context);
} catch (\Exception $e) {
$this->logger->error(sprintf(
'Could not send mail for order %s: %s',
$order->getOrderNumber(),
$e->getMessage()
));
}
}

Querying with the Query Builder

I'M USING SYMFONY 4.12 I'm trying to write queries to filter my jobs(I've job table ,départements one) I first try with experience but I'm stuck in
here is my offerController:
/**
* #Route("/offres", name="offres")
* #param Request $request
* #param PaginatorInterface $paginator
* #param FormFactoryInterface $formFactory
* #return Response
*/
public function offreSearch(Request $request, PaginatorInterface $paginator ,FormFactoryInterface $formFactory):Response
{
$datas =new OffreEmploi();
$formFilter=$formFactory->create(OfferFilterForm::class,$datas);
$offres = $this->repository->findSearch($datas);
$formFilter->handleRequest($request);
return $this->render('offre/index.html.twig', [
'controller_name' => 'OffreController',
'offres' => $offres,
'formulaire' =>$formFilter->createView(),
]);
}
and this is my query in the offerRepository:
public function findSearch(OffreEmploi $data):?array
{
$query = $this->createQueryBuilder('o');
if ($data->getExperience() !== null) {
$query
->where('o.experience > :experience')
->setParameter('experience', $data->getExperience());
}
return $query->getQuery()->getResult();
}
when it come to enter any number IT gives the same thing it shows all the jobs stored in the database,I don't know where the problem is.
THE RESULT
Try with this solution:
public function findSearch(OffreEmploi $data):?array
{
$query = $this->createQueryBuilder('o');
if (!empty($data->getExperience())
// ...
}
return $query->getQuery()->getResult();
}
If it doesn't work , try to dump $data->getExperience() to see its value
public function findSearch(OffreEmploi $data):?array
{
$query = $this->createQueryBuilder('o');
dd($data->getExperience()) ;
}
EDIT
So try to do like this but be sure you send the form with GET method not POST:
public function offreSearch(Request $request, PaginatorInterface $paginator)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(OfferFilterForm::class);
$form->handleRequest($request);
$data = $request->query->all();
$qb = $em->getRepository(OffreEmploi::class)->findSearch($data);
$offres = $paginator->paginate($qb, $request->query->get('page', 1), 20);
return $this->render('offre/index.html.twig', array(
'formulaire' =>$form->createView(),
'offres' => $offres,
));
}
In the formType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('experience', IntegerType::class);
//.....
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => null,
'csrf_protection' => false,
));
}
public function getBlockPrefix()
{
return null;
}
and in the Repository:
public function findSearch($data)
{
$query = $this->createQueryBuilder('o');
if (!empty($data['experience'])) {
$query
->where('o.experience > :experience')
->setParameter('experience', $data['experience']);
}
return $query->getQuery()->getResult();
}
I think I found the answer but I just create another class witch contain all the form's field and that's it I don't know how it works because I didn't change significant things for that thinks for your help.

Always the same view content on slim framework with twig after save changes

I'm using Slim and Twig and I'm trying to change a view content, but it doesn't change after I saved the changes.
This is the controller:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../../vendor/autoload.php';
require './classes/connection.php';
$app = new \Slim\App;
$container = $app->getContainer();
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('../../views', [
'cache' => '../../views_cache'
]);
// Instantiate and add Slim specific extension
$router = $container->get('router');
$uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
$view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
return $view;
};
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
/*$name = $args['name'];
$response->getBody()->write("Hello, $name");
echo getcwd();
return $response;*/
return $this->view->render($response, 'login.html', [
'name' => $args['name']
]);
});
$app->post('/login', function (Request $request, Response $response, array $args) {
$post_data = $request->getParsedBody();
if (isset($post_data['user']) && isset($post_data['pass'])) {
$mongo = new Connection();
$conn = $mongo->getConnection();
$collection = $conn->prueba->users;
$result = $collection->find(['user' => $post_data['user']])->toArray();
$dbUser = $result[0]['username'];
$dbPass = $result[0]['password'];
if (password_verify($post_data['pass'], $dbPass)) {
echo '¡La contraseña es válida!';
} else {
echo 'La contraseña no es válida.';
}
} else {
return $response->withJson(array('login_status' => 'ko'));
}
});
$app->run();
What I missed to see the view changes? I think it's something about compile view but I'm not sure. It's the first time I use this framework.

How can i override set_message multiple time in foreach in codeginiter?

foreach($all_fields as $row){
$datatype = $this->sys_model->get_table_data_by_datatype_id('datatype',$row['datatype_id']);
$msg = $this->sys_model->get_validation_message_by_datatype_id('validation_message',$row['datatype_id']);
if($datatype[0]['datatype'] == 'email'){
$this->form_validation->set_rules($row['field_name'],$row['field_name'], 'required|trim|xss_clean|valid_email');
$this->form_validation->set_message('required',$msg[0]['validation_msg']);
}
elseif($datatype[0]['datatype'] == 'number'){
$this->form_validation->set_rules($row['field_name'],$row['field_name'], 'required|numeric');
$this->form_validation->set_message('required',$msg[0]['validation_msg']);
}else{
$this->form_validation->set_rules($row['field_name'],$row['field_name'], 'required');
$this->form_validation->set_message('required',$msg[0]['validation_msg']);
}
}
i want to set validation message dynamically from backend based on datatype but it takes same message for all fields..
How can i set different message for all fields based on datatype ?
create a callback functions for each datatype
function validate_string($str)
{
if(condition) )
{
return true;
}
else
{
$this->form_validation->set_message('validate_string', 'The %s your custom error message');
return false;
}
}
$this->form_validation->set_rules('field1', 'label1', 'validate_string');
$this->form_validation->set_rules('field2', 'label2', 'validate_string');
$this->form_validation->set_rules('field3', 'label3', 'validate_string');
$this->form_validation->set_rules('field4', 'label4', 'validate_string');

Plug-in for Smart Search on Joomla: no results

I'm writing a plug-in for my component. For this component I have table "#__radiocatalog_item" with columns id, name, description, and I need to lookup at column name. For this, I wrote this plugin:
<?php
defined('JPATH_BASE') or die;
require_once JPATH_ADMINISTRATOR.'/components/com_finder/helpers/indexer/adapter.php';
class PlgFinderRadioitem extends FinderIndexerAdapter
{
protected $context = 'Radioitem';
protected $extension = 'com_radiocatalog';
protected $layout = 'item';
protected $type_title = 'item';
protected $table = '#__radiocatalog_item';
protected $state_field = 'parent';
protected $autoloadLanguage = true;
protected function setup()
{
return true;
}
public function onFinderDelete($context, $table)
{
if ($context == 'com_radiocatalog.item')
{
$id = $table->id;
}
elseif ($context == 'com_finder.index')
{
$id = $table->id;
}
else
{
return true;
}
return $this->remove($id);
}
public function onFinderChangeState($context, $pks, $value)
{
if ($context == 'com_radiocatalog.item')
{
$this->itemStateChange($pks, $value);
}
if ($context == 'com_plugins.plugin' && $value === 0)
{
$this->pluginDisable($pks);
}
}
protected function index(FinderIndexerResult $item, $format = 'html')
{
if (JComponentHelper::isEnabled($this->extension) == false)
{
return;
}
$item->url = $this->getURL($item->id, 'com_radiocatalog&layout=item', $this->layout);
$item->route = 'index.php?option=com_radiocatalog&view=item&layout=item&id='.$item->id;
$item->addTaxonomy('Type', 'Radioitems');
$item->addTaxonomy('Language', $item->language);
$this->indexer->index($item);
}
protected function getListQuery($sql = null)
{
$db = JFactory::getDbo();
$sql = $sql instanceof JDatabaseQuery ? $sql : $db->getQuery(true);
$sql->select('a.id as id, a.name as title, a.description as description');
$sql->from('#__radiocatalog_item AS a');
return $sql;
}
protected function getStateQuery()
{
$sql = $this->db->getQuery(true);
$sql->select($this->db->quoteName('a.id'));
$sql->select($this->db->quoteName('a.name').' as title');
$sql->from($this->db->quoteName('#__radiocatalog_item') . ' AS a');
return $sql;
}
}
?>
After full indexing, search on the site does not work.
I was struggling with the same problem. So I enabled Joomla debugging {Global Configuration / System / Debug System = true} and tried to search for a term "myterm" using public site SmartSearch module. Then I checked the performed SQL queries. First, the term was found:
SELECT t.term, t.term_id
FROM j_finder_terms AS t
WHERE t.term = 'myterm'
AND t.phrase = 0
with ID=653 (used later):
SELECT l.link_id,m.weight AS ordering
FROM `j_finder_links` AS l
INNER JOIN `j_finder_links_terms2` AS m
ON m.link_id = l.link_id
WHERE l.access IN (1,1)
AND l.state = 1
AND (l.publish_start_date = '0000-00-00 00:00:00' OR l.publish_end_date <= '2014-01-04 17:34:00')
AND (l.publish_end_date = '0000-00-00 00:00:00' OR l.publish_end_date >= '2014-01-04 17:34:00')
AND m.term_id IN (653)
But this query didn't return any result, because j_finder_links.access and j_finder_links.state values were set to 0 instead of 1.
So my suggest you to check the queries and if you have the same problem, try to change your query from getStateQuery() method or select "1 AS access, 1 AS state" in the getListQuery() query and leave the $state_field variable unset.
I'm sorry for a vague explanation, I don't know much about how the SmartSearch work, I'm just trying to make it work somehow with my component.

Resources