Rendering only the <form> tag - zend-framework

Is there any way that i can render ONLY the start <form> tag of a Zend_Form object?
print $this->registerForm->renderForm();
renders <form></form>, and i only need <form>
Edit:
After Asleys possible solution i wrote this for My_Form class
public function renderFormOpen() {
return str_replace('</form>', '', $this->renderForm());
}
public function renderFormClose() {
return '</form>';
}
Still looking for at ZF way of doing thins, even though i don't think there is any - after going through the code in the ZF library.

You could write an custom form-decorator that uses a custom view-helper that only renders the open form tag. But I think this would be overkill.
Just "hardcode" the form-tags and fill the attributes with the data provided by the form-variable in your view.
<!--in your view-template -->
<form action="<?php echo $this->form->getAction() ?>"
enctype="<?php echo $this->form->getEnctype() ?>"
method="<?php echo $this->form->getMethod() ?>"
id="<?php echo $this->form->getId() ?>"
class="<?php echo $this->form->getAttrib('class') ?>" >
<!--in case your products are represented as elements -->
<?php foreach ($this->form->getElements() as $element): ?>
<?php echo $element ?>
<?php endforeach; ?>
<!--in case your products are represented as displayGroups -->
<?php foreach ($this->form->getDisplayGroups() as $displayGroup): ?>
<?php echo $displayGroup ?>
<?php endforeach; ?>
<!--in case your products are represented as subforms -->
<?php foreach ($this->form->getSubforms() as $subform): ?>
<?php echo $subform ?>
<?php endforeach; ?>
<!--in case your products are rendered by a view helper -->
<?php foreach ($this->products as $product): ?>
<?php echo $this->renderProduct($product) ?>
<?php endforeach; ?>
</form>
Just for fun the overkill way
// Get your products form
$form = new Form_Products();
// Add custom prefix path
$form->addPrefixPath('Foobar_Form_Decorator', 'Foobar/Form/Decorator', 'decorator');
// Set OnlyOpenTagForm-ViewHelper for FormDecorator
$form->getDecorator('Form')->setHelper('OnlyOpenTagForm');
// copy Zend/View/Helper/Form to Foobar/Form/Decorato/OnlyOpenTagForm.php
// In OnlyOpenTagForm.php
// replace Zend_View_Helper_Form with Foobar_View_Helper_OnlyOpenTagForm
// replace method "form" with onlyOpenTagForm"
// replace
if (false !== $content) {
$xhtml .= $content
. '</form>';
}
// with:
if (false !== $content) {
$xhtml .= $content;
}
Done! - The Java-Guys will love it ;)

You can render just the open form tag by passing false to the form decorator like so:
<?php echo $this->form->renderForm(false) ?>
Which will output something like:
<form id="post" enctype="multipart/form-data" method="post" action="/post">
Additonally you can pass a string to the form decorator to be enclosed by the form tags like so:
<?php echo $this->form->renderForm('Some Text') ?>
Which outputs something like:
<form id="post" enctype="multipart/form-data" method="post" action="/simchas/post">Some Text</form>
Hope this helps...

You could do something like this:
echo $this->form->getDecorator('Form')->setElement($this->form)->render(false);

Related

facebook status on web with picture

Finally i got this done with the likes and statuses but I would like to ask for help if it is possible somehow to transfer also the pictures on web.
thank you
<?php
$facebook_page_id = '**********';
$access_token = '************';
$number_of_posts = 2;
$json_content = file_get_contents('http://graph.facebook.com/'.$facebook_page_id.'/feed?access_token='.$access_token);
$raw_data = json_decode($json_content);
$i=0;
foreach ($raw_data->data as $feed ) {
$feed_id = explode("_", $feed->id);
if (!empty($feed->message)) {
$i++;
if ($i<($number_of_posts+1)) {
?>
<div class=”fb_update”>
<?php if (!empty($feed->likes->count)) { ?>
<div class=”fb_likes”>
<?php echo $feed->likes->count; ?>
</div>
<?php } ?>
<?php if (!empty($feed->created_time)) { ?>
<div class=”fb_date”>
<?php echo date('F j, Y', strtotime($feed->created_time)); ?>
</div>
<?php } ?>
<div class=”fb_message”>
<?php echo $feed->message; ?>
</div>
</div>
<?php } ?>
<?php } ?>
<?php } ?>
Yes, $feed->picture will get you the URL to an image for a particular item, if it exists.
You should really look at using cURL via the PHP SDK for this instead of file_get_contents(). It is more robust.

Show post title and custom fields in sidebar with shortcode in widget - Wordpress

I would like to show certain data in the HTML/text widget with shortcodes.
I already made the include php call in my functions.php:
function event_widget($atts) {
// turn on output buffering to capture script output
ob_start();
// include file (contents will get saved in output buffer)
include("wp-content/themes/mytheme/widgets/event.php");
// save and return the content that has been output
$content = ob_get_clean();
return $content;
}
//register the Shortcode handler
add_shortcode('event', 'event_widget');
It gets the data to the widget if I put just plain text to event.php, so the call is done correctly, but I don't know how to write the event.php to get this data:
// the loop
<?php if (have_posts()) :
while (have_posts()) : the_post(); ?>
<ul>
<li>
<?php if( get_post_meta($post->ID, "customfield1", true) ): ?>
<?php echo get_post_meta($post->ID, "customfield1", true); ?>
<?php endif; ?>
</li>
<li>
<?php if( get_post_meta($post->ID, "customfield2", true) ): ?>
<?php echo get_post_meta($post->ID, "customfield2", true); ?>
<?php endif; ?>
</li>
</ul>
Try this:
global $post;
echo get_post_meta($post->ID, "customfield1", true);
echo get_post_meta($post->ID, "customfield2", true);
If you echo a value that is false it will amount to '' (nothing) so you don't have to check if they are set.
And also this works perfect:
<?php
global $post;
$args = array('category' => 37, 'post_type' => 'post' );
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post);
?>
<?php if( get_post_meta($post->ID, "customfield1", true) ): ?>
<?php echo get_post_meta($post->ID, "customfield1", true); ?></span>
<?php endif; ?>
Is anything "wrong" with this code?

Handle two different forms in a single page

So I want to handle two forms on one single page, and I've got some problems to do it; I've got a module named 'contact', here is the indexSucces.php
<div id="registerForm">
<form action="<?php echo url_for('contact'); ?>" method="post" id="loginForm">
<?php foreach ($loginForm as $widget): ?>
<?php if(!$widget->isHidden()) { ?>
<?php echo $widget->renderRow(); ?>
<?php } else { ?>
<?php echo $widget->render() ?>
<?php } ?>
<?php endforeach; ?>
<br/><input type="submit" id="loginSubmit" class="btn primary" value="<?php echo __('Envoyer'); ?>" />
</form>
</div>
<div id="registerForm">
<form action="<?php echo url_for('contact'); ?>" method="post" id="registerForm">
<?php foreach ($registerForm as $widget): ?>
<?php if(!$widget->isHidden()) { ?>
<?php echo $widget->renderRow(); ?>
<?php } else { ?>
<?php echo $widget->render() ?>
<?php } ?>
<?php endforeach; ?>
<br/><input type="submit" id="registerSubmit" class="btn primary" value="<?php echo __('Envoyer'); ?>" />
</form>
</div>
Is it possible to handle that in a single action page ? I need to know the way on how to it, I'm stuck since yesterday. For exemple, when I want to submit the first form, it wants to submit the second form with.
Someone can provide me an exemple ? I can post my sh** action page if you want to see how I tried to handle that.
Thanks in advance !
EDIT:
I made this code according to your advice :
public function executeIndex(sfWebRequest $request)
{
$this->loginForm = new loginForm();
$this->registerForm = new registerForm();
$this->processForm($request, $this->loginForm, $this->registerForm);
}
public function processForm(sfWebRequest $request, sfForm $loginForm, sfForm $registerForm)
{
if($request->hasParameter('login'))
{
if($request->isMethod('post'))
{
$loginForm->bind($request->getParameter($loginForm->getName()));
if($loginForm->isValid())
{
$this->redirect('payement');
}
}
} elseif ($request->hasParameter('register'))
{
if($request->isMethod('post'))
{
$registerForm->bind($request->getParameter($registerForm->getName()));
if($registerForm->isValid())
{
$this->redirect('payement');
}
}
}
}
The registerForm is submitting correctly, I can see the errors I've made in the form etc, and if it's correct, it is correctly redirected. But when I submit the loginForm, here is the error :
Argument 1 passed to sfForm::bind() must be an array, string given : on this line
$loginForm->bind($request->getParameter($loginForm->getName()));
Why ?
Yes, you can.
Add a name attribute to your buttons (i.e. login and register), and modify your action to:
if ($request->hasParameter("login")) {
// handle login
}
elseif ($request->hasParameter("register")) {
// handle register
}

Zend Framework Custom Forms with viewScript

I am having some problems working out how to use custom forms in Zend Framework.
I have followed various guides but none seem to work. Nothing at all gets rendered.
Here is the bits of code that I am trying to use (All code below is in the default module). I have simplified the code to a single input for the test.
applications/forms/One/Nametest.php
class Application_Form_One_Nametest extends Zend_Form {
public function init() {
$this->setMethod('post');
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Box Name')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Submit Message');
$submit->setAttrib('id', 'submitbutton');
$submit->setAttrib('class', 'bluebutton');
$this->addElements(array($name, $submit));
}
}
application/views/scripts/one/formlayout.phtml
<form action="<?= $this->escape($this->form->getAction()) ?>" method="<?= $this->escape($this->form->getMethod()) ?>">
<p>
Please provide us the following information so we can know more about
you.
</p>
<? echo $this->element->name ?>
<? echo $this->element->submit ?>
</form>
application/controllers/IndexController.php
public function formtestAction() {
$form = new Application_Form_One_Nametest();
$form->setDecorators(array(array('ViewScript', array('viewScript' => 'one/formlayout.phtml'))));
$this->view->form = $form;
}
application/views/scripts/index/formtest.phtml
<h1>Formtest</h1>
<?
echo $this->form;
?>
The above code does not throw any errors or render any part of formlayout.phtml including the form tags or text between the p tags.
Can anybody tell me what I might be doing wrong?
I think the problem is your form element's decorator. You should set the decorator to ViewHelper and Error only. It works for me at least.
Here is the code I used and it should work
applications/forms/Form.php
class Application_Form_Form extends Zend_Form {
public function loadDefaultDecorators() {
$this->setDecorators(
array(
array(
'ViewScript',
array(
'viewScript' => 'index/formlayout.phtml',
)
)
)
);
}
public function init() {
$this->setAction('/action');
$this->setMethod('post');
$this->addElement('text', 'name', array(
'decorators' => array('ViewHelper', 'Errors')
));
}
}
application/views/scripts/index/formlayout.phtml
<form action="<?php echo $this->element->getAction(); ?>" method="<?php echo $this->element->getMethod(); ?>">
<div>
<label for="name">Box Name</label>
<?php echo $this->element->name; ?>
</div>
<input type="submit" value="Submit Message" id="submitbutton" class="bluebutton">
</form>
application/views/scripts/index/index.phtml
<!-- application/views/scripts/index/index.phtml -->
<?php echo $this -> form; ?>
application/controllers/IndexController.php
public function indexAction() {
$form = new Application_Form_Form();
$this -> view -> form = $form;
}
Here is a very simple example to get you going adapted from this article.
The form:-
class Application_Form_Test extends Zend_Form
{
public function init()
{
$this->setMethod('POST');
$this->setAction('/');
$text = new Zend_Form_Element_Text('testText');
$submit = new Zend_Form_Element_Submit('submit');
$this->setDecorators(
array(
array('ViewScript', array('viewScript' => '_form_test.phtml'))
)
);
$this->addElements(array($text, $submit));
$this->setElementDecorators(array('ViewHelper'));
}
}
The order in which setDecorators(), addElements() and setElementDecorators() are called is very important here.
The view script _form_test.phtml can be called anything you like, but it needs to be in /views/scripts so that it can be found by the renderer.
/views/scripts/_form_test.phtml would look something like this:-
<form id="contact" action="<?php echo $this->element->getAction(); ?>"
method="<?php echo $this->element->getMethod(); ?>">
<p>
Text<br />
<?php echo $this->element->testText; ?>
</p>
<p>
<?php echo $this->element->submit ?>
</p>
</form>
You instantiate the form, pass it to the view and render it as usual. The output from this example looks like this:-
<form id='contact' action='/' method='post'>
<p>
Text<br />
<input type="text" name="testText" id="testText" value=""></p>
<p>
<input type="submit" name="submit" id="submit" value="submit"></p>
</form>
That should be enough to get you started creating your own forms.
Usually, if you don't see anything on the screen it means that some sort of error happened.
Maybe you have errors turned off or something, maybe not. I'm just trying to give you ideas.
The only things I could spot where the following.
In the below code, you have to still specify the form when trying to print out the elements.
<form>
action="<?php $this->escape($this->element->getAction()) ?>"
method="<?php $this->escape($this->element->getMethod()) ?>" >
<p>
Please provide us the following information so we can know more about
you.
</p>
<?php echo $this->element->getElement( 'name' ); ?>
<?php echo $this->element->getElement( 'submit' ) ?>
</form>
As vascowhite's code shows, once you are inside the viewscript, the variable with the form is called element. The viewscript decorator uses a partial to do the rendering and thus it creates its own scope within the viewscript with different variable names.
So, although in your original view it was called $form, in the viewscript you'll have to call it element.
Also, maybe it was copy/paste haste, but you used <? ?> tags instead of <?= ?> or <?php ?> tags. Maybe that caused some error that is beyond parsing and that's why you got no output.

Creating child CMS pages in Magento

I would like to create a subordinate set of CMS pages in Magento so that the breadcrumb navigation at the top of the page looks like this:
Home > Parent CMS Page > Child CMS Page
Even though I can specify a hierarchical relationship with the URL key field, it seems to be that all CMS pages in Magento are listed in the root directory by default:
Home > Child CMS Page
Any ideas?
You are right, there is no hierarchy of CMS pages in Magento. The best solution would be to create a real hierarchy by adding a parent_id to CMS pages and modifying the CMS module to handle nested URLs and breadcrumbs. But that requires a lot of coding.
A quick-and-dirty hack is to modify the breadcrumbs manually on each subpage by adding something like this to the layout update XML:
<reference name="root">
<action method="unsetChild"><alias>breadcrumbs</alias></action>
<block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs">
<action method="addCrumb">
<crumbName>home</crumbName>
<crumbInfo><label>Home page</label><title>Home page</title><link>/</link></crumbInfo>
</action>
<action method="addCrumb">
<crumbName>myparentpage</crumbName>
<crumbInfo><label>My Parent Page</label><title>My Parent Page</title><link>/myparentpage/</link></crumbInfo>
</action>
<action method="addCrumb">
<crumbName>mysubpage</crumbName>
<crumbInfo><label>My Sub Page</label><title>My Sub Page</title></crumbInfo>
</action>
</block>
</reference>
I had the same problem with breadcrumbs and cms pages a few days ago check here ->
Similar to Anders Rasmussen post I edited every cms page manually
In breadcrumbs.phtml I added a little condition to define if a Page is a CMS page (thanks to Alan Storm) and remove standard crumb(s) and added new crumbs via xmllayout.
<?php
if($this->getRequest()->getModuleName() == 'cms'){
unset($crumbs['cms_page']);
}
?>
xml:
<reference name="breadcrumbs">
<action method="addCrumb">
<crumbName>cms_page_1st_child</crumbName>
<crumbInfo><label>1st child</label><title>1st child</title><link>/1st child/</link></crumbInfo>
</action>
<action method="addCrumb">
<crumbName>cms_page_2nd_child</crumbName>
<crumbInfo><label>2nd child</label><title>2nd child</title></crumbInfo>
</action>
</reference>
hope that helps,
Rito
For enterprise (version 1.12) use this code at following file, location is:
default->template->page->html->breadcrumb.phtml.
<?php
$cms_id = Mage::getSingleton('cms/page')->getPageId();
if($cms_id):
if($_SERVER['REQUEST_URI']) {
$trim_data = substr($_SERVER['REQUEST_URI'],1);
$data = explode('/',$trim_data);
}
$cms_collection = array();
$url_full = '';
$cms_enterprise = '';
foreach($data as $identifier) {
$page_data = Mage::getModel('cms/page')->getCollection()
->addFieldToFilter('identifier', $identifier);
if($page_data) {
foreach($page_data as $single) {
if($single->getContentHeading() != null) {
if($single->getPageId()) {
$cms_enterprise = Mage::getModel('enterprise_cms/hierarchy_node')->getCollection()
->addFieldToFilter('page_id', $single->getPageId());
foreach($cms_enterprise as $single_enterprise) {
$url_full = $single_enterprise->getRequestUrl();
}
}
$cms_collection[] = array($single->getTitle(), $single->getContentHeading(), $url_full );
} else {
if($single->getPageId()) {
$cms_enterprise = Mage::getModel('enterprise_cms/hierarchy_node')->getCollection()
->addFieldToFilter('page_id', $single->getPageId());
foreach($cms_enterprise as $single_enterprise) {
$url_full = $single_enterprise->getRequestUrl();
}
}
$cms_collection[] = array($single->getTitle(), $single->getTitle(), $url_full );
}
}
}
}
$count = count($cms_collection);
$i = 1;
?>
<?php if(count($cms_collection)): ?>
<div class="breadcrumbs">
<ul>
<li>
<a href="<?php echo $this->getUrl() /*Home*/ ?>" title="<?php echo $this->__('Home'); /*Home Title*/ ?>">
<?php echo $this->__('Home'); /*Home Name*/ ?>
</a>
<span>> </span>
</li>
<?php foreach($cms_collection as $key=>$value): ?>
<?php if($i == $count): ?>
<li>
<strong>
<?php echo $value[1]; /*Name*/ ?>
</strong>
</li>
<?php else: ?>
<li>
<a href="<?php echo $this->getUrl().$value[2] /*Identifier*/ ?>" title="<?php echo $value[0] /*Title*/ ?>">
<?php echo $value[1]; /*Name*/ ?>
</a>
<span>> </span>
</li>
<?php endif; ?>
<?php $i++; ?>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php else: ?>
<?php if($crumbs && is_array($crumbs)): ?>
<div class="breadcrumbs">
<ul>
<?php foreach($crumbs as $_crumbName=>$_crumbInfo): ?>
<li class="<?php echo $_crumbName ?>">
<?php if($_crumbInfo['link']): ?>
<?php echo $this->htmlEscape($_crumbInfo['label']) ?>
<?php elseif($_crumbInfo['last']): ?>
<strong><?php echo $this->htmlEscape($_crumbInfo['label']) ?></strong>
<?php else: ?>
<?php echo $this->htmlEscape($_crumbInfo['label']) ?>
<?php endif; ?>
<?php if(!$_crumbInfo['last']): ?>
<span>> </span>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
Thanks,
Kashif
This is my solution of the problem. I use custom layout for most of the CMS pages (default/template/page/cmsLayout.phtml) so I heve added following code into the layout file:
<div class="col-main">
<?php
$urlPart=str_replace(Mage::getUrl(),'',Mage::getUrl('', array('_current' => true,'_use_rewrite' => true)));
$urlPart=explode('/',$urlPart);
$string='';
$return='<div class="breadcrumbs"><ul><li class="home">Home<span> / </span></li>';
$count=count($urlPart);
foreach($urlPart as $value)
{
$count--;
$string.='/'.$value;
$string=trim($string, '/');
$pageTitle = Mage::getModel('cms/page')->load($string, 'identifier')->getTitle();
if($count==0)
$return.='<li><strong>'.$pageTitle.'</strong></li>';
else
$return.='<li>'.$pageTitle.'<span> / </span></li>';
}
echo $return.'</li></ul></div>';
?>
<?php echo $this->getChildHtml('global_messages') ?>
<?php echo $this->getChildHtml('content') ?>
</div>
update
-oops- this might be an enterprise feature only
There is a built-in CMS page hierarchy option in Magento.
To turn it on:
System > Configuration > General > Content Management > CMS Page Hierarchy - see here
To organise the hierarchy tree:
CMS > Pages > Manage Hierarchy
To manage the position of a page in the tree, after saving a page, go to its "hierarchy tab" - see the screenshot:
In the example the page "Our culture" is a child of "jobs" and not of the root directory
For Magento Enterprise, I have created an extension to solve this. It uses the built in CMS Hierarchy in the backend. The module is called Demac/BananaBread and shouldn't require any hacks or customization.
Direct download: here
Link to article: http://www.demacmedia.com/magento-commerce/introducing-demac_bananabread-adding-cms-breadcrumbs-from-the-hierarchy-in-magento/
I built a custom block as to generate the crumbs (removing the built-in and replacing with the custom one below in the layout):
namespace Uprated\Theme\Block\Html;
class UpratedBreadcrumbs extends \Magento\Framework\View\Element\Template
{
/**
* Current template name
*
* #var string
*/
public $crumbs;
protected $_template = 'html/breadcrumbs.phtml';
protected $_urlInterface;
protected $_objectManager;
protected $_repo;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\UrlInterface $urlInterface,
\Magento\Framework\ObjectManagerInterface $objectManager,
array $data = [])
{
$this->_urlInterface = $urlInterface;
$this->_objectManager = $objectManager;
$this->_repo = $this->_objectManager->get('Magento\Cms\Model\PageRepository');
$this->getCrumbs();
parent::__construct($context, $data);
}
public function getCrumbs() {
$baseUrl = $this->_urlInterface->getBaseUrl();
$fullUrl = $this->_urlInterface->getCurrentUrl();
$urlPart = explode('/', str_replace($baseUrl, '', trim($fullUrl, '/')));
//Add in the homepage
$this->crumbs = [
'home' => [
'link' => $baseUrl,
'title' => 'Go to Home Page',
'label' => 'Home',
'last' => ($baseUrl == $fullUrl)
]
];
$path = '';
$numParts = count($urlPart);
$partNum = 1;
foreach($urlPart as $value)
{
//Set the relative path
$path = ($path) ? $path . '/' . $value : $value;
//Get the page
$page = $this->getPageByIdentifier($path);
if($page) {
$this->crumbs[$value] = [
'link' => ($partNum == $numParts) ? false : $baseUrl . $path,
'title' => $page['title'],
'label' => $page['title'],
'last' => ($partNum == $numParts)
];
}
$partNum++;
}
}
protected function getPageByIdentifier($identifier) {
//create the filter
$filter = $this->_objectManager->create('Magento\Framework\Api\Filter');
$filter->setData('field','identifier');
$filter->setData('condition_type','eq');
$filter->setData('value',$identifier);
//add the filter(s) to a group
$filter_group = $this->_objectManager->create('Magento\Framework\Api\Search\FilterGroup');
$filter_group->setData('filters', [$filter]);
//add the group(s) to the search criteria object
$search_criteria = $this->_objectManager->create('Magento\Framework\Api\SearchCriteriaInterface');
$search_criteria->setFilterGroups([$filter_group]);
$pages = $this->_repo->getList($search_criteria);
$pages = ($pages) ? $pages->getItems() : false;
return ($pages && is_array($pages)) ? $pages[0] : [];
}
Then used a slightly modified .phtml template to display them:
<?php if ($block->crumbs && is_array($block->crumbs)) : ?>
<div class="breadcrumbs">
<ul class="items">
<?php foreach ($block->crumbs as $crumbName => $crumbInfo) : ?>
<li class="item <?php /* #escapeNotVerified */ echo $crumbName ?>">
<?php if ($crumbInfo['link']) : ?>
<a href="<?php /* #escapeNotVerified */ echo $crumbInfo['link'] ?>" title="<?php echo $block->escapeHtml($crumbInfo['title']) ?>">
<?php echo $block->escapeHtml($crumbInfo['label']) ?>
</a>
<?php elseif ($crumbInfo['last']) : ?>
<strong><?php echo $block->escapeHtml($crumbInfo['label']) ?></strong>
<?php else: ?>
<?php echo $block->escapeHtml($crumbInfo['label']) ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
Working fine for me in 2.1