enter a specific object value - zend-framework2

i'm using zendframwork 2 , i implement the album exemple in the official documentation
http://framework.zend.com/manual/2.1/en/user-guide/overview.html#the-tutorial-application (so in my model folder i have Album.php and AlbumTable.php) and all works fine , i just want to make a small modification :
i want to have acces to the third element in album . in the index.phtml view (originally i have this code )
<?php foreach ($albums as $album) : ?>
<?php echo $this->escapeHtml($album->title);?>
<?php echo $this->escapeHtml($album->artist);?>
<?php endforeach; ?>
i tried things like
<?php echo $this->escapeHtml($album->title[3]);?>
<?php echo $this->escapeHtml($album[3]->title);?>
but i always get this error
( ! ) Fatal error: Cannot use object of type Auth\Model\Album as array in C:\wamp\www\zf2-album\module\Auth\view\auth\auth\index.phtml on line 14
any help please ?
thanks every one

Do you need ONLY the third one? Then write your Query to be more efficient ;) For all other cases, since you are working with a Zend\Db\ResultSet\ResultSet, which uses Iterator you have different options.
The first one would be to still iterate through the fieldset like
while ($albums->key() != 3) {
$albums->next();
}
$album = $albums->current();
The alternative would be to simply convert the ResultSet into an array
$myAlbums = $albums->toArray();
$album = $myAlbums[3];
Depending on how big your ResultSet is and how many entries you really need, either Solution may be faster for you. Guess you have to test that one ;)

Related

Passing URL parameter to link on page

I am trying to grab a parameter from a webpage and insert it into a URL link on that same page but am having problems with the syntax.
So, for example, the webpage is www.website.com?src=mm
Currently the code on the page that does not pull in the parameter is
<?php echo "<A HREF='http://www.website2.com?offer=AAt&sub1=422'><B>Click Here</B></A><BR>" ?>
I would like to include that "mm" parameter at the end of the URL so the final URL is:
http://www.website2.com?offer=AA&sub1=422&sub2=mm
I tried the following but does not work:
<?php echo "<B>Click Here</B><BR>" ?>
Any ideas on how to get this to work? Thanks
Your code doesn't even compile:
Parse error: syntax error, unexpected 'http' (T_STRING), expecting ',' or ';' in /var/www/html/ImagePT/test.php on line 1
it has to be
<?php echo '<B>Click Here</B><BR>'; ?>
but since I'm just in the mood to give you some further advice:
You don't have to write HTML in uppercase, it's rather unusual (not impossible, but you don't see it very often) - then this script is horrible, when the $_GET['src'] variable is undefinied, therefore I'd check if it is set and then modifiy the URL accordingly. So my advice would be to use the following:
<?php
if(isset($_GET['src']))
{
echo '<b>Click Here</b></br>';
}
else
{
echo '<b>Click Here</b></br>';
}
?>

Can I use two sets of variables in one foreach loop?

Is is possible to construct one single foreach loop that loops through using two separate sets of variables?
Below is a simplified example of what I'm trying to do - except this example lists two separate loops whereas I would like to set them up in one single loop.
$Sites = #("https://www.google.com" , "https://duckduckgo.com")
$Site_names = #( "Google" , "DuckDuckGO")
foreach ($element in $Sites) {
Write-Host "`n`n"
$element
Write-Host "`n`n"
}
foreach ($name in $Site_names) {
Write-Host "`n`n"
$name
Write-Host "`n`n"
}
There is other code to be used so the loop needs to be able to allow for multiple lines of code in the code block - so a single line solution if there is one isn't what I'm after. Also I didn't think using the pipeline would be workable (but I could certainly be wrong on that).
Two sets of variables: $Sites and $Site_names.
I would like one foreach loop that runs through and lists the site address and the site name with both values changing each time the loop is run.
First run: reference the URL "https://www.google.com" and the site name "Google".
Second run: reference the URL "https://duckduckgo.com" and the site name "DuckDuckGo".
Is this possible?
If you have two arrays of the same size you can simply use a for loop like this:
for ($i=0; $i -lt $Sites.Count; $i++) {
"{0}`t{1}" -f $Site_names[$i], $Sites[$i]
}
However, if the elements of your two arrays are correlated anyway, it would be better to use a hashtable instead:
$Sites = #{
'Google' = 'https://www.google.com'
'DuckDuckGo' = 'https://duckduckgo.com'
}
foreach ($name in $Sites.Keys) {
"{0}`t{1}" -f $name, $Sites[$name]
}

ZF2: How to pass a variable from the method attached to MvcEvent::EVENT_FINISH to the layout attached in MvcEvent::EVENT_RENDER?

I am trying to understand Zend Framework 2 (ZF2). Few days ago I bought the book "Learn ZF2: Learning By Example" by Slavey Karadzhov. Now I am reading it and trying to get some examples working.
I am stuck in page 60. The example shown in the book works well, but the modification I just made does not work... Why? How to fix it?
To get into the same code/situation you would have to:
git clone https://github.com/slaff/learnzf2 .
composer.phar self-update
composer.phar install
git stash
git checkout 'ch-view'
After that You will have the same setup as I do.
Now I have changed the file /module/Debug/view/debug/layout/sidebar.phtml from this:
<h1>Top Line</h1>
<?= $this->content ?>
<h1>Bottom Line</h1>
to this (just added one line at the end):
<h1>Top Line</h1>
<?= $this->content ?>
<h1>Bottom Line</h1>
<p>MVC duration: <?= $this->mvcDuration ?></p>
I would like $this->mvcDuration to be the value of $duration from /module/Debug/Module.php file getMvcDuration method.
I changed the content of method getMvcDuration from this:
public function getMvcDuration(MvcEvent $event)
{
// Here we get the service manager
$serviceManager = $event->getApplication()->getServiceManager();
// Get the already created instance of our timer service
$timer = $serviceManager->get('timer');
$duration = $timer->stop('mvc-execution');
// and finally print the duration
error_log("MVC Duration:".$duration." seconds");
}
to this (added two lines at the end of the method):
public function getMvcDuration(MvcEvent $event)
{
// Here we get the service manager
$serviceManager = $event->getApplication()->getServiceManager();
// Get the already created instance of our timer service
$timer = $serviceManager->get('timer');
$duration = $timer->stop('mvc-execution');
// and finally print the duration
error_log("MVC Duration:".$duration." seconds");
$viewModel = $event->getViewModel();
$viewModel->setVariable('mvcDuration', $duration);
}
However, this kind of change does not work and the value of $duration is not passed to the layout. The question is WHY? How can I pass $duration to $this->mvcDuration of the layout?
p.s. The code downloaded from official github repo (https://github.com/slaff/learnzf2) is acting quite strange... Changing project files (e.g.: /module/Debug/view/debug/layout/sidebar.phtml) does not change the output. If You have the same situation while trying to help me with this case then I would suggest you to modify files in /vendor/learnzf2 directory instead of files in /module directory. I know that modifying code in vendor directory is not good thing to do, but let this post (my question) be about the one problem only.
Good book. Your basic problem is that you are Trying to update a variable into the view in a method that is triggered after the view has already been sent. You probably can't do this, unless you redefine which event triggers it, but that would defeat the intended purpose of timing the whole mvc duration.
All that said, you shouldn't be injecting variables into the view model from module.php. It's very hard to test that. This is what view helpers are good for.

Zend framework 2 CSV data as an array or string

I am still very new to Zend and running into some issues on exporting my data to a CSV.
I found a great resource that explains the headers and download part here however I am running into issues when trying to export the actual data.
If I create a variable like $content = "test" the export works fine using the code above.
However when I duplicate my indexAction code, make some changes, and bring it into my downloadAction, I am getting issues that I believe are due to my content being returned as an Object rather than an array or string.
My Module is grabbing the SQL by using:
public function fetchAllMembers($order = null , $order_by = null, $selectwhere = null) {
$session = new SessionContainer('logggedin_user');
$sql = new Sql($this->adapter);
$select = new Select();
$select->from(array('u' => 'tbl_all_data'));
if ($selectwhere != null){
$select->where($selectwhere);
}
$select->order($order_by . ' ' . $order);
$selectString = $sql->getSqlStringForSqlObject($select);
$results = $this->adapter->query($selectString, Adapter::QUERY_MODE_EXECUTE);
$results->buffer();
return $results;
}
and my Controller is calling that SQL by using:
$content = $modulesTable->fetchAllMembers($order, $order_by, $where);
Any help would be greatly appreciated, and I don't need anyone to write the code for me just help with pointoing me in the right direction.
$this->adapter->query returns a Zend\Db\ResultSet object. So you need to call $results = $results->toArray(); to send an array.
Also you need to loop through the array and echo it out in your view file.
Results, returned by adapter are ResultSet type. I guess you need to call at least
current()
method to grab some data. And they will be of array type, so, again you need to do something with them.
toArray() is often used to quickly get data.
More sophisticated way to get data, is to use next() method with current():
$firstThing = $result->current();
$result->next();
$result->next();
$thirdThing = $result->current();
It's just an example, but it can be useful in some cases.

How to display extra fields in article with K2

currently I've got Jreviews installed and I'd like to replace it by K2 to list specialized shops with addresses, phones, maps, opening hours ...
With K2 I guess I'll need to define extra custom fields to hold those specific information. No problem.
But, how may I configure things to have those fields displayed in the detailed article/items for a specific shop ?
Many thanks,
Tibi.
// In the item template you can skip this first line...
$this->item->extra_fields = K2ModelItem::getItemExtraFields($this->item->extra_fields);
$extraFlds = array();
if ( $this->item->extra_fields ){
foreach ( $this->item->extra_fields as $key=>$extraField ){
$extraFlds[ $extraField->name ] = $extraField->value;
}
}
Then you can access your extra fields in the associate array like $extraFlds['my field']
After a lot of tries here what i used and worked for me
<?php
// if form is empty show default form
$k2obj = new K2ModelItem();
$fields = $k2obj->getItemExtraFields($this->item->extra_fields, $this->item);
//echo $this->item->extraFields->State->name;
echo $this->item->extraFields->FIELD_ALIAS->value;
?>
This is working and noted its all pegged to instantiating the class.
Note: I am using this in the k2 item i version 2.6.7 Joomla 2.5.14
if you want show custum field in k2 table list go to:
components\com_k2\templates\default\category_item.php
and edit file near line 136 like this:
<?php foreach ($this->item->extra_fields as $key=>$extraField):
**if(strpos($extraField->name,"/")){**
?>
<li class="<?php echo ($key%2) ? "odd" : "even"; ?> type<?php echo ucfirst($extraField->type); ?> group<?php echo $extraField->group; ?>">
<span class="catItemExtraFieldsLabel"><?php echo $extraField->name; ?></span>
<span class="catItemExtraFieldsValue"><?php echo $extraField->value; ?></span>
</li>
<?php **}** endforeach; ?>
i do that in my site: www.joomir.com
The problem is that $this->item->extra_fields is actually a JSON string retrieved from the database, so you have to decode it first. It's structure is rather complicated (and unfortunately each field is labelled by it's id, it's name doesn't appear at all), you'll see it if you execute:
print_r($this->item->extra_fields);`
If you want to call field values by it's field name I'd do it like this:
if ($this->item->params->get('itemExtraFields')) {
$item_extra_fields = json_decode($this->item->extra_fields);
$put_your_extra_field1_name_here = $item_extra_fields[1]->value;
$put_your_extra_field2_name_here = $item_extra_fields[2]->value;
$put_your_extra_field3_name_here = $item_extra_fields[3]->value;
$put_your_extra_field4_name_here = $item_extra_fields[4]->value;
}
Notice that this is useful if the extra field you need is text, but it can be an array or whatever so you might have to code a little bit more. Hope this is useful!
In K2 you set the parameters for how an item displays at the category level. There is an option to display the extra fields in both Item view options in category listings as well as the Item view options.
By default, the built in K2 template will display the extra fields under a heading "Additional Information" with an unordered list of field name and values. You can override that template and make the extra fields display any way you like.

Resources