I want to create a slug. it should be a concatenation of title and subtitle.The following is my code and it's not working, i don't know where i went wrong?
public function setTitleAttribute($value)
{
$this->attributes['main_title'] = ucfirst($value);
$this->attributes['sub_title'] = $value;
if (! $this->exists) {
$this->attributes['slug'] = str_slug($this->attributes['main_title'].$this->attributes['sub_title']);
}
}
I need slug as a combination of main_title+sub_title
public function to_slug ($string) {
$table = array(
'Š'=>'S', 'ı'=>'i', 'ğ'=>'g', 'ü'=>'u', 'ş'=>'s', 'ö'=>'o', 'ç'=>'c', 'Ğ'=>'G', 'Ü'=>'U', 'Ş'=>'S',
'İ'=>'I', 'Ö'=>'O', 'Ç'=>'C',
'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
);
return preg_replace('/[^A-Za-z0-9-]+/', '-', strtr($string, $table) );
}
I'm using this code and its working for me.
It is also good for utf-8.
You can use a laravel package:
https://github.com/cviebrock/eloquent-sluggable
Or I use JavaScript when I sent the form:
https://github.com/madflow/jquery-slugify
I have replicated the exact condition like yours passing static data and its working perfectly in my machine.. try below solution.. do some dd and see whats the combination of the main_title and sub_title is resulting. Also check by removing that if condition once.
$this->attributes['main_title'] = ucfirst($value) . " ";
$this->attributes['sub_title'] = $value;
$slugToUse = $this->attributes['main_title'] . $this->attributes['sub_title'];
if (! $this->exists) {
$this->attributes['slug'] = str_slug($slugToUse);
}
}
Related
I'm working with Lumen framework v5.8 (it's the same as Laravel)
I have a command for read a big XML (400Mo) and update datas in database from datas in this file, this is my code :
public function handle()
{
$reader = new XMLReader();
$reader->open(storage_path('app/mesh2019.xml'));
while ($reader->read()) {
switch ($reader->nodeType) {
case (XMLREADER::ELEMENT):
if ($reader->localName === 'DescriptorRecord') {
$node = new SimpleXMLElement($reader->readOuterXML());
$meshId = $node->DescriptorUI;
$name = (string) $node->DescriptorName->String;
$conditionId = Condition::where('mesh_id', $meshId)->first();
if ($conditionId) {
ConditionTranslation::where(['condition_id' => $conditionId->id, 'locale' => 'fr'])->update(['name' => $name]);
$this->info(memory_get_usage());
}
}
}
}
}
So, I have to find in the XML each DescriptorUI element, the value corresponds to the mesh_id attribute of my class Condition.
So, with $conditionId = Condition::where('mesh_id', $meshId)->first(); I get the Condition object.
After that, I need to update a child of Condition => ConditionTranslation. So I just get the element DescriptorName and update the name field of ConditionTranslation
At the end of the script, you can see $this->info(memory_get_usage());, and when I run the command the value increases each time until the script runs very very slowly...and never ends.
How can I optimize this script ?
Thanks !
Edit : Is there a way with Laravel for preupdate multiple object, and save just one time at the end all objects ? Like the flush() method of Symfony
There is a solution with ON DUPLICATE KEY UPDATE
public function handle()
{
$reader = new XMLReader();
$reader->open(storage_path('app/mesh2019.xml'));
$keyValues = [];
while ($reader->read()) {
switch ($reader->nodeType) {
case (XMLREADER::ELEMENT):
if ($reader->localName === 'DescriptorRecord') {
$node = new SimpleXMLElement($reader->readOuterXML());
$meshId = $node->DescriptorUI;
$name = (string) $node->DescriptorName->String;
$conditionId = Condition::where('mesh_id', $meshId)->value('id');
if ($conditionId) {
$keyValues[] = "($conditionId, '".str_replace("'","\'",$name)."')";
}
}
}
}
if (count($keyValues)) {
\DB::query('INSERT into `conditions` (id, name) VALUES '.implode(', ', $keyValues).' ON DUPLICATE KEY UPDATE name = VALUES(name)');
}
}
I'm stuck on this from a while.Can't figured it out.I reed documantion, tried with several videos and tried like 10 different ways, nothing is working yet.So I have one view/model for one thing, in this example Destination and I have separate files for Offers.The controllers for both are in one file.I want tho the information that is in destination to go to Offers as well.Please help I can't figure out what I'm missing:
So here is the most important parts:
destination_model.php
<?php class Destination_model extends CI_Model
{
public function getDestinationDetails($slug) {
$this->db->select('
id,
title,
information
');
$this->db->where('slug', $slug);
$query = $this->db->get('destinations')->row();
if(count($query) > 0)
{
return $query;
}
else
{
// redirect(base_url());
}
}
public function getOffersByDestination($destination_id)
{
$this->db->select('
o.short_title,
o.price,
o.currency,
o.information,
o.long_title_slug,
oi.image,
c.slug as parent_category
');
$this->db->from('offers o');
$this->db->join('offers_images oi', 'oi.offer_id = o.id', 'left');
$this->db->join('categories c', 'c.id = o.category');
$this->db->group_by('o.id');
$this->db->where('o.destination', $destination_id);
$this->db->where('o.active', '1');
return $this->db->get();
} }
And then in the controller for offers I put this:
$this->load->model('frontend/destination_model');
$this->params['destination'] = $this->destination_model->getOffersByDestination($data->id);
All I need is the title and the information about the destination.
Here is the whole controller for the offers:
$data = $this->slugs_model->getOfferDetails(strtok($this->uri->segment(2), "."));
$this->load->model('frontend/offers_model');
$this->load->model('frontend/destination_model');
$this->params['main'] = 'frontend/pages/offer_details';
$this->params['title'] = $data->long_title;
$this->params['breadcumb'] = $this->slugs_model->getSlugName($this->uri->segment(1));
$this->params['data'] = $data;
$this->params['images'] = $this->slugs_model->getOfferImages($data->id);
$this->params['similar'] = $this->slugs_model->getSimilarOffers($data->category, $data->id);
$this->params['destination'] = $this->destination_model->getOffersByDestination($data->id);
$this->params['offers'] = $this->offers_model->getImportantOffers($data->offers, $data->category, $data->id);
You need to generate query results after you get it from model,
e.g: row_array(), this function returns a single result row.
here's the doc: Generating Query Results
try this:
$this->load->model('frontend/destination_model');
$data['destination'] = $this->destination_model->getOffersByDestination($data->id)->row_array();
$this->load->view('view_name', $data);
And in your view echo $destination['attribut_name'];,
or you can print the array, to see if it's work print_r($destination);
I trying to keep original file name when using System/Models/File, I got following code to extend this model:
namespace System\Models;
class NewFile extends File { public function fromPost($uploadedFile) { if ($uploadedFile === null) { return; }
$this->file_name = $uploadedFile->getClientOriginalName();
$this->file_size = $uploadedFile->getClientSize();
$this->content_type = $uploadedFile->getMimeType();
$this->disk_name = $this->getDiskName();
/*
* getRealPath() can be empty for some environments (IIS)
*/
$realPath = empty(trim($uploadedFile->getRealPath()))
? $uploadedFile->getPath() . DIRECTORY_SEPARATOR . $uploadedFile->getFileName()
: $uploadedFile->getRealPath();
//$this->putFile($realPath, $this->disk_name);
$this->putFile($realPath, $this->file_name);
return $this;
It works with file itself, it keeps original name but problem is link to attached file is still being generated. Broke my mind but cant get this work. Can anyone elaborate how to fix it?
Oh I see it seems its try to use disk_name to generate URL
so you did well for saving an image
//$this->putFile($realPath, $this->disk_name);
$this->putFile($realPath, $this->file_name);
but you just need to replace one line .. just undo your changes and make this one change
$this->file_name = $uploadedFile->getClientOriginalName();
$this->file_size = $uploadedFile->getClientSize();
$this->content_type = $uploadedFile->getMimeType();
// $this->disk_name = $this->getDiskName();
$this->disk_name = $this->file_name;
// use same file_name for disk ^ HERE
Link logic ( for referance only ) vendor\october\rain\src\Database\Attach\File.php and modules\system\models\File.php
/**
* Returns the public address to access the file.
*/
public function getPath()
{
return $this->getPublicPath() . $this->getPartitionDirectory() . $this->disk_name;
}
/**
* Define the public address for the storage path.
*/
public function getPublicPath()
{
$uploadsPath = Config::get('cms.storage.uploads.path', '/storage/app/uploads');
if ($this->isPublic()) {
$uploadsPath .= '/public';
}
else {
$uploadsPath .= '/protected';
}
return Url::asset($uploadsPath) . '/';
}
Just make disk_name also same as file_name so when file saved on disk it will use original name and when the link is generated it also use disk_name which is original file_name
now your link and file name are synced and will be same always.
if any doubt please comment.
I am converting one database to another database through a script.
While running the script I am getting the following error:
SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xBFbangl...' for column 'country' at row 1
An exception is thrown where it shows that it tries to set country as "\xcf\xbb\xbf\x62\x61\x6e\x67\x6c\x61\x64\x65\x73\x68".
When I var_dump the value, it just shows as "Bangladesh".
Is there something I have to adjust in my php code?
I have tried this, but phpmyadmin is throwing an #1064 error stating a syntax error in the query.
UPDATE
The scripts is a command in Symfony3:
<?php
namespace My\Bundle\Command;
use My\AccommodationBundle\Entity\Visit;
use My\NewAccommodationBundleV2\Entity\Visit as Visit2;
use My\OtherBundle\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class VisitConvertToNewFormatCommand extends ContainerAwareCommand
{
private $em;
protected function configure()
{
$this
->setName('accommodation:visit:convert')
->setDescription("Converting old structure to new structure'")
;
}
protected function getTimeStamp() {
$currentTime = new \DateTime('now');
return '['.$currentTime->format('Y-m-d H:i:s').'] ';
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln($this->getTimeStamp().$this->getDescription());
$this->em = $this->getContainer()->get('doctrine')->getManager();
$visits = $this->em->getRepository('MyOldAccommodationBundle:Visit')->findAll();
foreach ($visits as $visit) {
$visit2 = new Visit2();
$visit2->setArrivalDate($visit->getArrivalDate());
$visit2->setArrivalStatus($visit->getArrivalStatus());
$visit2->setArrivalTime($visit->getArrivalTime());
$visit2->setBookingType($visit->getBookingType());
$visit2->setCountry($visit->getCountry()); // <----
...
$this->em->persist($visit2);
$user = $visit->getUser();
if ($user != null) {
$person = new Person();
...
$person->setFirstName(trim(ucfirst(strtolower($user->getFirstName()))));
$person->setLastName(trim(ucfirst(strtolower($user->getLastName()))));
$person->setEmail(preg_replace('/\s+/', '', $user->getEmail()));
...
$this->em->persist($person);
}
}
}
}
\x62\x61\x6e\x67\x6c\x61\x64\x65\x73\x68 is Bangladesh; the \xcf\xbb\xbf before it makes no sense. In latin1 it is Ï»¿. It does not validly convert to utf8. CFBB is ϻ (GREEK SMALL LETTER SAN), but then bf is broken utf8.
I suggest it is coming from the source of the data.
var_dump probably showed nothing because of what device you were displaying it on.
Ok after days of trying this did the trick:
$country = iconv("UTF-8", "ISO-8859-1//IGNORE", $country);
I have no idea why it went wrong in the first place. if anybody knows, please share.
I want to create some kind of sitemap in extbase/fluid (based on the pagetree). I have loaded the pages table into a model:
config.tx_extbase.persistence.classes.Tx_MyExt_Domain_Model_Page.mapping.tableName = pages
I have created a controller and repository, but get stuck on the part wich can load the subpages as relation into my model.
For example:
$page = $this->pageRepository->findByPid($rootPid);
Returns my rootpage. But how can I extend my model that I can use $page->getSubpages() or $page->getNestedPages()?
Do I have to create some kind of query inside my model? Or do I have to resolve this with existing functions (like the object storage) and how?
I tried a lot of things but can simply figure out how this should work.
you have to overwrite your findByPid repository-method and add
public function findByPid($pid) {
$querySettings = $this->objectManager->create('Tx_Extbase_Persistence_Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$this->setDefaultQuerySettings($querySettings);
$query = $this->createQuery();
$query->matching($query->equals('pid', $pid));
$pages = $query->execute();
return $pages;
}
to get all pages. Than you can write your own getSubpages-method like
function getSubpages($currentPid) {
$subpages = $this->pagesRepository->findByPid($currentPid);
if (count($subpages) > 0) {
$i = 0;
foreach($subpages as $subpage) {
$subpageUid = $subpage->getUid();
$subpageArray[$i]['page'] = $subpage;
$subpageArray[$i]['subpages'] = $this->getSubpages($subpageUid);
$i++;
}
} else {
$subpageArray = Array();
}
return $subpageArray;
}
i didn't test this method, but it looks like this to get alle subpages.
i wonder that i could´t find a typo3 method that return the complete Page-Tree :( So i write a little function (you can use in an extbase extension), for sure not the best or fastes way, but easy to extend or customize ;)
first you need an instance of the PageRepository
$this->t3pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
this->t3pageRepository->init();
make the init, to set some basic confs, like "WHERE deletet = 0 AND hidden = 0..."
then with this function you get an array with the page data and subpages in. I implement yust up to three levels:
function getPageTree($pid,$deep=2){
$fields = '*';
$sortField = 'sorting';
$pages = $this->t3pageRepository->getMenu($pid,$fields,$sortField);
if($deep>=1){
foreach($pages as &$page) {
$subPages1 = $this->t3pageRepository->getMenu($page['uid'],$fields,$sortField);
if(count($subPages1)>0){
if($deep>=2){
foreach($subPages1 as &$subPage1){
$subPages2 = $this->t3pageRepository->getMenu($subPage1['uid'],$fields,$sortField);
if(count($subPages2>0)){
$subPage1['subpages'] = $subPages2;
}
}
}
$page['subpages'] = $subPages1;
}
}
}
return $pages;
}