Am creating a custom page using Opencart. Here am using foreach for displaying customer details.
But customer details not showing.
Following codes:
.tpl
<?php foreach($dealerData as $invoice){ ?>
<label> <b>Dealer Name:</b> <?php echo $invoice['name']; ?></label><br>
<label><b>Dealer TIN Number:</b> <?php echo $invoice['tin_number'];?></label><br>
<?php } ?>
Controller
$query13 = $this->db->query("select concat(firstname, ' ', lastname) as name, tin_number from ".DB_PREFIX."customer where customer_id='".$customer_id."'");
$dataDelar = $query13->rows;
foreach ($dataDelar as $dealer) {
$data['dealerData'][] = array(
'name' => $dealer['name'],
'tin_number' => $dealer['tin_number']
);
}
Why are you putting queries in your controller? You have models van database related functions. An foreach on the variable $invoiceData1 should work, you can see in the print_r that there is 1 array in the array. Did you put the print_r in your controller? So yes, look bellow that, maybe you are overriding $invoiceData1.
EDIT
You are not creating an empty array to put your values in:
$query13 = $this->db->query("select concat(firstname, ' ', lastname) as name, tin_number from ".DB_PREFIX."customer where customer_id='".$customer_id."'");
$dataDelar = $query13->rows;
$data['dealerData'] = [];
foreach ($dataDelar as $dealer) {
$data['dealerData'][] = array(
'name' => $dealer['name'],
'tin_number' => $dealer['tin_number']
);
}
Related
I'm developing a theme on a local development server. But when I try to get the featured image of posts into my home page, I get a 404 error due to the url appearing like this:
http://localhost:8888/crystal/%E2%80%9Dhttp:/localhost:8888/crystal/wp-
content/uploads/2018/04/restaurant-kitchen-inspired-design-ideas.png
See how the domain repeats itself?
I've checked my wp_options table in the database and it looks correct. Both "siteurl" and "home" does have the "http://" already and does not have a "/" after the url. I also already tried adding this script to my wp-config.php:
define('WP_HOME','http://localhost:8888/crystal');
define('WP_SITEURL','http://localhost:8888/crystal');
and this to my functions.php file:
update_option( 'siteurl', 'http://localhost:8888/crystal' );
update_option( 'home', 'http://localhost:8888/crystal' );
but that didn't fix it.
So far, it seems to be only happening when I try to use "wp_get_attachment_image_src( get_post_thumbnail_id()" to get the featured image.
Here is my code:
<?php
$args = array(
'post_type' => 'tournament',
'post_status' => 'publish',
'posts_per_page' => '10'
);
$tournaments_loop = new WP_Query( $args );
if ( $tournaments_loop->have_posts() ) :
while ( $tournaments_loop->have_posts() ) : $tournaments_loop
>the_post();
// Set variables
$title = get_the_title();
$description = get_the_content();
$tournament_date_time = get_field('tournament_date_time');
$location = get_field('location');
$featured_image = wp_get_attachment_image_src(
get_post_thumbnail_id(), 'full' );
$tournament_image = $featured_image[0];
// Output
?>
<div class=”tournament”>
<h3><?php echo $title; ?></h3>
<p><?php echo $tournament_date_time; ?></p>
<p><?php echo $location; ?></p>
<img src=”<?php echo $tournament_image; ?>” alt=”<?php echo
$title; ?>”>
</div>
<?php
endwhile;
wp_reset_postdata();
endif; ?>
Thank you.
My automatic generated base form class is as follows:
abstract class BaseGestorForm extends BaseFormDoctrine {
public function setup() {
$this->setWidgets(array(
'persona_fk' => new sfWidgetFormInputHidden(),
'unitat_fk' => new sfWidgetFormInputHidden(),
'baixa' => new sfWidgetFormDateTime(),
));
$this->setValidators(array(
'persona_fk' => new sfValidatorChoice(array('choices' => array($this->getObject()->get('persona_fk')), 'empty_value' => $this->getObject()->get('persona_fk'), 'required' => false)),
'unitat_fk' => new sfValidatorChoice(array('choices' => array($this->getObject()->get('unitat_fk')), 'empty_value' => $this->getObject()->get('unitat_fk'), 'required' => false)),
'baixa' => new sfValidatorDateTime(array('required' => false)),
));
$this->widgetSchema->setNameFormat('gestor[%s]');
$this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
$this->setupInheritance();
parent::setup();
}
public function getModelName() {
return 'Gestor';
}
}
In the form I added two extra fields (totes_unitats and unitats_a_gestionar). The first field is a drop down list where users select one or more choices and using jquery when a user press a button the options selected are added to unitats_a_gestionar drop down list. At the same time, these options are removed from totes_unitats list.
class GestorForm extends BaseGestorForm {
public function configure() {
unset($this['baixa']);
$this->widgetSchema['persona_fk'] = new sfWidgetFormChoice(array(
'choices' => UsuariLdap::getAllUsuaris()
));
$this->widgetSchema['totes_unitats'] = new sfWidgetFormChoice(array(
'choices' => UnitatTable::findAllUnitatsPerOrdreArray(),
'multiple' => true
));
$this->widgetSchema['unitats_a_gestionar'] = new sfWidgetFormChoice(array(
'choices' => array(),
'multiple' => true
));
$this->widgetSchema->setLabels(array(
'persona_fk' => 'Gestor',
'unitat_fk' => 'Unitat',
'totes_unitats' => 'Totes les unitats',
'unitats_a_gestionar' => 'Unitats a gestionar'
));
$this->validatorSchema->setOption('allow_extra_fields', true);
$this->validatorSchema['persona_fk'] = new sfValidatorString(array('required' => true), array('required' => 'Requerit'));
}
}
Where I find the problem is in the actions file. First of all, I call the executeNouGestor method that renders the form. Then when the user press to proceed and create the Gestor object, it calls executeValidaGestor that validates the form. This last method calls processFormGestor where there is no way to retrieve the unitats_a_gestionar extra field.
public function executeNouGestor(sfWebRequest $request) {
$this->gestorForm = new GestorForm();
}
public function executeValidaGestor(sfWebRequest $request) {
$this->forward404Unless($request->isMethod(sfRequest::POST));
$this->gestorForm = new GestorForm();
$this->processFormGestor($request, $this->gestorForm);
$this->setTemplate('nouGestor');
}
protected function processFormGestor(sfWebRequest $request, sfForm $gestorForm) {
$gestorForm->bind($request->getParameter($gestorForm->getName()), $request->getFiles($gestorForm->getName()));
if ($gestorForm->isValid()) {
var_dump($_POST);
var_dump($request->getParameterHolder()->getAll());
...
}
}
These two var_dump shows me the following information:
var_dump($_POST):
array(2) {
["gestor"]=>
array(2) {
["persona_fk"]=>
string(3) "330"
["_csrf_token"]=>
string(32) "91e18aa0570bfc7558d21ebb4b98f512"
}
["Desar"]=>
string(5) "Desar"
}
var_dump($request->getParameterHolder()->getAll()):
array(4) {
["gestor"]=>
array(2) {
["persona_fk"]=>
string(3) "330"
["_csrf_token"]=>
string(32) "91e18aa0570bfc7558d21ebb4b98f512"
}
["Desar"]=>
string(5) "Desar"
["module"]=>
string(13) "administracio"
["action"]=>
string(12) "validaGestor"
}
So, as you can see, in ["gestor"] there is no track neither totes_unitats nor unitats_a_gestionar extra form fields. I have no idea why. The way I show the form fields in the template is as usual:
<?php echo $gestorForm['persona_fk']->renderLabel(); ?>
<div class="input"><?php echo $gestorForm['persona_fk']->render(); ?></div>
<div class="error-input"><?php echo $gestorForm['persona_fk']->renderError(); ?></div>
<?php echo $gestorForm['totes_unitats']->renderLabel(); ?>
<div class="input multiple"><?php echo $gestorForm['totes_unitats']->render(); ?></div>
<div class="error-input"><?php echo $gestorForm['totes_unitats']->renderError(); ?></div>
<?php echo $gestorForm['unitats_a_gestionar']->renderLabel(); ?>
<div class="input multiple"><?php echo $gestorForm['unitats_a_gestionar']->render(); ?></div>
<div class="error-input"><?php echo $gestorForm['unitats_a_gestionar']->renderError(); ?></div>
I also add the jquery code that manage the options added or removed between the two drop down lists with multiple selection:
function afegirTreureUnitats() {
var boto_afegir = $("#btn-multiple-afegir");
var boto_treure = $("#btn-multiple-treure");
boto_afegir.click(function() {
var selectedItems = $("#gestor_totes_unitats option:selected");
var output = [];
$.each(selectedItems, function(key, e)
{
output.push('<option value="' + e.value + '">' + e.text + '</option>');
});
$("#gestor_unitats_a_gestionar").append(output.join(""));
ordenaOptionsSelect("gestor_unitats_a_gestionar");
selectedItems.remove();
});
boto_treure.click(function() {
var selectedItems = $("#gestor_unitats_a_gestionar option:selected");
var output = [];
$.each(selectedItems, function(key, e)
{
output.push('<option value="' + e.value + '">' + e.text + '</option>');
});
$("#gestor_totes_unitats").append(output.join(""));
ordenaOptionsSelect("gestor_totes_unitats");
selectedItems.remove();
});
}
function ordenaOptionsSelect(idSelect)
{
var options = $('#' + idSelect + ' option');
options.sort(function(a, b)
{
if (a.text > b.text)
return 1;
else if (a.text < b.text)
return -1;
else
return 0;
});
$('#' + idSelect).empty().append(options);
}
$(document).ready(function() {
afegirTreureUnitats();
});
The form rendered has this appearance:
https://drive.google.com/file/d/0B0Mz720p9Q_DN1RnYWIyR0pXOTQ/edit?usp=sharing
I have also found a curious fact. If I select one of the options in the drop down list, either totes_unitats or unitats_a_gestionar they are sent through POST method, but only one (if I select more than one I only can get one of the options selected).
When you use <select> elements on the form, or <input> of type radio or checkbox the browser will send their values on form submission only when the fields have any options selected.
The list of options in the <select> tag is not sent back to the server. Only the values of the options which are actually selected.
You can resolve your problem in two ways:
Either create a JS which will modify your form just before sending it and will select all the items on both your lists. This way your form will send the values and you will be able to work with them on the server side.
Other option is to add two hidden fields which will keep the lists of the options and modify these lists together with the <select> fields.
I have a table with join, and group by, so i have multiple item in the table like:
namecat nameprod
1 a
1 b
1 c
2 a
2 a
2 c
I want to display in a select drop down menu, Since is a result from a query that i have in the $products variable, I passed the it to my view
return View::make('admin.view')->with('products',$products);
Then in my admin.view
#foreach ($products as $product)
{{Form::select('categorie', array(
$product-namecat => array($product->nameprod => $product-nomeprod)))
}}
#endforeach
like this i just get a lot of drop down for each category i have. how can i do to have a drop down menu with title in bold with namecat e.g. (1) and then all the product in 1. like this in laravel docs:
Generating A Grouped List
echo Form::select('animal', array(
'Cats' => array('leopard' => 'Leopard'),
'Dogs' => array('spaniel' => 'Spaniel'),
));
I try to use 2 foreach:
#foreach ($products as $product)
#foreach ($product->namecat as $category)
{{Form::select('categorie', array(
$category => array($product->nameprod => $product-nomeprod)))
}}
#endforeach
#endforeach
but it says Trying to get property of non-object (BTW i saw someone using that kind of build inside a foreach but there's no way i can $product->namecat work inside a foreach it says Invalid argument supplied for foreach() Why?)
Actually I have in mind (in a normal programming way) something like:
echo Form::select('animal', array(
foreach ($product->nomecat as $cat)
$cat => array( foreach ($product->nameprod as $prod)
$prod => $prod
endforeach),
endforeach));
i assume your $products array looks something like
$products = [
(object) ['namecat' => 1, 'nameprod' => 'a'],
(object) ['namecat' => 1, 'nameprod' => 'b'],
(object) ['namecat' => 2, 'nameprod' => 'a'],
(object) ['namecat' => 2, 'nameprod' => 'b'],
// ...
]
for a grouped list with that $products array to work, you'd need some tweaking. an easy way would be bringing a new variable $categories into the game, that you can fill in your controller for instance.
$categories = [];
foreach ($products as $product) {
if (!isset($categories[$product->namecat])) {
$categories[$product->namecat] = [];
}
array_push($categories[$product->namecat], $product->nameprod);
}
View::make('leView')->with('categories' => $categories);
within the view:
so since $categories looks like this:
$categories[1] => ['a', 'b']
$categories[2] => ['a', 'b']
you should be able to use the Form::select
{{ Form::select('category', $categories) }}
I have a WP front end post form that I have made for my website, the Idea was to make it so artists can post up their own mixtape submissions!
So far I have managed to get the form to either use the image uploaded as the featured image OR give me the images ID so I can put it in the post content, the problem is I need both! I need the image automatically set as the thumbnail for the post and I need the ID so I can set the form to automatically put the image where I want it in the post!
So far I have located the problem to be this bit of code:
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
// $newupload returns the attachment id
}
}
I say this as, the location of this code is what changes whether I successfully get the ID of the attachment or whether the image is set as the thumbnail.
The whole code is as follows:
function insert_attachment($file_handler,$post_id,$setthumb='false') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
function mixtape_fep($content = null) {
global $post;
// We're outputing a lot of html and the easiest way
// to do it is with output buffering from php.
ob_start(); ?> <?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter the wine name';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter some notes';
}
$cover_id = get_post_meta($post->ID, 'thumb', true);
$cover = wp_get_attachment_link($cover_id);
$content = $cover.'<br /><br />'.$description;
$tags = $_POST['post_tags'];
// ADD THE FORM INPUT TO $new_post ARRAY
$new_post = array(
'post_title' => $title,
'post_content' => $content,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags),
'post_status' => 'publish', // Choose: publish, preview, future, draft, etc.
'post_type' => 'post' //'post',page' or use a custom post type if you want to
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
// $newupload returns the attachment id of the file that
// was just uploaded. Do whatever you want with that now.
}
}
//SET OUR TAGS UP PROPERLY
wp_set_post_tags($pid, $_POST['post_tags']);
//REDIRECT TO THE NEW POST ON SAVE
$link = get_permalink( $pid );
wp_redirect( $link );
} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM
//POST THE POST YO
do_action('wp_insert_post', 'wp_insert_post'); ?>
The issue of assigning the thumbnail and inserting the image was fixed by adding this into the code:
if ( $_FILES ) {
$files = $_FILES['cover'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("cover" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post->ID);
}
}
}
}
and then
set_post_thumbnail( $pid, $newupload );
below the insert post function.
I have a model that implements NestedSet behaviour:
Page:
actAs:
NestedSet:
hasManyRoots: true
rootColumnName: root_id
columns:
slug: string(255)
name: string(255)
Example fixtures:
Page:
NestedSet: true
Page_1:
slug: slug1
name: name1
Page_2:
slug: slug2
name: name2
children:
Page_3:
slug: page3
name: name3
I am looking for the easiest way to implement breadcrumb navigation (trail). For example, for Page_3 navigation will look like this:
name2 > <a href="page2/page3>name3</a>
Since I hate having any kind of logic in templates (and partials), here's my slightly improved version.
//module/templates/_breadcrumbElement.php
<?php foreach ($node as $child): ?>
<li>
<?php echo $child->getName() ?>
<?php if (count($child->get('__children')) > 0): ?>
<ul>
<?php include_partial('node', array('node' => $child->get('__children'), 'parent' => $child)) ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
So, all the logic for building a url is now in Page::getPath() method.
class Page extends BasePage
{
/**
* Full path to node from root
*
*/
protected $path = false;
public function __toString()
{
return $this->getSlug();
}
public function getPath($parent = null)
{
if (!$this->path)
{
$this->path = join('/', null !== $parent ? array($parent->getPath(), $this) : array($this));
}
return $this->path;
}
}
What I don't like it having to pass $parent to Page::getPath(). It just doesn't make any semantical sense.
Almost the same as in the other question, but you have to add a 'parentUrl' variable :
//module/templates/_breadcrumbElement.php
foreach ($node->get('__children') as $child) :
if ($child->isAncestorOf($pageNode)):
$currentNodeUrl = $parentUrl . $child->getSlug() . '/';
echo link_to($child->getName(), $currentNodeUrl) . ' > ' ;
include_partial('module/breadcrumbElement', array('node' => $child, 'pageNode' => $pageNode, 'parentUrl' => $currentNodeUrl));
endif;
endforeach;
Feed it the root of your tree as $node (hydrate it hierarchically), the node of the current page as $pageNode, and '' as $currentNodeUrl and add ' > ' and the link to the current page.
Why does this solution use recursion and not getAncestors()? Because your urls seem to imply recursion.
Another answer, more simple (and perhaps more efficient), with getAncestors() and recursion:
//module/templates/_breadcrumbElement.php
if ($node = array_pop($nodes)) // stop condition
{
$currentNodeUrl = $parentUrl . $node->getSlug() . '/';
echo link_to($node->getName(), $currentNodeUrl) . ' > ' ;
include_partial('module/breadcrumbElement', array(
'nodes' => $nodes, 'parentUrl' => $currentNodeUrl));
}
Call this with an array of ancestor nodes or find a way to pop a Doctrine_Collection if you want to use it with getAncestors() directly.
Again, all your problem comes from the fact that your urls are recursively computed, it would be simpler and faster to display if you had a colum path with the current url (but then you would have to compute, update it), etc... consider doing this if you have more reads than writes (if your tree does not change often).