register View-Helper understanding issue - zend-framework

I tried to register a View Helper for navigation, it is an example from olegkrivtsov,I chose this to learn more about the topic. I also read the posts about it. I thought it must be really easy, but it doesn't work, probably some more experienced Zend-developer will see the problem immediately.
First the folder I use, is this the right folder, what is the diffenrence to the folder helpers in the module Import for example?
Here is the content of menu.php
<?php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
// This view helper class displays a menu bar.
class Menu extends AbstractHelper
{
// Menu items array.
protected $items = [];
// Active item's ID.
protected $activeItemId = '';
// Constructor.
public function __construct($items=[])
{
$this->items = $items;
}
// Sets menu items.
public function setItems($items)
{
$this->items = $items;
}
// Sets ID of the active items.
public function setActiveItemId($activeItemId)
{
$this->activeItemId = $activeItemId;
}
// Renders the menu.
public function render()
{
if (count($this->items)==0)
return ''; // Do nothing if there are no items.
$result = '<nav class="navbar navbar-default" role="navigation">';
$result .= '<div class="navbar-header">';
$result .= '<button type="button" class="navbar-toggle" ';
$result .= 'data-toggle="collapse" data-target=".navbar-ex1-collapse">';
$result .= '<span class="sr-only">Toggle navigation</span>';
$result .= '<span class="icon-bar"></span>';
$result .= '<span class="icon-bar"></span>';
$result .= '<span class="icon-bar"></span>';
$result .= '</button>';
$result .= '</div>';
$result .= '<div class="collapse navbar-collapse navbar-ex1-collapse">';
$result .= '<ul class="nav navbar-nav">';
// Render items
foreach ($this->items as $item) {
$result .= $this->renderItem($item);
}
$result .= '</ul>';
$result .= '</div>';
$result .= '</nav>';
return $result;
}
// Renders an item.
protected function renderItem($item)
{
$id = isset($item['id']) ? $item['id'] : '';
$isActive = ($id==$this->activeItemId);
$label = isset($item['label']) ? $item['label'] : '';
$result = '';
if(isset($item['dropdown'])) {
$dropdownItems = $item['dropdown'];
$result .= '<li class="dropdown ' . ($isActive?'active':'') . '">';
$result .= '<a href="#" class="dropdown-toggle" data-toggle="dropdown">';
$result .= $label . ' <b class="caret"></b>';
$result .= '</a>';
$result .= '<ul class="dropdown-menu">';
foreach ($dropdownItems as $item) {
$link = isset($item['link']) ? $item['link'] : '#';
$label = isset($item['label']) ? $item['label'] : '';
$result .= '<li>';
$result .= ''.$label.'';
$result .= '</li>';
}
$result .= '</ul>';
$result .= '</a>';
$result .= '</li>';
} else {
$link = isset($item['link']) ? $item['link'] : '#';
$result .= $isActive?'<li class="active">':'<li>';
$result .= ''.$label.'';
$result .= '</li>';
}
return $result;
}
}
I posted the hole example for somebody who also wants to use it.
Here how I tried to register in my module.config.php
'view_helpers' => [
'factories' => [
View\Helper\Menu::class => InvokableFactory::class,
],
'aliases' => [
'mainMenu' => View\Helper\Menu::class
]
],
I placed it in the layout.phtml
<div class="collapse navbar-collapse">
<?php
$this->mainMenu()->setItems([
[
'id' => 'home',
'label' => 'Dashboard',
'link' => $this->url('home')
],
[
'id' => 'project',
'label' => 'Project',
'link' => $this->url("project", ['action'=>'index'])
],
[
'id' => 'unit',
'label' => 'Unit',
'dropdown' => [
[
'id' => 'add',
'label' => 'add Unit',
// 'link' => $this->url('unit', ['page'=>'contents'])
'link' => $this->url('unit', ['action'=>'add'])
],
[
'id' => 'help',
'label' => 'Help',
'link' => $this->url('home')
]
]
],
]);
echo $this->mainMenu()->render();
?>
</div>
With this code I replaced the former part, which came from the skeleton:
<div class="collapse navbar-collapse">
<?= $this->navigation('navigation')
->menu()
->setMinDepth(0)
->setMaxDepth(0)
->setUlClass('nav navbar-nav') ?>
I get this error message via browser:
Fatal error: Uncaught Error: Class 'Application\view\helper\Menu' not found in C:\wamp64\www\xyz\vendor\zendframework\zend-servicemanager\src\Factory\InvokableFactory.php
I'd really love to understand this because it might be really helpful in future, so any suggestion is appreciated.

Move file Menu.php to the folder Application/src/Application/View/Helper

Related

Paragraph breaks missing from shortcode output

I created a shortcode in Wordpress to perform a query and display the content, but the content line breaks are being removed.
add_shortcode( 'resource' , 'Resource' );
function Resource($atts) {
$atts = shortcode_atts( array(
'category' => ''
), $atts );
$categories = explode(',' , $atts['category']);
$args = array(
'post_type' => 'resource',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page'=> -1,
'tax_query' => array( array(
'taxonomy' => 'category',
'field' => 'term_id',
'operator' => 'AND',
'terms' => $categories
) )
);
$string = '';
$query = new WP_Query( $args );
if( ! $query->have_posts() ) {
$string .= '<p>no listings at this time...</p>';
}
while( $query->have_posts() ){
$query->the_post();
$string .= '<div id="links"><div id="linksImage">' . get_the_post_thumbnail() . '</div>
<div id="linksDetails"><h1>'. get_the_title() .'</h1><p>' . get_the_content() . '</p>
<p>for more information CLICK HERE</div></div>';
}
wp_reset_postdata();
$output = '<div id="linksWrapper">' . $string . '</div>';
return $output;
}
Any suggestion on why this is happening and what to do to fix it. This is only happening on the shortcode output. On regular pages - the content displays correctly.
found a solution through more searches:
function get_the_content_with_formatting ($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
works perfect, so I thought I would share..

bootstrap mail form $from<$email> $fromEmail

I refer to this page. https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form and i uesd index-2.html / contact-2.php files.
i want mailheader ''
but code is
**$fromEmail = 'demo#domain.com';
$fromName = 'Demo contact form';**
$sendToEmail = 'my#mail.com';
$fields = array('name' => 'Name', 'phone' => 'Phone', 'email' => 'Email', "\r\n" , 'message' => 'Message');
so i changed
$fromEmail = "$email" $fromName = '$name'; or
$fromEmail = $_POST['form_email']; $name = $_POST['name'];
but It just makes an error.
ex) Root User" '
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table>";
$mail = new PHPMailer;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->msgHTML($emailTextHtml); //
what should I do?
$fromEmail = 'demo#domain.com';
$fromName = 'Demo contact form'
How should I change it?

Drupal form api file upload using drupal_http_request

I am trying to post a file uploaded in drupal form to another server through a post request using drupal_http_request.
I am not sure where am I making a mistake but the file doesnot seem to get posted. What should I be doing.?
I use the following code.
$options = array(
'method' => 'POST',
'data' => drupal_http_build_query($data),
'timeout' => $connect_ariba_values['timeout'],
'headers' => array('Content-Type' => 'multipart/form-data'),
);
$response = drupal_http_request($url, $options);
multipart/form-data doesnot seem to work.
Source: https://drupal.org/user/194073
<?php
$boundary = md5(uniqid());
$post_data = array(
'name' => 'Ayesh',
'file' => '/var/www/test/test.png',
);
$options = array(
'method' => 'POST',
'data' => multipart_encode($boundary, $post_data),
'timeout' => $connect_ariba_values['timeout'],
'headers' => array('Content-Type' => "multipart/form-data; boundary=$boundary"),
);
$response = drupal_http_request($url, $options);
// Function to encode text data.
function multipart_enc_text($name, $value){
return "Content-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n";
}
// Function to multipart encode a file from a give path.
function multipart_enc_file($path){
if (substr($path, 0, 1) == "#") $path = substr($path, 1);
$filename = basename($path);
$mimetype = "application/octet-stream";
$data = "Content-Disposition: form-data; name=\"file\"; filename=\"$filename\"\r\n"; // "file" key.
$data .= "Content-Transfer-Encoding: binary\r\n";
$data .= "Content-Type: $mimetype\r\n\r\n";
$data .= file_get_contents($path) . "\r\n";
return $data;
}
// base function to encode a data array.
function multipart_encode($boundary, $params){
$output = "";
foreach ($params as $key => $value){
$output .= "--$boundary\r\n";
if ($key == 'file'){
$output .= multipart_enc_file($value);
} else $output .= multipart_enc_text ($key, $value);
}
$output .="--$boundary--";
return $output;
}
In the server, file will be available in $_FILES['file'], and other POST data will be available in their relevant keys.
I didn't test the code. I just found the code in drupal forum, changed it to work with Drupal 6 and 7.

Zend-Image Uploading at Wrong Destination

please help..I'm newbies and try to learn Zend Framework, but have problem when uploading image.
The script at file Application.ini
uploads.uploadPath = APPLICATION_PATH "/../public/uploads"
Form to upload Image:
$this->setAction('/data/personil/create')
->setMethod('post');
//Item input untuk gambar
$images = new Zend_Form_Element_File('images');
$images->setMultiFile(3)
->addValidator('IsImage')
->addValidator('Size', false, '204800')
->addValidator('Extension', false, 'jpg,png,gif')
->addValidator('ImageSize', false, array(
'minwidth' => 150,
'minheight' => 150,
'maxwidth' => 700,
'maxheight' => 700
))
->setValueDisabled(true);
// attach element to form
$this->addElement($images);
// create display group for file elements
$this->addDisplayGroup(array('images'), 'files');
$this->getDisplayGroup('files')
->setOrder(40)
->setLegend('Images');
Controller action create :
public function createAction()
{
$form = new Pengadilan_Form_PersonilCreate();
$this->view->form = $form;
$flashMessenger = $this->_helper->FlashMessenger;
//SImpan kedatabase
if($this->getRequest()->isPost()){
if($form->isValid($this->getRequest()->getPost())){
$personil = new Pengadilan_Model_Personil();
$personil->fromArray($form->getValues());
$personil->RecordDate = date('Y-m-d', mktime());
$personil->DisplayStatus = 0;
$personil->DisplayUntil = null;
$personil->save();
$id = $personil->RecordId;
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
$form->images->setDestination($config['uploadPath']);
$adapter = $form->images->getTransferAdapter();
for($x=0; $x<$form->images->getMultiFile(); $x++) {
$xt = #pathinfo($adapter->getFileName('images_'.$x.'_'), PATHINFO_EXTENSION);
$adapter->clearFilters();
$adapter->addFilter('Rename', array(
'target' => sprintf('%d_%d.%s', $id, ($x+1), $xt),
'overwrite' => true
));
$adapter->receive('images_'.$x.'_');
}
$this->_helper->getHelper('FlashMessenger')->addMessage('Data sekses diinput ke database #' . $id . '. Admin akan segera merivew, jika diterima, akan ditampilkan dalam waktu 48 jam, Terima kasih.');
$this->_redirect('/data/personil/sukses');
}
}
}
Controller action display :
public function displayAction()
{
//Pertama setting filters
$filters = array(
'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
);
$validators = array(
'id' => array('NotEmpty', 'Int')
);
$input = new Zend_Filter_Input($filters, $validators);
$input->setData($this->getRequest()->getParams());
if($input->isValid()){
$q = Doctrine_Query::create()
->from('Pengadilan_Model_Personil p')
->leftJoin('p.Pengadilan_Model_Jabatan j')
->leftJoin('p.Pengadilan_Model_Tupoksi t')
->leftJoin('p.Pengadilan_Model_Golongan g')
->leftJoin('p.Pengadilan_Model_Agama a')
->leftJoin('p.Pengadilan_Model_Kelamin k')
->where('p.RecordId = ?', $input->id)
->addWhere('p.DisplayStatus = 1')
->addWhere('p.DisplayUntil >= CURDATE()');
$result = $q->fetchArray();
if(count($result) == 1){
$this->view->personil = $result[0];
$this->view->images = array();
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
foreach (glob("{$config['uploadPath']}/{$this->view->item['RecordID']}_*") as $file) {
$this->view->images[] = basename($file);
}
}else{
throw new Zend_Exception('Maaf, halaman tidak ditemukan, 404');
}
}else{
throw new Zend_Exception('Kesalahan Input');
}
}
The last script at view : display.phtml
<div id="images">
<?php foreach ($this->images as $image): ?>
<img src="/uploads/<?php echo $this->escape($image); ?>" width="150" height="150" />
<?php endforeach; ?>
Image upload Destination at config is /public/uploads
in my case image at /public
Image succes to upload and renamed but outside the directory and
Image won't displayed at display.phtml
Many thanks for your help..
First you need to set your form encoding File element link$form->setAttrib('enctype', 'multipart/form-data');
Also you should probably finish setting up your image element before you POST the form not after. So move the setDestination stuff up to where you initialize the form, you may have a better chance of it working.
public function createAction()
{
$form = new Pengadilan_Form_PersonilCreate();
//set form encoding
$form->setAttrib('enctype', 'multipart/form-data');
//get path and set destination for image element
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
$form->images->setDestination($config['uploadPath']);
$this->view->form = $form;
//consider intializing flash messenger in the init() method
$flashMessenger = $this->_helper->FlashMessenger;
//SImpan kedatabase
if($this->getRequest()->isPost()){
if($form->isValid($this->getRequest()->getPost())){
//more code...
$adapter = $form->images->getTransferAdapter();
for($x=0; $x<$form->images->getMultiFile(); $x++) {
$xt = #pathinfo($adapter->getFileName('images_'.$x.'_'), PATHINFO_EXTENSION);
$adapter->clearFilters();
$adapter->addFilter('Rename', array(
'target' => sprintf('%d_%d.%s', $id, ($x+1), $xt),
'overwrite' => true
));
$adapter->receive('images_'.$x.'_');
}
$this->_helper->getHelper('FlashMessenger')->addMessage('Data sekses diinput ke database #' . $id . '. Admin akan segera merivew, jika diterima, akan ditampilkan dalam waktu 48 jam, Terima kasih.');
$this->_redirect('/data/personil/sukses');
}
}
}
not sure if this will fix everything but it should be a start...

zend-form select optgroup, how to specify id

Hello i am using Zend Framework Form and have tried to get this example to work http://framework.zend.com/issues/browse/ZF-8252, but it fails xD
this is my code
$options = Array
(
[] => Qualsiasi Agente
[agenti_attivi] => Array
(
[4] => Giovanni Abc
[10] => Luigi Abc
[13] => Michela Abc
)
);
$agenti->addMultiOptions($options);
and the generated code is :
<select name="agente_id" id="agente_id" tabindex="6">
<option value="" label="Qualsiasi Agente" selected="selected">Qualsiasi Agente</option>
<optgroup id="agente_id-optgroup-Agenti attivi: " label="Agenti attivi: ">
<option value="4" label="Giovanni Abc">Giovanni Abc</option>
<option value="10" label="Luigi Capoarea">Luigi Abc</option>
<option value="13" label="Michela Abc">Michela Abc</option>
</optgroup>
</select>
where id="agente_id-optgroup-Agenti attivi: " is not xhtml valid Line 724, Column 44: value of attribute "id" must be a single token
i am using zend 1.11.10
thanks
Create a custom view helper FormSelect that extends the core FormSelect and then modify the code.
Include the path to your view helpers in the bootstrap file
protected function _initHelpers()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
The custom view helper. It's a copy of Zend_View_Helper_FormSelect but with small modification.
class My_View_Helper_FormSelect extends Zend_View_Helper_FormSelect
{
public function formSelect($name, $value = null, $attribs = null,
$options = null, $listsep = "<br />\n")
{
$info = $this->_getInfo($name, $value, $attribs, $options, $listsep);
extract($info); // name, id, value, attribs, options, listsep, disable
// force $value to array so we can compare multiple values to multiple
// options; also ensure it's a string for comparison purposes.
$value = array_map('strval', (array) $value);
// check if element may have multiple values
$multiple = '';
if (substr($name, -2) == '[]') {
// multiple implied by the name
$multiple = ' multiple="multiple"';
}
if (isset($attribs['multiple'])) {
// Attribute set
if ($attribs['multiple']) {
// True attribute; set multiple attribute
$multiple = ' multiple="multiple"';
// Make sure name indicates multiple values are allowed
if (!empty($multiple) && (substr($name, -2) != '[]')) {
$name .= '[]';
}
} else {
// False attribute; ensure attribute not set
$multiple = '';
}
unset($attribs['multiple']);
}
// now start building the XHTML.
$disabled = '';
if (true === $disable) {
$disabled = ' disabled="disabled"';
}
// Build the surrounding select element first.
$xhtml = '<select'
. ' name="' . $this->view->escape($name) . '"'
. ' id="' . $this->view->escape($id) . '"'
. $multiple
. $disabled
. $this->_htmlAttribs($attribs)
. ">\n ";
// build the list of options
$list = array();
$translator = $this->getTranslator();
foreach ((array) $options as $opt_value => $opt_label) {
if (is_array($opt_label)) {
$opt_disable = '';
if (is_array($disable) && in_array($opt_value, $disable)) {
$opt_disable = ' disabled="disabled"';
}
if (null !== $translator) {
$opt_value = $translator->translate($opt_value);
}
$opt_id = ' id="' . $this->formatElementId($id . '-optgroup-' . $opt_value) . '"';
$list[] = '<optgroup'
. $opt_disable
. $opt_id
. ' label="' . $this->view->escape($opt_value) .'">';
foreach ($opt_label as $val => $lab) {
$list[] = $this->_build($val, $lab, $value, $disable);
}
$list[] = '</optgroup>';
} else {
$list[] = $this->_build($opt_value, $opt_label, $value, $disable);
}
}
// add the options to the xhtml and close the select
$xhtml .= implode("\n ", $list) . "\n</select>";
return $xhtml;
}
private function formatElementId($id)
{
// in here put whatever filter you want for the id value
$id = trim(strtr($id, array('[' => '-', ']' => '', ' ' => '', ':' => '')), '-');
$id = strtolower($id);
return $id;
}
}
Done. Create multi select element with a valid id.
<?php
$this->addElement('multiSelect', 'agente_id', array(
'label' => 'Label Name:',
'multiOptions' => array(
'' => 'Qualsiasi Agente',
'Agenti attivi: ' => array(
4 => 'Giovanni Verdi',
10 => 'Luigi Capoarea',
13 => 'Michela Passarin',
)
)
));
try this, it's works for me:
$select = new Zend_Form_Element_Select('select');
$options = Array(
'' => 'Qualsiasi Agente',
'agenti_attivi' => Array(
4 => 'Giovanni Verdi',
10 => 'Luigi Capoarea',
13 => 'Michela Passarin'
)
);
$this->addElements(array($xxxx,$select,$yyyy)); // $this : the form instance
and the result is:
<select id="select" name="select">
<option label="Qualsiasi Agente" value="">Qualsiasi Agente</option>
<optgroup label="agenti_attivi">
<option label="Giovanni Verdi" value="4">Giovanni Verdi</option>
<option label="Luigi Capoarea" value="10">Luigi Capoarea</option>
<option label="Michela Passarin" value="13">Michela Passarin</option>
</optgroup>
</select>
the problem is that the id attribute does not accept spaces and special special characters:
id="agente_id-optgroup-Agenti attivi: "
Zend is usually pretty good about rendering the proper html, given a doctype.
Try setting your doctype like this if you aren't already.
<?php
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->initView();
$viewRenderer->view->doctype('XHTML1_STRICT');
AND
<?php echo $this->doctype(); ?>
at the top of your layout
I don't have a install of ZF i can mess with easy, if this doesn't work ill setup a test environment.