This is again an understanding issue, any explanation is appreciated:
I before had the issue to show a foreignkey table in my view, that now works, it looks like follows:
That's quite what I wanted, but:
I only get the first row, but there are of course several in the second collection (it is the row with filename).
It is because of my method in my model, which looks like follows:
public function getImportU($unitid)
{
$unitid = (int) $unitid;
$rowset = $this->tableGateway->select(['UnitID' => $unitid]);
$row = $rowset->current();
if (! $row) {
return null;
}
else{
return $row;
}
}
Of course I have a row object and it returns the current row. So I thought, ok I will try with a rowset, after that it looked like this:
public function getImportU($unitid)
{
$unitid = (int) $unitid;
$rowset = $this->tableGateway->select(['UnitID' => $unitid]);
//$row = $rowset->current();
if (! $rowset) {
return null;
}
else{
return $rowset;
}
}
I got some errors which said:
Notice: Undefined property: Zend\Db\ResultSet\ResultSet::$Importdate in
Blockquote
So how to get a recordcollection, all records there are in the table with the same unitid? And how to call them in the view. It is probably not a big deal, but I couldn't find anything usable in the documentation.
EDIT1: Adding related code.
Here I pass the ViewModel within my Controller indexAction:
return new ViewModel([
'projects' => $this->projectTable->fetchAll(),
'dcls' => $this->table,
//'id' =>$this->authService,
]);
And here a snippet of my index.phtml:
foreach ($projects as $project) :
//var_dump(get_object_vars($project));
?>
<tr>
<td><?= $project['Projectname']?></td>
<td><?= $project['ProjectShortcut']?></td>
<td><?= $project['ProjectCiNumber']?></td>
<td><?= $project['Unitname']?></td>
<td><?= $project['UnitShortcut']?></td>
<td><?= $project['UnitCiNumber']?></td>
<td><?= $project['UnitID']?></td>
</tr>
<?php
$dclsx=$dcls->getImportU($project['UnitID']);
// var_dump($dclss);
if ( empty ($dclsx)==false){ ?>
<tr>
<th></th>
<th>filename</th>
<th>importdate</th>
<th>importuser</th>
<th>importok</th>
</tr>
<?php
$dclss=array($dclsx);
// var_dump($dclss);
foreach ( $dclss as $dcl) :
?>
<tr>
<td> </td>
<td><?= $dcl->filename?></td>
<td><?= $dcl->Importdate?></td>
<td><?= $dcl->Importuser?></td>
</tr>
?php
endforeach;
}
endforeach; ?>
I believe you are pretty close to the solution.
"getImportU" returning a rowset is the correct solution as I see it:
public function getImportU($unitid)
{
$unitid = (int) $unitid;
$rowset = $this->tableGateway->select(['UnitID' => $unitid]);
if (! $rowset) {
return null;
}
else{
return $rowset;
}
}
Your view should be changed from:
<?php
$dclss=array($dclsx);
// var_dump($dclss);
foreach ( $dclss as $dcl) :
to:
<?php
foreach ( $dclsx as $dcl) :
$dclsx is a resultset and can be iterated, it does not make sense to put it in an array.
Your error also suggests that "Importdate" cannot be found in the blockquote table.
Please check if the column exists at the table(also check the name is case sensitive, is it "Importdate", "importdate" or "importDate"?)
Related
I implemented Isotope.js into my WordPress site. I use it to display gallery with Easy Fancybox plugin to add zooming functionality for images. Problem is with Isotope filtering. I added rel attribute to my images but when I filter categories Fancybox still cycles through all images.
I need to add rel attribute dynamically based on category I'm filtering. I'm struggling with this problem for 3 days now. I've read bunch of post, tried view things but still can't make it work.
Most of posts give solution with data-fancybox-group attribute but I can't use it I must use rel attribute (it doesn't work for me anyway).
Here's my WP code:
<ul id="filters">
<li>All</li>
<?php
$terms = get_terms("polygraphy-categories");
$count = count($terms);
if ( $count > 0 ){
foreach ( $terms as $term ) {
echo "<li><a class='filterbutton' href='#' data-filter='.".$term->slug."'>" . $term->name . "</a></li>\n";
}
}
?>
</ul>
<?php $the_query = new WP_Query( 'post_type=polygraphy' ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<div id="isotope-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$termsArray = get_the_terms( $post->ID, "polygraphy-categories" );
$termsString = "";
foreach ( $termsArray as $term ) {
$termsString .= $term->slug.' ';
}
?>
<div class="<?php echo $termsString; ?> poli">
<?php
if ( has_post_thumbnail()) {
$full_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full');
echo '<a class="fancybox" href="' . $full_image_url[0] . '" title="' . the_title_attribute('echo=0') . '" >';
the_post_thumbnail('thumbnail');
echo '</a>';
}
?>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
And JS code:
jQuery(function ($) {
$(window).load(function(){
var $container = $('#isotope-list');
$container.isotope({
itemSelector : '.poli',
layoutMode : 'masonry'
});
var $optionSets = $('#filters'),
$optionLinks = $optionSets.find('a');
$optionLinks.click(function(){
var $this = $(this);
if ( $this.hasClass('selected') ) {
return false;
}
var $optionSet = $this.parents('#filters');
$optionSets.find('.selected').removeClass('selected');
$this.addClass('selected');
var selector = $(this).attr('data-filter');
$container.isotope({ filter: selector });
return false;
});
});
});
I was told that this code should work but it doesn't:
$('.filterbutton').on("click", function(){
var selector = $(this).attr('data-filter');
if(selector == "*"){
$(".fancybox").attr("rel", "gallery");
} else{
$(selector).find(".fancybox").attr("rel", selector);
}
return false;
});
I'm working on a Yii project with a database, that contains a table, where almost all it's data is saved in a field as JSON (it's crazy, but it is so as it is):
id INTEGER
user_id INTEGER
data LONGTEXT
This "JSON field" data has following structure and contains inter alia an image:
{
"id":"1",
"foo":"bar",
...
"data":{
"baz":"buz",
...
}
}
Displaying it is no problem, but now I want to make the data ediable. My form looks like this:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'my-form',
'htmlOptions' => array('enctype' => 'multipart/form-data'),
'enableAjaxValidation'=>false,
));
?>
<div class="row">
<?php echo $form->labelEx($model, 'foo'); ?>
<?php
echo $form->textField($model, 'foo', array(...));
?>
<?php echo $form->error($model, 'foo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'baz'); ?>
<?php
echo $form->textField($model, 'data[baz]', array(...));
?>
<?php echo $form->error($model, 'data[baz]'); ?>
</div>
It works. But there are multiple problems, that seem to be caused by the same thing -- that he form fields are not referenced to the model attributes/properties:
When I make fields foo and baz required (public function rules() { return array(array('foo, baz', 'required')); } -- the property $foo is defined) foo bahaves as wished, but baz causes an "foo cannot be blank" error. So I cannot set a data[*] as required.
If the form is not valid and gets reloaded, all the data[*] fields are empty.
The data[*] fields are not marked as required.
Is there a to solve this without to change the datase structure? There will not be a correct way for it, but maybe a workaround.
It's impossible to validate fields in such way. First of all if you are using field in model it must be defined or exist in table for active record. So if you want to validate such structure the only right way to do it:
class Model extends CActiveRecord {
// Define public varialble
public $data_baz;
public function rules(){
return array(
// Add it to rules
array( 'data_baz', 'required' )
);
}
public function attributeLabels(){
return array(
// Add it to list of labels
'data_baz' => 'Some field'
);
}
protected function beforeSave(){
if ( !parent::beforeSave() ) {
return false;
}
// Also you may create a list with names to automate append
$this->data['baz'] = $this->data_baz;
// And serialize data before save
$this->data = serialize( $this->data );
return true;
}
}
And your form should looks like
<div class="row">
<?php echo $form->labelEx($model, 'data_baz'); ?>
<?php echo $form->textField($model, 'data_baz'); ?>
<?php echo $form->error($model, 'data_baz'); ?>
</div>
I'm working on a Yii project with a database, containing a table, where almost all it's data is saved in a field as JSON (it's crazy, but it is so as it is):
id INTEGER
user_id INTEGER
data LONGTEXT
This "JSON field" data has following structure and contains inter alia an image:
{
"id":"1",
"foo":"bar",
...
"bat":{
"baz":"buz",
"name":"Joe Doe",
"my_picture":"iVBORw0KGgoAAAANSUhEUgAAAGQA...", <-- binary
...
}
}
Displaying it is no problem, but now I want to make the data ediable. My form looks like this:
<?php
$form=$this->beginWidget('CActiveForm', array(
'id' => 'insurance-form',
'htmlOptions' => array('enctype' => 'multipart/form-data'),
'enableAjaxValidation'=>false,
));
?>
<div class="row">
<?php echo $form->labelEx($model, 'provider_name'); ?>
<?php
echo $form->textField($model, 'data[provider][name]', array(
'size'=>60, 'maxlength'=>255, "autocomplete"=>"off"
));
?>
<?php echo $form->error($model, 'data[provider][name]'); ?>
</div>
It works.
I know, that for image upload I need fileField(...), but cannot find out, how to configure it in order to save the image directly to the database. How to do his?
view
<div class="row">
<?php echo $form->labelEx($model, 'provider_name'); ?>
<?php
echo $form->fileField($model, 'data[provider][name]', array());
?>
<?php echo $form->error($model, 'data[provider][name]'); ?>
</div>
controller
public function actionUpdate($id)
{
$model = $this->loadModel($id);
if(isset($_POST['External'])) {
$modelDataArray = $model->data;
// adding the image as string to the POSted data
if (isset($_FILES['MyModel']['name']['data']['provider']['picture'])) {
$_POST['MyModel']['data']['provider']['picture'] = base64_encode(
file_get_contents($_FILES['MyModel']['tmp_name']['data']['provider']['picture'])
);
}
$inputFieldData = $_POST['MyModel']['data'];
$updatedDataArray = array_replace_recursive($modelDataArray, $inputFieldData);
$model->attributes = $_POST['MyModel'];
$updatedDataJson = json_encode($updatedDataArray);
$model->setAttribute('data', $updatedDataJson);
if($model->save()) {
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('update', array(
'model' => $model,
));
}
CActiveRecord model
no special changes
I think I have just been working too long and am tired. I have an application using the Zend Framework where I display a list of clubs from a database. I then want the user to be able to click the club and get the id of the club posted to another page to display more info.
Here's the clubs controller:
class ClubsController extends Zend_Controller_Action
{
public function init()
{
}
public function indexAction()
{
$this->view->assign('title', 'Clubs');
$this->view->headTitle($this->view->title, 'PREPEND');
$clubs = new Application_Model_DbTable_Clubs();
$this->view->clubs = $clubs->fetchAll();
}
}
the model:
class Application_Model_DbTable_Clubs extends Zend_Db_Table_Abstract
{
protected $_name = 'clubs';
public function getClub($id) {
$id = (int) $id;
$row = $this->fetchRow('id = ' . $id);
if (!$row) {
throw new Exception("Count not find row $id");
}
return $row->toArray();
}
}
the view:
<table>
<?php foreach($this->clubs as $clubs) : ?>
<tr>
<td><a href=''><?php echo $this->escape($clubs->club_name);?></a></td>
<td><?php echo $this->escape($clubs->rating);?></td>
</tr>
<?php endforeach; ?>
</table>
I think I am just getting confused on how its done with the zend framework..
in your view do this
<?php foreach ($this->clubs as $clubs) : ?>
...
<a href="<?php echo $this->url(array(
'controller' => 'club-description',
'action' => 'index',
'club_id' => $clubs->id
));?>">
...
That way you'll have the club_id param available in index action of your ClubDescription controller. You get it like this $this->getRequest()->getParam('club_id')
An Example:
class ClubsController extends Zend_Controller_Action
{
public function init()
{
}
public function indexAction()
{
$this->view->assign('title', 'Clubs');
$this->view->headTitle($this->view->title, 'PREPEND');
$clubs = new Application_Model_DbTable_Clubs();
$this->view->clubs = $clubs->fetchAll();
}
public function displayAction()
{
//get id param from index.phtml (view)
$id = $this->getRequest()->getParam('id');
//get model and query by $id
$clubs = new Application_Model_DbTable_Clubs();
$club = $clubs->getClub($id);
//assign data from model to view [EDIT](display.phtml)
$this->view->club = $club;
//[EDIT]for debugging and to check what is being returned, will output formatted text to display.phtml
Zend_debug::dump($club, 'Club Data');
}
}
[EDIT]display.phtml
<!-- This is where the variable passed in your action shows up, $this->view->club = $club in your action equates directly to $this->club in your display.phtml -->
<?php echo $this->club->dataColumn ?>
the view index.phtml
<table>
<?php foreach($this->clubs as $clubs) : ?>
<tr>
<!-- need to pass a full url /controller/action/param/, escape() removed for clarity -->
<!-- this method of passing a url is easy to understand -->
<td><a href='/index/display/id/<?php echo $clubs->id; ?>'><?php echo $clubs->club_name;?></a></td>
<td><?php echo $clubs->rating;?></td>
</tr>
<?php endforeach; ?>
an example view using the url() helper
<table>
<?php foreach($this->clubs as $clubs) : ?>
<tr>
<!-- need to pass a full url /controller/action/param/, escape() removed for clarity -->
<!-- The url helper is more correct and less likely to break as the application changes -->
<td><a href='<?php echo $this->url(array(
'controller' => 'index',
'action' => 'display',
'id' => $clubs->id
)); ?>'><?php echo $clubs->club_name;?></a></td>
<td><?php echo $clubs->rating;?></td>
</tr>
<?php endforeach; ?>
</table>
[EDIT]
With the way your current getClub() method in your model is built you may need to access the data using $club['data']. This can be corrected by removing the ->toArray() from the returned value.
If you haven't aleady done so you can activate error messages on screen by adding the following line to your .htaccess file SetEnv APPLICATION_ENV development.
Using the info you have supplied, make sure display.phtml lives at application\views\scripts\club-description\display.phtml(I'm pretty sure this is correct, ZF handles some camel case names in a funny way)
You can put the club ID into the URL that you link to as the href in the view - such as /controllername/club/12 and then fetch that information in the controller with:
$clubId = (int) $this->_getParam('club', false);
The 'false' would be a default value, if there was no parameter given. The (int) is a good practice to make sure you get a number back (or 0, if it was some other non-numeric string).
I an using zend db table models for backend crud operations. However I think the model like this is meaningless for my front end data display like news by category , news and blog widgets and etc from various table or joining various table.
class Bugs extends Zend_Db_Table_Abstract {
protected $_name = 'bugs'; }
Model this way is perfect for my backend admin panel crud operation, How would i create model for front end operation, any example would be highly appreceated. Thanks
You can join on other tables even with a Zend_Db_Table-derived model. Just be sure to turn off integrity check.
Code (not tested) could look something like this:
class My_Model_News extends Zend_Db_Table
{
// Hate the 'tbl_' prefix. Just being explicit that this is a
// table name.
protected $_name = 'tbl_news';
public function fetchNewsByAuthor($authorId)
{
$select = $this->select();
$select->setIntegrityCheck(false)
->from(array('n' => 'tbl_news'), array('*'))
->join(array('a' => 'tbl_author'), array('n.author_id = a.id'), array('author_name' => 'a.name'))
->order('n.date_posted DESC');
return $this->fetchAll($select);
}
}
Then in your controller:
$authorId = $this->_getParam('authorId');
$newsModel = new My_Model_News();
$this->view->articles = $newsModel->fetchNewsByAuthor($authorId);
Truth be told, that's one of the things that leaves me flat about most TableGateway approaches, like Zend_Db_Table. I find that TableGateway is great for single-table queries, but I find that most of my real-life situations require multi-tables. As a result, I end up creating models that are not tied to a single table, but rather accept a Zend_Db_Adapter instance and then query/join whatever tables they need. Or, I push out to more complex ORM's, like Doctrine.
I think what you are asking about in ZF would be a View Helper, A view helper takes data from your models and allows you to dump it to the view without having to process it in the controller. Here is a simple example:
<?php
class Zend_View_Helper_Track extends Zend_View_Helper_Abstract
{
/**
*
* #param type $trackId
* #return type object
*/
public function Track($trackId) {
//this model just aggregates data from several DbTable models
$track = new Application_Model_TrackInfo();
$data = $track->getByTrackId($trackId);
return $data;
}
}
view helpers are characterized by returning some data (object, string, array, boolean) and can be used to supply data to views and partials.
The following is an example of a partial that uses several view helpers to present data in view.
<fieldset><legend>Dates and Qualifications</legend>
<table>
<tr>
<td>Birth Date: </td><td><?php echo $this->escape($this->FormatDate($this->bdate)) ?></td>
</tr>
<tr>
<td>Seniority Date: </td><td><?php echo $this->escape($this->FormatDate($this->sendate)) ?></td>
</tr>
</table>
<table>
<tr>
<td>I'm a Lead:</td><td><?php echo $this->escape(ucfirst($this->ToBool($this->lead))) ?></td>
</tr>
<tr>
<td>Lead Date:</td><td><?php echo $this->escape($this->FormatDate($this->ldate)) ?></td>
</tr>
<tr>
<td>I'm an Inspector:</td><td><?php echo $this->escape(ucfirst($this->toBool($this->inspector))) ?></td>
</tr>
<tr>
<td>Admin Login:</td><td><?php echo $this->escape(ucfirst($this->toBool($this->admin))) ?></td>
</tr>
</table>
</fieldset>
and finally I call this partial in a view with:
<?php echo $this->partial('_dates.phtml', $this->memberData) ?>
as far as DbTable models being useless for the frontend, you might be surprised. Once you have established the relationships between your tables properly in your DbTable classes the functionality of what they can do goes way up. However if you are like most people you will likely have at least one layer of domain models (mappers, service, repository) between your DbTable classes and your application.
This is a model with relationships, it's sole purpose is to supply the data to build navigation.
<?php
class Application_Model_DbTable_Menu extends Zend_Db_Table_Abstract {
protected $_name = 'menus';
protected $_dependentTables = array('Application_Model_DbTable_MenuItem');
protected $_referenceMap = array(
'Menu' => array(
'columns' => array('parent_id'),
'refTableClass' => 'Application_Model_DbTable_Menu',
'refColumns' => array('id'),
'onDelete' => self::CASCADE,
'onUpdate' => self::RESTRICT
)
);
public function createMenu($name) {
$row = $this->createRow();
$row->name = $name;
return $row->save();
}
public function getMenus() {
$select = $this->select();
$select->order('name');
$menus = $this->fetchAll($select);
if ($menus->count() > 0) {
return $menus;
} else {
return NULL;
}
}
public function updateMenu($id, $name) {
$currentMenu = $this->find($id)->current();
if ($currentMenu) {
//clear the cache entry for this menu
$cache = Zend_Registry::get('cache');
$id = 'menu_' . $id;
$cache->remove($id);
$currentMenu->name = $name;
return $currentMenu->save();
} else {
return FALSE;
}
}
public function deleteMenu($menuId) {
$row = $this->find($menuId)->current();
if ($row) {
return $row->delete();
} else {
throw new Zend_Exception("Error loading menu...");
}
}
}
Zend_Db_Table_Abstract supplies the interface for several data access patterns and you just have to supply the business logic and whatever level of abstraction you want.