UTF-8 characters are disappeared after Zend Form render - zend-form

I use Zend Framework 2 and have this code in my view script. Name and description are Russian strings:
$brand = $form->get('brand');
$id = $brand->get('id');
$name = $brand->get('name');
$type = $brand->get('type');
$description = $brand->get('description');
\Zend\Debug\Debug::dump($name->getValue()); //correctly dumps russian letters
\Zend\Debug\Debug::dump($this->formText()->getEncoding()); //UTF-8 (by default)
But when I'm trying to render these elements, I have empty input and textarea:
<?= $this->formText($name) ?>
<?= $this->formTextarea($description) ?>
I've found, that Zend\Form\View\Helper\AbstractHelper do the following code:
$strings[] = sprintf('%s="%s"', $escape($key), $escape($value));
after which russian letters disappear. But I still have no idea how to fix this.

Related

Insert SQL statement error

Hi Im trying to insert data into a database using an insert statement. So basically, the user inputs data into a form and then once the submit button is clicked its meant to get the property_id of the table Property.
My code is this:
<?php
$id = intval($_GET['id']);
$query = mysql_query('SELECT * FROM review WHERE property_id="'.$id.'"');
if(isset($_POST['submit']))
{
$review = mysqli_real_escape_string($mysqli, $_POST['review']);
if(mysqli_query($mysqli, "INSERT INTO review(review) VALUES ('$review')"))
{
?>
<script>alert('Successfully Updated ');</script>
<?php
}
else
{
?>
<script>alert('Error...');</script>
<?php
}
}
?>
At the top of the page is my other code which is as followed:
<?php
include_once '../db/dbconnect.php';
$id = intval($_GET['id']);
$sql = 'SELECT* FROM property WHERE property_id="'.$id.'"';
$result = mysqli_query($mysqli, $sql);
$row=mysqli_fetch_array($result);
?>
The code above basically displays all the data for that individual property. Any help would be great.
There are several errors in your code:
$id = intval($_GET['id']);
$query = mysql_query('SELECT * FROM review WHERE property_id="'.$id.'"');
The mysql_* functions are deprecated in PHP 5, and totally removed in PHP 7. Don't use them!
Moreover, it's not possible to use mysql_* and mysqli_* functions together.
Yet another error: you are executing a SELECT query, but you never fetch the results!
Note: you don't need to concatenate $id. It makes the code harder to read with plenty of useless single and double quotes, and increases the likeliness of a typo. Just enclose the variables in a double-quoted string.
You are casting $id to an int value. If the field property_id is an integer, there is no need to put single quotes around $id in the query.
Updated snippet:
$id = intval($_GET['id']);
$query = mysqli_query($mysqli, "SELECT * FROM review WHERE property_id=$id") or die(mysqli_error($mysqli));
while($r = $query->fetch_assoc()) {
// do something here with the current record $r
}
Your code:
if(mysqli_query($mysqli, "INSERT INTO review(review) VALUES ('$review')"))
[...]
<script>alert('Error...');</script>
When developing, you should display (or write to a log file) the MySQL error message from each failing query. It will make debugging much easier:
<script>alert('Error: <?= mysqli_error($mysqli) ?>');</script>

get value of CHtml::activeDropDownList in yii

I have this code
<?php echo CHtml::activeDropDownList(
$semaineModel,
'libelleSemaine',
CHtml::listData(Semaine::findBySql('SELECT * FROM Semaine')->all(), 'idSemine', 'libelleSemaine')
); ?>
but why that displays just the last element of the table, and me I have 6 items in this table 'Semaine 1' to 'Semaine 6'
and that code display just 'Semaine 6'.
an idea please ?
Then you don't nedd CHtml but active dropDownList
Assiming your Semain model is named Semain
use app\models\Semaine;
use yii\helpers\ArrayHelper;
$semaines=Semaine::find()->all();
$listSemaines = $listData=ArrayHelper::map($semaines,'idSemine', 'libelleSemaine');
echo $form->field($model, 'idSemaine')->dropDownList( $listSemaines,
['prompt'=>'Select Semaine...']);

Youtube api get latest upload thumbnail

I am looking to returning the video-thumbnail of the latest uploaded video from my channel, and display it on my website.
Anyone know how I can do a minimal connection trough api and get only the thumbnail?
Thanks!
-Tom
REVISED!!
Using Cakephp, this is how I did it (thanks dave for suggestions using zend);
controller:
App::import('Xml');
$channel = 'Blanktv';
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads?v=2&max-results=1&orderby=published';
$parsed_xml =& new XML($url);
$parsed_xml = Set::reverse($parsed_xml);
//debug($parsed_xml);
$this->set('parsed_xml',$parsed_xml);
View;
$i=0;
foreach ($parsed_xml as $entry)
{
echo '<a href="/videokanalen" target="_self">
<img width="220px" src="'.$entry['Entry']['Group']['Thumbnail'][1]['url'] .'">
</a>';
}
Now the only thing remaining is to cache the feed call someway.. Any suggestions???
-Tom
here is a quick dirty way of doing it without really touching the api at all.
I'm not suggesting it's best practice or anything and I'm sure there are smarter ways but it definitely works with the current Youtube feed service.
My solution is PHP using the Zend_Feed_Reader component from Zend Framework, if you need a hand setting this up if you're not familiar with it let me know.
Essentially you can download version 1.11 from Zend.com here and then make sure the framework files are accessible on your PHP include path.
If you are already using Zend Framework in an MVC pattern you can do this in your chosen controller action:
$channel = 'Blanktv'; //change this to your channel name
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads';
$feed = Zend_Feed_Reader::import($url);
$this->view->feed = $feed;
Then you can do this in your view:
<h1>Latest Video</h1>
<div>
<?php
$i=0;
foreach ($this->feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
echo '<h3>' . $entry->getTitle() . '</h3>';
echo '<p>Uploaded on: '. $entry->getDateCreated() .'</p>';
echo '<a href="http://www.youtube.com/watch?v=' . $videoId .'" target="_blank">
<img src="http://img.youtube.com/vi/' . $videoId .'/hqdefault.jpg">
</a>';
$i++;
if($i==1) break;
}
?>
</div>
otherwise you can do:
<?php
$channel = 'Blanktv'; //change this to your channel
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads';
$feed = Zend_Feed_Reader::import($url);
?>
<h1>Latest Video</h1>
<div>
<?php
$i=0;
foreach ($feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
echo '<h3>' . $entry->getTitle() . '</h3>';
echo '<p>Uploaded on: '. $entry->getDateCreated() .'</p>';
echo '<a href="http://www.youtube.com/watch?v=' . $videoId .'" target="_blank">
<img src="http://img.youtube.com/vi/' . $videoId .'/hqdefault.jpg">
</a>';
$i++;
if($i==1) break;
}
?>
</div>
With the latter method you'll likely need to use a php require statement for the Zend_Feed_Reader files etc....
Hope this helps, like I say let me know if you need a hand.
All the best,
Dave
UPDATE: In response to your comments about caching
Hi Tom, here is another quick and dirty solution which doesn't use cache but may be very quick to implement.
The reason I didn't go with a caching component is because I figured a simple db solution would suffice under the circumstances. I also thought having to pull the feed to compare whether it was new or not wouldn't be the most economical for you.
You could automate this process to be run automatically at specified times but if you don't want to automate the process and don't mind clicking a link to update the video manually you could trigger it that way.
My solution is again based on ZF but since you were ok hacking it into something useful with cakephp you should have no problem doing the same here.
First set up a new table (assuming a MySQL db):
CREATE TABLE `yourdbname`.`latestvid` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique identifier',
`videoId` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video id',
`videoTitle` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video title',
`uploadDate` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video upload date'
) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci;
INSERT INTO `yourdbname`.`latestvid` (`id`, `videoId`, `videoTitle`, `uploadDate`) VALUES (NULL, '--', '--', '--');
This will create a table for your latest video info for use in your template however the default values I've set up will not work with your template for obvious reasons.
You could then do something similar to this:
public function updateAction()
{
$this->_helper->viewRenderer->setNoRender(); // disable view
$this->_helper->layout()->disableLayout(); // disable layout
$user = 'Blanktv'; // insert your channel name
$url = 'https://gdata.youtube.com/feeds/api/users/'.$user.'/uploads';
$feed = Zend_Feed_Reader::import($url);
if(!$feed)
{
die("couldn't access the feed"); // Note: the Zend component will display an error if the feed is not available so this wouldn't really be necessary for ZF
}
else
{
$i=0;
foreach ($feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
$videoTitle = $entry->getTitle();
$uploadDate = $entry->getDateCreated();
// use your preferred method to update the db record where the id = 1
$i++;
if($i==1) break;
}
}
}
Maybe have a go and let me know how you get on?
You'd just need to tweak the template so you'd get the variables from the database instead of Youtube with the exception of the thumbnail.
I suppose you could always take that approach further and actually store images etc since the thumbnail is still being pulled from Youtube and may slow things down.
You could set up a script to copy the thumbnail to your own server and store the path in the db or use a standard thumbnail if you are running a series of videos for which you require standard branding - anyway hope it helps.
:-D
Dave

How to append a parameter to current page using CHtml::link?

Using Yii, and trying to append a Lang=xx to the end of the current page url and present it on the page.
I put the below code in the protected/views/layout/main.php
<?php echo CHtml::link('English', array('','lang'=>'en'), array('class'=>'en')) ?>
<?php echo CHtml::link('中文', array('','lang'=>'tw'), array('class'=>'tw')) ?>
<?php echo CHtml::link('日本語', array('','lang'=>'jp'), array('class'=>'jp')) ?>
With standard pages like "/site/index", or controller action pages like "/site/contact", they work fine. But with the standard static pages like "site/page?view=about", it's not working. The url expected should be something like "site/page?view=about&lang=tw", but instead, it gives me "site/page?lang=tw".
How can I fix that?
I ended up doing it with langhandeler extension and url rules and map [site]/[path]?lang=[language code] to [site]/[language code]/[path]
And then I coded the links like below:
<?php
$request = $_SERVER['REQUEST_URI'];
$path_a = explode("/",$request);
$haveLang = isSet($_GET["lang"]);
$uri = ($haveLang?
substr($request, strlen($path_a[1])+1) //strip language prefix and the slash
:$request); //don't process if the page is in default language
echo CHtml::link(CHtml::encode(Yii::app()->name), CHtml::normalizeUrl(($haveLang?'/'.$_GET["lang"].'/':'/')), array('id'=>'logo'));
?>
<div id="lang_switch">
<?php
echo CHtml::link('English', CHtml::normalizeUrl($uri), array('class'=>'en')); //no need to add default language prefix
echo CHtml::link('中文', CHtml::normalizeUrl('/tw'.$uri), array('class'=>'tw'));
echo CHtml::link('日本語', CHtml::normalizeUrl('/jp'.$uri), array('class'=>'jp'));
?>
</div>
that pretty much solved my problem. I hope this could help out someone else in the future.
you can give chtml link like this
$language = 'en';
CHtml::link("English", array('site/about/lang/' . $language));
site/about/lang/en = controller/action/lang/en
i hope this will help you.

symfony get data from array

I'm trying to use an SQL query to get data from my database into the template of a symfony project.
my query:
SQL:
SELECT l.loc_id AS l__loc_id, l.naam AS l__naam, l.straat AS l__straat,
l.huisnummer AS l__huisnummer, l.plaats AS l__plaats, l.postcode AS l__postcode,
l.telefoon AS l__telefoon, l.opmerking AS l__opmerking, o.org_id AS o__org_id, o.naam AS o__naam
FROM locatie l
LEFT JOIN organisatie o
ON l.org_id = o.org_id
This is generated by this DQL:
DQL:
$this->q = Doctrine_Query::create()
->select('l.naam, o.naam, l.straat, l.huisnummer, l.plaats, l.postcode, l.telefoon, l.opmerking')
->from('Locatie l')
->leftJoin('l.Organisatie o')
->execute();
But now when i try to acces this data in the template by either doing:
<?php foreach ($q as $locatie): ?>
<?php echo $locatie['o.naam'] ?>
or
<?php foreach ($q as $locatie): ?>
<?php echo $locatie['o__naam'] ?>
i get the error from symfony:
500 | Internal Server Error | Doctrine_Record_UnknownPropertyException
Unknown record property / related component "o__naam" on "Locatie"
Does anyone know what is going wrong here? i dont know how to call the value from the array if the names in both query's dont work.
Doctrine will have hydrated your results into objects corresponding to the models in your query. In your case these will be Locatie and Organisatie. You should therefore be able to access the data as follows:
<?php foreach ($q as $obj): ?>
<?php echo $obj->Locatie->naam; ?>
<?php echo $obj->Organisatie->naam; ?>
<?php endforeach; ?>
If you have the above method in eg the Locatie table class and use self::create("l") to create your method, the object you use in the view won't need the ->Locatie part.
Edit: table method example:
class LocatieTable extends Doctrine_Table
{
public function getLocaties()
{
$q = self::createQuery("l")
->select('l.naam, o.naam, l.straat, l.huisnummer, l.plaats, l.postcode, l.telefoon, l.opmerking')
->leftJoin('l.Organisatie o')
->execute();
return $q;
}
}
You should be able to find this class (probably empty) already auto-generated in lib/model/doctrine/LocatieTable.class.php. Now call it with:
$this->q = Doctrine::getTable("Locatie")->getLocaties();
If you want to know how to get some value from the result DoctrineRecord object I advise to use var_dump($obj->toArray()) method to get clear view of the object structure. After that you can use several types of getters to retrive what you want (e.g. $obj->A->b, $obj->getA()->getB() etc..)